blob: b0950ab7e656586ab2735cb5a22c10985951b982 [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner59907c42007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump1eb44332009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattner59907c42007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall2d887082010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattner59907c42007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikiebe0ee872012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenek23245122007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rose3f6f51e2013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000030#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/Initialization.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Richard Smith0e218972013-08-05 18:49:43 +000035#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000036#include "llvm/ADT/SmallString.h"
Richard Smith0e218972013-08-05 18:49:43 +000037#include "llvm/ADT/STLExtras.h"
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +000038#include "llvm/Support/ConvertUTF.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/Support/raw_ostream.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000040#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000041using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000042using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000043
Chris Lattner60800082009-02-18 17:49:48 +000044SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000046 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +000047 PP.getLangOpts(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000048}
49
John McCall8e10f3b2011-02-26 05:39:39 +000050/// Checks that a call expression's argument count is the desired number.
51/// This is useful when doing custom type-checking. Returns true on error.
52static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53 unsigned argCount = call->getNumArgs();
54 if (argCount == desiredArgCount) return false;
55
56 if (argCount < desiredArgCount)
57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58 << 0 /*function call*/ << desiredArgCount << argCount
59 << call->getSourceRange();
60
61 // Highlight all the excess arguments.
62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63 call->getArg(argCount - 1)->getLocEnd());
64
65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66 << 0 /*function call*/ << desiredArgCount << argCount
67 << call->getArg(1)->getSourceRange();
68}
69
Julien Lerougee5939212012-04-28 17:39:16 +000070/// Check that the first argument to __builtin_annotation is an integer
71/// and the second argument is a non-wide string literal.
72static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73 if (checkArgCount(S, TheCall, 2))
74 return true;
75
76 // First argument should be an integer.
77 Expr *ValArg = TheCall->getArg(0);
78 QualType Ty = ValArg->getType();
79 if (!Ty->isIntegerType()) {
80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81 << ValArg->getSourceRange();
Julien Lerouge77f68bb2011-09-09 22:41:49 +000082 return true;
83 }
Julien Lerougee5939212012-04-28 17:39:16 +000084
85 // Second argument should be a constant string.
86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88 if (!Literal || !Literal->isAscii()) {
89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90 << StrArg->getSourceRange();
91 return true;
92 }
93
94 TheCall->setType(Ty);
Julien Lerouge77f68bb2011-09-09 22:41:49 +000095 return false;
96}
97
Richard Smith5154dce2013-07-11 02:27:57 +000098/// Check that the argument to __builtin_addressof is a glvalue, and set the
99/// result type to the corresponding pointer type.
100static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101 if (checkArgCount(S, TheCall, 1))
102 return true;
103
104 ExprResult Arg(S.Owned(TheCall->getArg(0)));
105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
107 return true;
108
109 TheCall->setArg(0, Arg.take());
110 TheCall->setType(ResultType);
111 return false;
112}
113
John McCall60d7b3a2010-08-24 06:29:42 +0000114ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000115Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +0000116 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000117
Chris Lattner946928f2010-10-01 23:23:24 +0000118 // Find out if any arguments are required to be integer constant expressions.
119 unsigned ICEArguments = 0;
120 ASTContext::GetBuiltinTypeError Error;
121 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
122 if (Error != ASTContext::GE_None)
123 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
124
125 // If any arguments are required to be ICE's, check and diagnose.
126 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
127 // Skip arguments not required to be ICE's.
128 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
129
130 llvm::APSInt Result;
131 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
132 return true;
133 ICEArguments &= ~(1 << ArgNo);
134 }
135
Anders Carlssond406bf02009-08-16 01:56:34 +0000136 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000137 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000138 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000139 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000140 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000141 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000142 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000143 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000144 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000145 if (SemaBuiltinVAStart(TheCall))
146 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000147 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000148 case Builtin::BI__builtin_isgreater:
149 case Builtin::BI__builtin_isgreaterequal:
150 case Builtin::BI__builtin_isless:
151 case Builtin::BI__builtin_islessequal:
152 case Builtin::BI__builtin_islessgreater:
153 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000154 if (SemaBuiltinUnorderedCompare(TheCall))
155 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000156 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000157 case Builtin::BI__builtin_fpclassify:
158 if (SemaBuiltinFPClassification(TheCall, 6))
159 return ExprError();
160 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000161 case Builtin::BI__builtin_isfinite:
162 case Builtin::BI__builtin_isinf:
163 case Builtin::BI__builtin_isinf_sign:
164 case Builtin::BI__builtin_isnan:
165 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000166 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000167 return ExprError();
168 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000169 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000170 return SemaBuiltinShuffleVector(TheCall);
171 // TheCall will be freed by the smart pointer here, but that's fine, since
172 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000173 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000174 if (SemaBuiltinPrefetch(TheCall))
175 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000176 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000177 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000178 if (SemaBuiltinObjectSize(TheCall))
179 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000180 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000181 case Builtin::BI__builtin_longjmp:
182 if (SemaBuiltinLongjmp(TheCall))
183 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000184 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000185
186 case Builtin::BI__builtin_classify_type:
187 if (checkArgCount(*this, TheCall, 1)) return true;
188 TheCall->setType(Context.IntTy);
189 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000190 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000191 if (checkArgCount(*this, TheCall, 1)) return true;
192 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000193 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000194 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000195 case Builtin::BI__sync_fetch_and_add_1:
196 case Builtin::BI__sync_fetch_and_add_2:
197 case Builtin::BI__sync_fetch_and_add_4:
198 case Builtin::BI__sync_fetch_and_add_8:
199 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000200 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000201 case Builtin::BI__sync_fetch_and_sub_1:
202 case Builtin::BI__sync_fetch_and_sub_2:
203 case Builtin::BI__sync_fetch_and_sub_4:
204 case Builtin::BI__sync_fetch_and_sub_8:
205 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000206 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000207 case Builtin::BI__sync_fetch_and_or_1:
208 case Builtin::BI__sync_fetch_and_or_2:
209 case Builtin::BI__sync_fetch_and_or_4:
210 case Builtin::BI__sync_fetch_and_or_8:
211 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000212 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000213 case Builtin::BI__sync_fetch_and_and_1:
214 case Builtin::BI__sync_fetch_and_and_2:
215 case Builtin::BI__sync_fetch_and_and_4:
216 case Builtin::BI__sync_fetch_and_and_8:
217 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000218 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000219 case Builtin::BI__sync_fetch_and_xor_1:
220 case Builtin::BI__sync_fetch_and_xor_2:
221 case Builtin::BI__sync_fetch_and_xor_4:
222 case Builtin::BI__sync_fetch_and_xor_8:
223 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000224 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000225 case Builtin::BI__sync_add_and_fetch_1:
226 case Builtin::BI__sync_add_and_fetch_2:
227 case Builtin::BI__sync_add_and_fetch_4:
228 case Builtin::BI__sync_add_and_fetch_8:
229 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000230 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000231 case Builtin::BI__sync_sub_and_fetch_1:
232 case Builtin::BI__sync_sub_and_fetch_2:
233 case Builtin::BI__sync_sub_and_fetch_4:
234 case Builtin::BI__sync_sub_and_fetch_8:
235 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000236 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000237 case Builtin::BI__sync_and_and_fetch_1:
238 case Builtin::BI__sync_and_and_fetch_2:
239 case Builtin::BI__sync_and_and_fetch_4:
240 case Builtin::BI__sync_and_and_fetch_8:
241 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000242 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000243 case Builtin::BI__sync_or_and_fetch_1:
244 case Builtin::BI__sync_or_and_fetch_2:
245 case Builtin::BI__sync_or_and_fetch_4:
246 case Builtin::BI__sync_or_and_fetch_8:
247 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000248 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000249 case Builtin::BI__sync_xor_and_fetch_1:
250 case Builtin::BI__sync_xor_and_fetch_2:
251 case Builtin::BI__sync_xor_and_fetch_4:
252 case Builtin::BI__sync_xor_and_fetch_8:
253 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000254 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000255 case Builtin::BI__sync_val_compare_and_swap_1:
256 case Builtin::BI__sync_val_compare_and_swap_2:
257 case Builtin::BI__sync_val_compare_and_swap_4:
258 case Builtin::BI__sync_val_compare_and_swap_8:
259 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000260 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000261 case Builtin::BI__sync_bool_compare_and_swap_1:
262 case Builtin::BI__sync_bool_compare_and_swap_2:
263 case Builtin::BI__sync_bool_compare_and_swap_4:
264 case Builtin::BI__sync_bool_compare_and_swap_8:
265 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000266 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000267 case Builtin::BI__sync_lock_test_and_set_1:
268 case Builtin::BI__sync_lock_test_and_set_2:
269 case Builtin::BI__sync_lock_test_and_set_4:
270 case Builtin::BI__sync_lock_test_and_set_8:
271 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000272 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000273 case Builtin::BI__sync_lock_release_1:
274 case Builtin::BI__sync_lock_release_2:
275 case Builtin::BI__sync_lock_release_4:
276 case Builtin::BI__sync_lock_release_8:
277 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000278 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000279 case Builtin::BI__sync_swap_1:
280 case Builtin::BI__sync_swap_2:
281 case Builtin::BI__sync_swap_4:
282 case Builtin::BI__sync_swap_8:
283 case Builtin::BI__sync_swap_16:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000284 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithff34d402012-04-12 05:08:17 +0000285#define BUILTIN(ID, TYPE, ATTRS)
286#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
287 case Builtin::BI##ID: \
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000288 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithff34d402012-04-12 05:08:17 +0000289#include "clang/Basic/Builtins.def"
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000290 case Builtin::BI__builtin_annotation:
Julien Lerougee5939212012-04-28 17:39:16 +0000291 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000292 return ExprError();
293 break;
Richard Smith5154dce2013-07-11 02:27:57 +0000294 case Builtin::BI__builtin_addressof:
295 if (SemaBuiltinAddressof(*this, TheCall))
296 return ExprError();
297 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000298 }
299
300 // Since the target specific builtins for each arch overlap, only check those
301 // of the arch we are compiling for.
302 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000303 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000304 case llvm::Triple::arm:
305 case llvm::Triple::thumb:
306 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
307 return ExprError();
308 break;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000309 case llvm::Triple::aarch64:
310 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
311 return ExprError();
312 break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000313 case llvm::Triple::mips:
314 case llvm::Triple::mipsel:
315 case llvm::Triple::mips64:
316 case llvm::Triple::mips64el:
317 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
318 return ExprError();
319 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000320 default:
321 break;
322 }
323 }
324
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000325 return TheCallResult;
Nate Begeman26a31422010-06-08 02:47:44 +0000326}
327
Nate Begeman61eecf52010-06-14 05:21:25 +0000328// Get the valid immediate range for the specified NEON type code.
329static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000330 NeonTypeFlags Type(t);
331 int IsQuad = Type.isQuad();
332 switch (Type.getEltType()) {
333 case NeonTypeFlags::Int8:
334 case NeonTypeFlags::Poly8:
335 return shift ? 7 : (8 << IsQuad) - 1;
336 case NeonTypeFlags::Int16:
337 case NeonTypeFlags::Poly16:
338 return shift ? 15 : (4 << IsQuad) - 1;
339 case NeonTypeFlags::Int32:
340 return shift ? 31 : (2 << IsQuad) - 1;
341 case NeonTypeFlags::Int64:
342 return shift ? 63 : (1 << IsQuad) - 1;
343 case NeonTypeFlags::Float16:
344 assert(!shift && "cannot shift float types!");
345 return (4 << IsQuad) - 1;
346 case NeonTypeFlags::Float32:
347 assert(!shift && "cannot shift float types!");
348 return (2 << IsQuad) - 1;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000349 case NeonTypeFlags::Float64:
350 assert(!shift && "cannot shift float types!");
351 return (1 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000352 }
David Blaikie7530c032012-01-17 06:56:22 +0000353 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000354}
355
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000356/// getNeonEltType - Return the QualType corresponding to the elements of
357/// the vector type specified by the NeonTypeFlags. This is used to check
358/// the pointer arguments for Neon load/store intrinsics.
359static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
360 switch (Flags.getEltType()) {
361 case NeonTypeFlags::Int8:
362 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
363 case NeonTypeFlags::Int16:
364 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
365 case NeonTypeFlags::Int32:
366 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
367 case NeonTypeFlags::Int64:
368 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
369 case NeonTypeFlags::Poly8:
370 return Context.SignedCharTy;
371 case NeonTypeFlags::Poly16:
372 return Context.ShortTy;
373 case NeonTypeFlags::Float16:
374 return Context.UnsignedShortTy;
375 case NeonTypeFlags::Float32:
376 return Context.FloatTy;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000377 case NeonTypeFlags::Float64:
378 return Context.DoubleTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000379 }
David Blaikie7530c032012-01-17 06:56:22 +0000380 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000381}
382
Tim Northoverb793f0d2013-08-01 09:23:19 +0000383bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
384 CallExpr *TheCall) {
385
386 llvm::APSInt Result;
387
388 uint64_t mask = 0;
389 unsigned TV = 0;
390 int PtrArgNum = -1;
391 bool HasConstPtr = false;
392 switch (BuiltinID) {
393#define GET_NEON_AARCH64_OVERLOAD_CHECK
394#include "clang/Basic/arm_neon.inc"
395#undef GET_NEON_AARCH64_OVERLOAD_CHECK
396 }
397
398 // For NEON intrinsics which are overloaded on vector element type, validate
399 // the immediate which specifies which variant to emit.
400 unsigned ImmArg = TheCall->getNumArgs() - 1;
401 if (mask) {
402 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
403 return true;
404
405 TV = Result.getLimitedValue(64);
406 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
407 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
408 << TheCall->getArg(ImmArg)->getSourceRange();
409 }
410
411 if (PtrArgNum >= 0) {
412 // Check that pointer arguments have the specified type.
413 Expr *Arg = TheCall->getArg(PtrArgNum);
414 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
415 Arg = ICE->getSubExpr();
416 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
417 QualType RHSTy = RHS.get()->getType();
418 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
419 if (HasConstPtr)
420 EltTy = EltTy.withConst();
421 QualType LHSTy = Context.getPointerType(EltTy);
422 AssignConvertType ConvTy;
423 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
424 if (RHS.isInvalid())
425 return true;
426 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
427 RHS.get(), AA_Assigning))
428 return true;
429 }
430
431 // For NEON intrinsics which take an immediate value as part of the
432 // instruction, range check them here.
433 unsigned i = 0, l = 0, u = 0;
434 switch (BuiltinID) {
435 default:
436 return false;
437#define GET_NEON_AARCH64_IMMEDIATE_CHECK
438#include "clang/Basic/arm_neon.inc"
439#undef GET_NEON_AARCH64_IMMEDIATE_CHECK
440 }
441 ;
442
443 // We can't check the value of a dependent argument.
444 if (TheCall->getArg(i)->isTypeDependent() ||
445 TheCall->getArg(i)->isValueDependent())
446 return false;
447
448 // Check that the immediate argument is actually a constant.
449 if (SemaBuiltinConstantArg(TheCall, i, Result))
450 return true;
451
452 // Range check against the upper/lower values for this isntruction.
453 unsigned Val = Result.getZExtValue();
454 if (Val < l || Val > (u + l))
455 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
456 << l << u + l << TheCall->getArg(i)->getSourceRange();
457
458 return false;
459}
460
Tim Northover09df2b02013-07-16 09:47:53 +0000461bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall) {
462 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
463 BuiltinID == ARM::BI__builtin_arm_strex) &&
464 "unexpected ARM builtin");
465 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex;
466
467 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
468
469 // Ensure that we have the proper number of arguments.
470 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
471 return true;
472
473 // Inspect the pointer argument of the atomic builtin. This should always be
474 // a pointer type, whose element is an integral scalar or pointer type.
475 // Because it is a pointer type, we don't have to worry about any implicit
476 // casts here.
477 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
478 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
479 if (PointerArgRes.isInvalid())
480 return true;
481 PointerArg = PointerArgRes.take();
482
483 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
484 if (!pointerType) {
485 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
486 << PointerArg->getType() << PointerArg->getSourceRange();
487 return true;
488 }
489
490 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
491 // task is to insert the appropriate casts into the AST. First work out just
492 // what the appropriate type is.
493 QualType ValType = pointerType->getPointeeType();
494 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
495 if (IsLdrex)
496 AddrType.addConst();
497
498 // Issue a warning if the cast is dodgy.
499 CastKind CastNeeded = CK_NoOp;
500 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
501 CastNeeded = CK_BitCast;
502 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
503 << PointerArg->getType()
504 << Context.getPointerType(AddrType)
505 << AA_Passing << PointerArg->getSourceRange();
506 }
507
508 // Finally, do the cast and replace the argument with the corrected version.
509 AddrType = Context.getPointerType(AddrType);
510 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
511 if (PointerArgRes.isInvalid())
512 return true;
513 PointerArg = PointerArgRes.take();
514
515 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
516
517 // In general, we allow ints, floats and pointers to be loaded and stored.
518 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
519 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
520 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
521 << PointerArg->getType() << PointerArg->getSourceRange();
522 return true;
523 }
524
525 // But ARM doesn't have instructions to deal with 128-bit versions.
526 if (Context.getTypeSize(ValType) > 64) {
527 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
528 << PointerArg->getType() << PointerArg->getSourceRange();
529 return true;
530 }
531
532 switch (ValType.getObjCLifetime()) {
533 case Qualifiers::OCL_None:
534 case Qualifiers::OCL_ExplicitNone:
535 // okay
536 break;
537
538 case Qualifiers::OCL_Weak:
539 case Qualifiers::OCL_Strong:
540 case Qualifiers::OCL_Autoreleasing:
541 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
542 << ValType << PointerArg->getSourceRange();
543 return true;
544 }
545
546
547 if (IsLdrex) {
548 TheCall->setType(ValType);
549 return false;
550 }
551
552 // Initialize the argument to be stored.
553 ExprResult ValArg = TheCall->getArg(0);
554 InitializedEntity Entity = InitializedEntity::InitializeParameter(
555 Context, ValType, /*consume*/ false);
556 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
557 if (ValArg.isInvalid())
558 return true;
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) {
Richard Smith0e218972013-08-05 18:49:43 +0000712 // FIXME: We should check as much as we can in the template definition.
Jordan Rose66360e22012-10-02 01:49:54 +0000713 if (CurContext->isDependentContext())
714 return;
Daniel Dunbarde454282008-10-02 18:44:07 +0000715
Ted Kremenekc82faca2010-09-09 04:33:05 +0000716 // Printf and scanf checking.
Richard Smith0e218972013-08-05 18:49:43 +0000717 llvm::SmallBitVector CheckedVarArgs;
718 if (FDecl) {
Richard Trieu0538f0e2013-06-22 00:20:41 +0000719 for (specific_attr_iterator<FormatAttr>
Benjamin Kramer47abb252013-08-08 11:08:26 +0000720 I = FDecl->specific_attr_begin<FormatAttr>(),
721 E = FDecl->specific_attr_end<FormatAttr>();
Benjamin Kramer541a28f2013-08-09 09:39:17 +0000722 I != E; ++I) {
723 // Only create vector if there are format attributes.
724 CheckedVarArgs.resize(Args.size());
725
Benjamin Kramer47abb252013-08-08 11:08:26 +0000726 CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc, Range,
727 CheckedVarArgs);
Benjamin Kramer541a28f2013-08-09 09:39:17 +0000728 }
Richard Smith0e218972013-08-05 18:49:43 +0000729 }
Richard Smith831421f2012-06-25 20:30:08 +0000730
731 // Refuse POD arguments that weren't caught by the format string
732 // checks above.
Richard Smith0e218972013-08-05 18:49:43 +0000733 if (CallType != VariadicDoesNotApply) {
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000734 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000735 // Args[ArgIdx] can be null in malformed code.
Richard Smith0e218972013-08-05 18:49:43 +0000736 if (const Expr *Arg = Args[ArgIdx]) {
737 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
738 checkVariadicArgument(Arg, CallType);
739 }
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000740 }
Richard Smith0e218972013-08-05 18:49:43 +0000741 }
Mike Stump1eb44332009-09-09 15:08:12 +0000742
Richard Trieu0538f0e2013-06-22 00:20:41 +0000743 if (FDecl) {
744 for (specific_attr_iterator<NonNullAttr>
745 I = FDecl->specific_attr_begin<NonNullAttr>(),
746 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
747 CheckNonNullArguments(*I, Args.data(), Loc);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000748
Richard Trieu0538f0e2013-06-22 00:20:41 +0000749 // Type safety checking.
750 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
751 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
752 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>();
753 i != e; ++i) {
754 CheckArgumentWithTypeTag(*i, Args.data());
755 }
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000756 }
Richard Smith831421f2012-06-25 20:30:08 +0000757}
758
759/// CheckConstructorCall - Check a constructor call for correctness and safety
760/// properties not enforced by the C type system.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000761void Sema::CheckConstructorCall(FunctionDecl *FDecl,
762 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000763 const FunctionProtoType *Proto,
764 SourceLocation Loc) {
765 VariadicCallType CallType =
766 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000767 checkCall(FDecl, Args, Proto->getNumArgs(),
Richard Smith831421f2012-06-25 20:30:08 +0000768 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
769}
770
771/// CheckFunctionCall - Check a direct function call for various correctness
772/// and safety properties not strictly enforced by the C type system.
773bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
774 const FunctionProtoType *Proto) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000775 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
776 isa<CXXMethodDecl>(FDecl);
777 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
778 IsMemberOperatorCall;
Richard Smith831421f2012-06-25 20:30:08 +0000779 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
780 TheCall->getCallee());
781 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Eli Friedman2edcde82012-10-11 00:30:58 +0000782 Expr** Args = TheCall->getArgs();
783 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmandf75b0c2012-10-11 00:34:15 +0000784 if (IsMemberOperatorCall) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000785 // If this is a call to a member operator, hide the first argument
786 // from checkCall.
787 // FIXME: Our choice of AST representation here is less than ideal.
788 ++Args;
789 --NumArgs;
790 }
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000791 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs),
792 NumProtoArgs,
Richard Smith831421f2012-06-25 20:30:08 +0000793 IsMemberFunction, TheCall->getRParenLoc(),
794 TheCall->getCallee()->getSourceRange(), CallType);
795
796 IdentifierInfo *FnInfo = FDecl->getIdentifier();
797 // None of the checks below are needed for functions that don't have
798 // simple names (e.g., C++ conversion functions).
799 if (!FnInfo)
800 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +0000801
Anna Zaks0a151a12012-01-17 00:37:07 +0000802 unsigned CMId = FDecl->getMemoryFunctionKind();
803 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000804 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000805
Anna Zaksd9b859a2012-01-13 21:52:01 +0000806 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000807 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000808 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000809 else if (CMId == Builtin::BIstrncat)
810 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000811 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000812 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000813
Anders Carlssond406bf02009-08-16 01:56:34 +0000814 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000815}
816
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000817bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000818 ArrayRef<const Expr *> Args) {
Richard Smith831421f2012-06-25 20:30:08 +0000819 VariadicCallType CallType =
820 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000821
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000822 checkCall(Method, Args, Method->param_size(),
Richard Smith831421f2012-06-25 20:30:08 +0000823 /*IsMemberFunction=*/false,
824 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000825
826 return false;
827}
828
Richard Trieuf462b012013-06-20 21:03:13 +0000829bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
830 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000831 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
832 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000833 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000834
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000835 QualType Ty = V->getType();
Richard Trieuf462b012013-06-20 21:03:13 +0000836 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000837 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Richard Trieuf462b012013-06-20 21:03:13 +0000839 VariadicCallType CallType;
Richard Trieua4993772013-06-20 23:21:54 +0000840 if (!Proto || !Proto->isVariadic()) {
Richard Trieuf462b012013-06-20 21:03:13 +0000841 CallType = VariadicDoesNotApply;
842 } else if (Ty->isBlockPointerType()) {
843 CallType = VariadicBlock;
844 } else { // Ty->isFunctionPointerType()
845 CallType = VariadicFunction;
846 }
Richard Smith831421f2012-06-25 20:30:08 +0000847 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000848
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000849 checkCall(NDecl,
850 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
851 TheCall->getNumArgs()),
Richard Smith831421f2012-06-25 20:30:08 +0000852 NumProtoArgs, /*IsMemberFunction=*/false,
853 TheCall->getRParenLoc(),
854 TheCall->getCallee()->getSourceRange(), CallType);
855
Anders Carlssond406bf02009-08-16 01:56:34 +0000856 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000857}
858
Richard Trieu0538f0e2013-06-22 00:20:41 +0000859/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
860/// such as function pointers returned from functions.
861bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
862 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
863 TheCall->getCallee());
864 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
865
866 checkCall(/*FDecl=*/0,
867 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
868 TheCall->getNumArgs()),
869 NumProtoArgs, /*IsMemberFunction=*/false,
870 TheCall->getRParenLoc(),
871 TheCall->getCallee()->getSourceRange(), CallType);
872
873 return false;
874}
875
Richard Smithff34d402012-04-12 05:08:17 +0000876ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
877 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000878 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
879 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000880
Richard Smithff34d402012-04-12 05:08:17 +0000881 // All these operations take one of the following forms:
882 enum {
883 // C __c11_atomic_init(A *, C)
884 Init,
885 // C __c11_atomic_load(A *, int)
886 Load,
887 // void __atomic_load(A *, CP, int)
888 Copy,
889 // C __c11_atomic_add(A *, M, int)
890 Arithmetic,
891 // C __atomic_exchange_n(A *, CP, int)
892 Xchg,
893 // void __atomic_exchange(A *, C *, CP, int)
894 GNUXchg,
895 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
896 C11CmpXchg,
897 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
898 GNUCmpXchg
899 } Form = Init;
900 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
901 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
902 // where:
903 // C is an appropriate type,
904 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
905 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
906 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
907 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000908
Richard Smithff34d402012-04-12 05:08:17 +0000909 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
910 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
911 && "need to update code for modified C11 atomics");
912 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
913 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
914 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
915 Op == AtomicExpr::AO__atomic_store_n ||
916 Op == AtomicExpr::AO__atomic_exchange_n ||
917 Op == AtomicExpr::AO__atomic_compare_exchange_n;
918 bool IsAddSub = false;
919
920 switch (Op) {
921 case AtomicExpr::AO__c11_atomic_init:
922 Form = Init;
923 break;
924
925 case AtomicExpr::AO__c11_atomic_load:
926 case AtomicExpr::AO__atomic_load_n:
927 Form = Load;
928 break;
929
930 case AtomicExpr::AO__c11_atomic_store:
931 case AtomicExpr::AO__atomic_load:
932 case AtomicExpr::AO__atomic_store:
933 case AtomicExpr::AO__atomic_store_n:
934 Form = Copy;
935 break;
936
937 case AtomicExpr::AO__c11_atomic_fetch_add:
938 case AtomicExpr::AO__c11_atomic_fetch_sub:
939 case AtomicExpr::AO__atomic_fetch_add:
940 case AtomicExpr::AO__atomic_fetch_sub:
941 case AtomicExpr::AO__atomic_add_fetch:
942 case AtomicExpr::AO__atomic_sub_fetch:
943 IsAddSub = true;
944 // Fall through.
945 case AtomicExpr::AO__c11_atomic_fetch_and:
946 case AtomicExpr::AO__c11_atomic_fetch_or:
947 case AtomicExpr::AO__c11_atomic_fetch_xor:
948 case AtomicExpr::AO__atomic_fetch_and:
949 case AtomicExpr::AO__atomic_fetch_or:
950 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000951 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000952 case AtomicExpr::AO__atomic_and_fetch:
953 case AtomicExpr::AO__atomic_or_fetch:
954 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000955 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000956 Form = Arithmetic;
957 break;
958
959 case AtomicExpr::AO__c11_atomic_exchange:
960 case AtomicExpr::AO__atomic_exchange_n:
961 Form = Xchg;
962 break;
963
964 case AtomicExpr::AO__atomic_exchange:
965 Form = GNUXchg;
966 break;
967
968 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
969 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
970 Form = C11CmpXchg;
971 break;
972
973 case AtomicExpr::AO__atomic_compare_exchange:
974 case AtomicExpr::AO__atomic_compare_exchange_n:
975 Form = GNUCmpXchg;
976 break;
977 }
978
979 // Check we have the right number of arguments.
980 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000981 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000982 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000983 << TheCall->getCallee()->getSourceRange();
984 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000985 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
986 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000987 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000988 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000989 << TheCall->getCallee()->getSourceRange();
990 return ExprError();
991 }
992
Richard Smithff34d402012-04-12 05:08:17 +0000993 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000994 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000995 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
996 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
997 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +0000998 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +0000999 << Ptr->getType() << Ptr->getSourceRange();
1000 return ExprError();
1001 }
1002
Richard Smithff34d402012-04-12 05:08:17 +00001003 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1004 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1005 QualType ValType = AtomTy; // 'C'
1006 if (IsC11) {
1007 if (!AtomTy->isAtomicType()) {
1008 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1009 << Ptr->getType() << Ptr->getSourceRange();
1010 return ExprError();
1011 }
Richard Smithbc57b102012-09-15 06:09:58 +00001012 if (AtomTy.isConstQualified()) {
1013 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1014 << Ptr->getType() << Ptr->getSourceRange();
1015 return ExprError();
1016 }
Richard Smithff34d402012-04-12 05:08:17 +00001017 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +00001018 }
Eli Friedman276b0612011-10-11 02:20:01 +00001019
Richard Smithff34d402012-04-12 05:08:17 +00001020 // For an arithmetic operation, the implied arithmetic must be well-formed.
1021 if (Form == Arithmetic) {
1022 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1023 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1024 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1025 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1026 return ExprError();
1027 }
1028 if (!IsAddSub && !ValType->isIntegerType()) {
1029 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1030 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1031 return ExprError();
1032 }
1033 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1034 // For __atomic_*_n operations, the value type must be a scalar integral or
1035 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +00001036 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +00001037 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1038 return ExprError();
1039 }
1040
Eli Friedmana3d727b2013-09-11 03:49:34 +00001041 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1042 !AtomTy->isScalarType()) {
Richard Smithff34d402012-04-12 05:08:17 +00001043 // For GNU atomics, require a trivially-copyable type. This is not part of
1044 // the GNU atomics specification, but we enforce it for sanity.
1045 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +00001046 << Ptr->getType() << Ptr->getSourceRange();
1047 return ExprError();
1048 }
1049
Richard Smithff34d402012-04-12 05:08:17 +00001050 // FIXME: For any builtin other than a load, the ValType must not be
1051 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +00001052
1053 switch (ValType.getObjCLifetime()) {
1054 case Qualifiers::OCL_None:
1055 case Qualifiers::OCL_ExplicitNone:
1056 // okay
1057 break;
1058
1059 case Qualifiers::OCL_Weak:
1060 case Qualifiers::OCL_Strong:
1061 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +00001062 // FIXME: Can this happen? By this point, ValType should be known
1063 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +00001064 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1065 << ValType << Ptr->getSourceRange();
1066 return ExprError();
1067 }
1068
1069 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +00001070 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +00001071 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +00001072 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +00001073 ResultType = Context.BoolTy;
1074
Richard Smithff34d402012-04-12 05:08:17 +00001075 // The type of a parameter passed 'by value'. In the GNU atomics, such
1076 // arguments are actually passed as pointers.
1077 QualType ByValType = ValType; // 'CP'
1078 if (!IsC11 && !IsN)
1079 ByValType = Ptr->getType();
1080
Eli Friedman276b0612011-10-11 02:20:01 +00001081 // The first argument --- the pointer --- has a fixed type; we
1082 // deduce the types of the rest of the arguments accordingly. Walk
1083 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +00001084 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +00001085 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +00001086 if (i < NumVals[Form] + 1) {
1087 switch (i) {
1088 case 1:
1089 // The second argument is the non-atomic operand. For arithmetic, this
1090 // is always passed by value, and for a compare_exchange it is always
1091 // passed by address. For the rest, GNU uses by-address and C11 uses
1092 // by-value.
1093 assert(Form != Load);
1094 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1095 Ty = ValType;
1096 else if (Form == Copy || Form == Xchg)
1097 Ty = ByValType;
1098 else if (Form == Arithmetic)
1099 Ty = Context.getPointerDiffType();
1100 else
1101 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1102 break;
1103 case 2:
1104 // The third argument to compare_exchange / GNU exchange is a
1105 // (pointer to a) desired value.
1106 Ty = ByValType;
1107 break;
1108 case 3:
1109 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1110 Ty = Context.BoolTy;
1111 break;
1112 }
Eli Friedman276b0612011-10-11 02:20:01 +00001113 } else {
1114 // The order(s) are always converted to int.
1115 Ty = Context.IntTy;
1116 }
Richard Smithff34d402012-04-12 05:08:17 +00001117
Eli Friedman276b0612011-10-11 02:20:01 +00001118 InitializedEntity Entity =
1119 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +00001120 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +00001121 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1122 if (Arg.isInvalid())
1123 return true;
1124 TheCall->setArg(i, Arg.get());
1125 }
1126
Richard Smithff34d402012-04-12 05:08:17 +00001127 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001128 SmallVector<Expr*, 5> SubExprs;
1129 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +00001130 switch (Form) {
1131 case Init:
1132 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +00001133 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001134 break;
1135 case Load:
1136 SubExprs.push_back(TheCall->getArg(1)); // Order
1137 break;
1138 case Copy:
1139 case Arithmetic:
1140 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001141 SubExprs.push_back(TheCall->getArg(2)); // Order
1142 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001143 break;
1144 case GNUXchg:
1145 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1146 SubExprs.push_back(TheCall->getArg(3)); // Order
1147 SubExprs.push_back(TheCall->getArg(1)); // Val1
1148 SubExprs.push_back(TheCall->getArg(2)); // Val2
1149 break;
1150 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001151 SubExprs.push_back(TheCall->getArg(3)); // Order
1152 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001153 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +00001154 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +00001155 break;
1156 case GNUCmpXchg:
1157 SubExprs.push_back(TheCall->getArg(4)); // Order
1158 SubExprs.push_back(TheCall->getArg(1)); // Val1
1159 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1160 SubExprs.push_back(TheCall->getArg(2)); // Val2
1161 SubExprs.push_back(TheCall->getArg(3)); // Weak
1162 break;
Eli Friedman276b0612011-10-11 02:20:01 +00001163 }
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00001164
1165 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1166 SubExprs, ResultType, Op,
1167 TheCall->getRParenLoc());
1168
1169 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1170 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1171 Context.AtomicUsesUnsupportedLibcall(AE))
1172 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1173 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001174
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00001175 return Owned(AE);
Eli Friedman276b0612011-10-11 02:20:01 +00001176}
1177
1178
John McCall5f8d6042011-08-27 01:09:30 +00001179/// checkBuiltinArgument - Given a call to a builtin function, perform
1180/// normal type-checking on the given argument, updating the call in
1181/// place. This is useful when a builtin function requires custom
1182/// type-checking for some of its arguments but not necessarily all of
1183/// them.
1184///
1185/// Returns true on error.
1186static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1187 FunctionDecl *Fn = E->getDirectCallee();
1188 assert(Fn && "builtin call without direct callee!");
1189
1190 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1191 InitializedEntity Entity =
1192 InitializedEntity::InitializeParameter(S.Context, Param);
1193
1194 ExprResult Arg = E->getArg(0);
1195 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1196 if (Arg.isInvalid())
1197 return true;
1198
1199 E->setArg(ArgIndex, Arg.take());
1200 return false;
1201}
1202
Chris Lattner5caa3702009-05-08 06:58:22 +00001203/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1204/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1205/// type of its first argument. The main ActOnCallExpr routines have already
1206/// promoted the types of arguments because all of these calls are prototyped as
1207/// void(...).
1208///
1209/// This function goes through and does final semantic checking for these
1210/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +00001211ExprResult
1212Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001213 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +00001214 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1215 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1216
1217 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +00001218 if (TheCall->getNumArgs() < 1) {
1219 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1220 << 0 << 1 << TheCall->getNumArgs()
1221 << TheCall->getCallee()->getSourceRange();
1222 return ExprError();
1223 }
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Chris Lattner5caa3702009-05-08 06:58:22 +00001225 // Inspect the first argument of the atomic builtin. This should always be
1226 // a pointer type, whose element is an integral scalar or pointer type.
1227 // Because it is a pointer type, we don't have to worry about any implicit
1228 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +00001229 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +00001230 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +00001231 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1232 if (FirstArgResult.isInvalid())
1233 return ExprError();
1234 FirstArg = FirstArgResult.take();
1235 TheCall->setArg(0, FirstArg);
1236
John McCallf85e1932011-06-15 23:02:42 +00001237 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1238 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001239 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1240 << FirstArg->getType() << FirstArg->getSourceRange();
1241 return ExprError();
1242 }
Mike Stump1eb44332009-09-09 15:08:12 +00001243
John McCallf85e1932011-06-15 23:02:42 +00001244 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +00001245 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +00001246 !ValType->isBlockPointerType()) {
1247 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1248 << FirstArg->getType() << FirstArg->getSourceRange();
1249 return ExprError();
1250 }
Chris Lattner5caa3702009-05-08 06:58:22 +00001251
John McCallf85e1932011-06-15 23:02:42 +00001252 switch (ValType.getObjCLifetime()) {
1253 case Qualifiers::OCL_None:
1254 case Qualifiers::OCL_ExplicitNone:
1255 // okay
1256 break;
1257
1258 case Qualifiers::OCL_Weak:
1259 case Qualifiers::OCL_Strong:
1260 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001261 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001262 << ValType << FirstArg->getSourceRange();
1263 return ExprError();
1264 }
1265
John McCallb45ae252011-10-05 07:41:44 +00001266 // Strip any qualifiers off ValType.
1267 ValType = ValType.getUnqualifiedType();
1268
Chandler Carruth8d13d222010-07-18 20:54:12 +00001269 // The majority of builtins return a value, but a few have special return
1270 // types, so allow them to override appropriately below.
1271 QualType ResultType = ValType;
1272
Chris Lattner5caa3702009-05-08 06:58:22 +00001273 // We need to figure out which concrete builtin this maps onto. For example,
1274 // __sync_fetch_and_add with a 2 byte object turns into
1275 // __sync_fetch_and_add_2.
1276#define BUILTIN_ROW(x) \
1277 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1278 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +00001279
Chris Lattner5caa3702009-05-08 06:58:22 +00001280 static const unsigned BuiltinIndices[][5] = {
1281 BUILTIN_ROW(__sync_fetch_and_add),
1282 BUILTIN_ROW(__sync_fetch_and_sub),
1283 BUILTIN_ROW(__sync_fetch_and_or),
1284 BUILTIN_ROW(__sync_fetch_and_and),
1285 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +00001286
Chris Lattner5caa3702009-05-08 06:58:22 +00001287 BUILTIN_ROW(__sync_add_and_fetch),
1288 BUILTIN_ROW(__sync_sub_and_fetch),
1289 BUILTIN_ROW(__sync_and_and_fetch),
1290 BUILTIN_ROW(__sync_or_and_fetch),
1291 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001292
Chris Lattner5caa3702009-05-08 06:58:22 +00001293 BUILTIN_ROW(__sync_val_compare_and_swap),
1294 BUILTIN_ROW(__sync_bool_compare_and_swap),
1295 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001296 BUILTIN_ROW(__sync_lock_release),
1297 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001298 };
Mike Stump1eb44332009-09-09 15:08:12 +00001299#undef BUILTIN_ROW
1300
Chris Lattner5caa3702009-05-08 06:58:22 +00001301 // Determine the index of the size.
1302 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001303 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001304 case 1: SizeIndex = 0; break;
1305 case 2: SizeIndex = 1; break;
1306 case 4: SizeIndex = 2; break;
1307 case 8: SizeIndex = 3; break;
1308 case 16: SizeIndex = 4; break;
1309 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001310 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1311 << FirstArg->getType() << FirstArg->getSourceRange();
1312 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001313 }
Mike Stump1eb44332009-09-09 15:08:12 +00001314
Chris Lattner5caa3702009-05-08 06:58:22 +00001315 // Each of these builtins has one pointer argument, followed by some number of
1316 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1317 // that we ignore. Find out which row of BuiltinIndices to read from as well
1318 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001319 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001320 unsigned BuiltinIndex, NumFixed = 1;
1321 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001322 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001323 case Builtin::BI__sync_fetch_and_add:
1324 case Builtin::BI__sync_fetch_and_add_1:
1325 case Builtin::BI__sync_fetch_and_add_2:
1326 case Builtin::BI__sync_fetch_and_add_4:
1327 case Builtin::BI__sync_fetch_and_add_8:
1328 case Builtin::BI__sync_fetch_and_add_16:
1329 BuiltinIndex = 0;
1330 break;
1331
1332 case Builtin::BI__sync_fetch_and_sub:
1333 case Builtin::BI__sync_fetch_and_sub_1:
1334 case Builtin::BI__sync_fetch_and_sub_2:
1335 case Builtin::BI__sync_fetch_and_sub_4:
1336 case Builtin::BI__sync_fetch_and_sub_8:
1337 case Builtin::BI__sync_fetch_and_sub_16:
1338 BuiltinIndex = 1;
1339 break;
1340
1341 case Builtin::BI__sync_fetch_and_or:
1342 case Builtin::BI__sync_fetch_and_or_1:
1343 case Builtin::BI__sync_fetch_and_or_2:
1344 case Builtin::BI__sync_fetch_and_or_4:
1345 case Builtin::BI__sync_fetch_and_or_8:
1346 case Builtin::BI__sync_fetch_and_or_16:
1347 BuiltinIndex = 2;
1348 break;
1349
1350 case Builtin::BI__sync_fetch_and_and:
1351 case Builtin::BI__sync_fetch_and_and_1:
1352 case Builtin::BI__sync_fetch_and_and_2:
1353 case Builtin::BI__sync_fetch_and_and_4:
1354 case Builtin::BI__sync_fetch_and_and_8:
1355 case Builtin::BI__sync_fetch_and_and_16:
1356 BuiltinIndex = 3;
1357 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001358
Douglas Gregora9766412011-11-28 16:30:08 +00001359 case Builtin::BI__sync_fetch_and_xor:
1360 case Builtin::BI__sync_fetch_and_xor_1:
1361 case Builtin::BI__sync_fetch_and_xor_2:
1362 case Builtin::BI__sync_fetch_and_xor_4:
1363 case Builtin::BI__sync_fetch_and_xor_8:
1364 case Builtin::BI__sync_fetch_and_xor_16:
1365 BuiltinIndex = 4;
1366 break;
1367
1368 case Builtin::BI__sync_add_and_fetch:
1369 case Builtin::BI__sync_add_and_fetch_1:
1370 case Builtin::BI__sync_add_and_fetch_2:
1371 case Builtin::BI__sync_add_and_fetch_4:
1372 case Builtin::BI__sync_add_and_fetch_8:
1373 case Builtin::BI__sync_add_and_fetch_16:
1374 BuiltinIndex = 5;
1375 break;
1376
1377 case Builtin::BI__sync_sub_and_fetch:
1378 case Builtin::BI__sync_sub_and_fetch_1:
1379 case Builtin::BI__sync_sub_and_fetch_2:
1380 case Builtin::BI__sync_sub_and_fetch_4:
1381 case Builtin::BI__sync_sub_and_fetch_8:
1382 case Builtin::BI__sync_sub_and_fetch_16:
1383 BuiltinIndex = 6;
1384 break;
1385
1386 case Builtin::BI__sync_and_and_fetch:
1387 case Builtin::BI__sync_and_and_fetch_1:
1388 case Builtin::BI__sync_and_and_fetch_2:
1389 case Builtin::BI__sync_and_and_fetch_4:
1390 case Builtin::BI__sync_and_and_fetch_8:
1391 case Builtin::BI__sync_and_and_fetch_16:
1392 BuiltinIndex = 7;
1393 break;
1394
1395 case Builtin::BI__sync_or_and_fetch:
1396 case Builtin::BI__sync_or_and_fetch_1:
1397 case Builtin::BI__sync_or_and_fetch_2:
1398 case Builtin::BI__sync_or_and_fetch_4:
1399 case Builtin::BI__sync_or_and_fetch_8:
1400 case Builtin::BI__sync_or_and_fetch_16:
1401 BuiltinIndex = 8;
1402 break;
1403
1404 case Builtin::BI__sync_xor_and_fetch:
1405 case Builtin::BI__sync_xor_and_fetch_1:
1406 case Builtin::BI__sync_xor_and_fetch_2:
1407 case Builtin::BI__sync_xor_and_fetch_4:
1408 case Builtin::BI__sync_xor_and_fetch_8:
1409 case Builtin::BI__sync_xor_and_fetch_16:
1410 BuiltinIndex = 9;
1411 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001412
Chris Lattner5caa3702009-05-08 06:58:22 +00001413 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001414 case Builtin::BI__sync_val_compare_and_swap_1:
1415 case Builtin::BI__sync_val_compare_and_swap_2:
1416 case Builtin::BI__sync_val_compare_and_swap_4:
1417 case Builtin::BI__sync_val_compare_and_swap_8:
1418 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001419 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001420 NumFixed = 2;
1421 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001422
Chris Lattner5caa3702009-05-08 06:58:22 +00001423 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001424 case Builtin::BI__sync_bool_compare_and_swap_1:
1425 case Builtin::BI__sync_bool_compare_and_swap_2:
1426 case Builtin::BI__sync_bool_compare_and_swap_4:
1427 case Builtin::BI__sync_bool_compare_and_swap_8:
1428 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001429 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001430 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001431 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001432 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001433
1434 case Builtin::BI__sync_lock_test_and_set:
1435 case Builtin::BI__sync_lock_test_and_set_1:
1436 case Builtin::BI__sync_lock_test_and_set_2:
1437 case Builtin::BI__sync_lock_test_and_set_4:
1438 case Builtin::BI__sync_lock_test_and_set_8:
1439 case Builtin::BI__sync_lock_test_and_set_16:
1440 BuiltinIndex = 12;
1441 break;
1442
Chris Lattner5caa3702009-05-08 06:58:22 +00001443 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001444 case Builtin::BI__sync_lock_release_1:
1445 case Builtin::BI__sync_lock_release_2:
1446 case Builtin::BI__sync_lock_release_4:
1447 case Builtin::BI__sync_lock_release_8:
1448 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001449 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001450 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001451 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001452 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001453
1454 case Builtin::BI__sync_swap:
1455 case Builtin::BI__sync_swap_1:
1456 case Builtin::BI__sync_swap_2:
1457 case Builtin::BI__sync_swap_4:
1458 case Builtin::BI__sync_swap_8:
1459 case Builtin::BI__sync_swap_16:
1460 BuiltinIndex = 14;
1461 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001462 }
Mike Stump1eb44332009-09-09 15:08:12 +00001463
Chris Lattner5caa3702009-05-08 06:58:22 +00001464 // Now that we know how many fixed arguments we expect, first check that we
1465 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001466 if (TheCall->getNumArgs() < 1+NumFixed) {
1467 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1468 << 0 << 1+NumFixed << TheCall->getNumArgs()
1469 << TheCall->getCallee()->getSourceRange();
1470 return ExprError();
1471 }
Mike Stump1eb44332009-09-09 15:08:12 +00001472
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001473 // Get the decl for the concrete builtin from this, we can tell what the
1474 // concrete integer type we should convert to is.
1475 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1476 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001477 FunctionDecl *NewBuiltinDecl;
1478 if (NewBuiltinID == BuiltinID)
1479 NewBuiltinDecl = FDecl;
1480 else {
1481 // Perform builtin lookup to avoid redeclaring it.
1482 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1483 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1484 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1485 assert(Res.getFoundDecl());
1486 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1487 if (NewBuiltinDecl == 0)
1488 return ExprError();
1489 }
Chandler Carruthd2014572010-07-09 18:59:35 +00001490
John McCallf871d0c2010-08-07 06:22:56 +00001491 // The first argument --- the pointer --- has a fixed type; we
1492 // deduce the types of the rest of the arguments accordingly. Walk
1493 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001494 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001495 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001496
Chris Lattner5caa3702009-05-08 06:58:22 +00001497 // GCC does an implicit conversion to the pointer or integer ValType. This
1498 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001499 // Initialize the argument.
1500 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1501 ValType, /*consume*/ false);
1502 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001503 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001504 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001505
Chris Lattner5caa3702009-05-08 06:58:22 +00001506 // Okay, we have something that *can* be converted to the right type. Check
1507 // to see if there is a potentially weird extension going on here. This can
1508 // happen when you do an atomic operation on something like an char* and
1509 // pass in 42. The 42 gets converted to char. This is even more strange
1510 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001511 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001512 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001513 }
Mike Stump1eb44332009-09-09 15:08:12 +00001514
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001515 ASTContext& Context = this->getASTContext();
1516
1517 // Create a new DeclRefExpr to refer to the new decl.
1518 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1519 Context,
1520 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001521 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001522 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001523 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001524 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001525 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001526 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001527
Chris Lattner5caa3702009-05-08 06:58:22 +00001528 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001529 // FIXME: This loses syntactic information.
1530 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1531 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1532 CK_BuiltinFnToFnPtr);
John Wiegley429bb272011-04-08 18:41:53 +00001533 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001534
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001535 // Change the result type of the call to match the original value type. This
1536 // is arbitrary, but the codegen for these builtins ins design to handle it
1537 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001538 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001539
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001540 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001541}
1542
Chris Lattner69039812009-02-18 06:01:06 +00001543/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001544/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001545/// Note: It might also make sense to do the UTF-16 conversion here (would
1546/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001547bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001548 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001549 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1550
Douglas Gregor5cee1192011-07-27 05:40:30 +00001551 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001552 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1553 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001554 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001555 }
Mike Stump1eb44332009-09-09 15:08:12 +00001556
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001557 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001558 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001559 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001560 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00001561 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001562 UTF16 *ToPtr = &ToBuf[0];
1563
1564 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1565 &ToPtr, ToPtr + NumBytes,
1566 strictConversion);
1567 // Check for conversion failure.
1568 if (Result != conversionOK)
1569 Diag(Arg->getLocStart(),
1570 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1571 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001572 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001573}
1574
Chris Lattnerc27c6652007-12-20 00:05:45 +00001575/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1576/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001577bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1578 Expr *Fn = TheCall->getCallee();
1579 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001580 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001581 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001582 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1583 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001584 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001585 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001586 return true;
1587 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001588
1589 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001590 return Diag(TheCall->getLocEnd(),
1591 diag::err_typecheck_call_too_few_args_at_least)
1592 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001593 }
1594
John McCall5f8d6042011-08-27 01:09:30 +00001595 // Type-check the first argument normally.
1596 if (checkBuiltinArgument(*this, TheCall, 0))
1597 return true;
1598
Chris Lattnerc27c6652007-12-20 00:05:45 +00001599 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001600 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001601 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001602 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001603 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001604 else if (FunctionDecl *FD = getCurFunctionDecl())
1605 isVariadic = FD->isVariadic();
1606 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001607 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001608
Chris Lattnerc27c6652007-12-20 00:05:45 +00001609 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001610 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1611 return true;
1612 }
Mike Stump1eb44332009-09-09 15:08:12 +00001613
Chris Lattner30ce3442007-12-19 23:59:04 +00001614 // Verify that the second argument to the builtin is the last argument of the
1615 // current function or method.
1616 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001617 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001618
Nico Weberb07d4482013-05-24 23:31:57 +00001619 // These are valid if SecondArgIsLastNamedArgument is false after the next
1620 // block.
1621 QualType Type;
1622 SourceLocation ParamLoc;
1623
Anders Carlsson88cf2262008-02-11 04:20:54 +00001624 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1625 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001626 // FIXME: This isn't correct for methods (results in bogus warning).
1627 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001628 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001629 if (CurBlock)
1630 LastArg = *(CurBlock->TheDecl->param_end()-1);
1631 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001632 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001633 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001634 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001635 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weberb07d4482013-05-24 23:31:57 +00001636
1637 Type = PV->getType();
1638 ParamLoc = PV->getLocation();
Chris Lattner30ce3442007-12-19 23:59:04 +00001639 }
1640 }
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Chris Lattner30ce3442007-12-19 23:59:04 +00001642 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001643 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001644 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weberb07d4482013-05-24 23:31:57 +00001645 else if (Type->isReferenceType()) {
1646 Diag(Arg->getLocStart(),
1647 diag::warn_va_start_of_reference_type_is_undefined);
1648 Diag(ParamLoc, diag::note_parameter_type) << Type;
1649 }
1650
Chris Lattner30ce3442007-12-19 23:59:04 +00001651 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001652}
Chris Lattner30ce3442007-12-19 23:59:04 +00001653
Chris Lattner1b9a0792007-12-20 00:26:33 +00001654/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1655/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001656bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1657 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001658 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001659 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001660 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001661 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001662 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001663 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001664 << SourceRange(TheCall->getArg(2)->getLocStart(),
1665 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001666
John Wiegley429bb272011-04-08 18:41:53 +00001667 ExprResult OrigArg0 = TheCall->getArg(0);
1668 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001669
Chris Lattner1b9a0792007-12-20 00:26:33 +00001670 // Do standard promotions between the two arguments, returning their common
1671 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001672 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001673 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1674 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001675
1676 // Make sure any conversions are pushed back into the call; this is
1677 // type safe since unordered compare builtins are declared as "_Bool
1678 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001679 TheCall->setArg(0, OrigArg0.get());
1680 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001681
John Wiegley429bb272011-04-08 18:41:53 +00001682 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001683 return false;
1684
Chris Lattner1b9a0792007-12-20 00:26:33 +00001685 // If the common type isn't a real floating type, then the arguments were
1686 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001687 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001688 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001689 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001690 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1691 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001692
Chris Lattner1b9a0792007-12-20 00:26:33 +00001693 return false;
1694}
1695
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001696/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1697/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001698/// to check everything. We expect the last argument to be a floating point
1699/// value.
1700bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1701 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001702 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001703 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001704 if (TheCall->getNumArgs() > NumArgs)
1705 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001706 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001707 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001708 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001709 (*(TheCall->arg_end()-1))->getLocEnd());
1710
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001711 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001712
Eli Friedman9ac6f622009-08-31 20:06:00 +00001713 if (OrigArg->isTypeDependent())
1714 return false;
1715
Chris Lattner81368fb2010-05-06 05:50:07 +00001716 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001717 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001718 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001719 diag::err_typecheck_call_invalid_unary_fp)
1720 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001721
Chris Lattner81368fb2010-05-06 05:50:07 +00001722 // If this is an implicit conversion from float -> double, remove it.
1723 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1724 Expr *CastArg = Cast->getSubExpr();
1725 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1726 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1727 "promotion from float to double is the only expected cast here");
1728 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001729 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001730 }
1731 }
1732
Eli Friedman9ac6f622009-08-31 20:06:00 +00001733 return false;
1734}
1735
Eli Friedmand38617c2008-05-14 19:38:39 +00001736/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1737// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001738ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001739 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001740 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001741 diag::err_typecheck_call_too_few_args_at_least)
Craig Topperb44545a2013-07-28 21:50:10 +00001742 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1743 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001744
Nate Begeman37b6a572010-06-08 00:16:34 +00001745 // Determine which of the following types of shufflevector we're checking:
1746 // 1) unary, vector mask: (lhs, mask)
1747 // 2) binary, vector mask: (lhs, rhs, mask)
1748 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1749 QualType resType = TheCall->getArg(0)->getType();
1750 unsigned numElements = 0;
Craig Toppere3fbbe92013-07-19 04:46:31 +00001751
Douglas Gregorcde01732009-05-19 22:10:17 +00001752 if (!TheCall->getArg(0)->isTypeDependent() &&
1753 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001754 QualType LHSType = TheCall->getArg(0)->getType();
1755 QualType RHSType = TheCall->getArg(1)->getType();
Craig Toppere3fbbe92013-07-19 04:46:31 +00001756
Craig Topperbbe759c2013-07-29 06:47:04 +00001757 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1758 return ExprError(Diag(TheCall->getLocStart(),
1759 diag::err_shufflevector_non_vector)
1760 << SourceRange(TheCall->getArg(0)->getLocStart(),
1761 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00001762
Nate Begeman37b6a572010-06-08 00:16:34 +00001763 numElements = LHSType->getAs<VectorType>()->getNumElements();
1764 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001765
Nate Begeman37b6a572010-06-08 00:16:34 +00001766 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1767 // with mask. If so, verify that RHS is an integer vector type with the
1768 // same number of elts as lhs.
1769 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru4cb3d902013-07-06 08:00:09 +00001770 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001771 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbbe759c2013-07-29 06:47:04 +00001772 return ExprError(Diag(TheCall->getLocStart(),
1773 diag::err_shufflevector_incompatible_vector)
1774 << SourceRange(TheCall->getArg(1)->getLocStart(),
1775 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00001776 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbbe759c2013-07-29 06:47:04 +00001777 return ExprError(Diag(TheCall->getLocStart(),
1778 diag::err_shufflevector_incompatible_vector)
1779 << SourceRange(TheCall->getArg(0)->getLocStart(),
1780 TheCall->getArg(1)->getLocEnd()));
Nate Begeman37b6a572010-06-08 00:16:34 +00001781 } else if (numElements != numResElements) {
1782 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001783 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001784 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001785 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001786 }
1787
1788 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001789 if (TheCall->getArg(i)->isTypeDependent() ||
1790 TheCall->getArg(i)->isValueDependent())
1791 continue;
1792
Nate Begeman37b6a572010-06-08 00:16:34 +00001793 llvm::APSInt Result(32);
1794 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1795 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00001796 diag::err_shufflevector_nonconstant_argument)
1797 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001798
Craig Topper6f4f8082013-08-03 17:40:38 +00001799 // Allow -1 which will be translated to undef in the IR.
1800 if (Result.isSigned() && Result.isAllOnesValue())
1801 continue;
1802
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001803 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001804 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00001805 diag::err_shufflevector_argument_too_large)
1806 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001807 }
1808
Chris Lattner5f9e2722011-07-23 10:55:15 +00001809 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001810
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001811 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001812 exprs.push_back(TheCall->getArg(i));
1813 TheCall->setArg(i, 0);
1814 }
1815
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001816 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001817 TheCall->getCallee()->getLocStart(),
1818 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001819}
Chris Lattner30ce3442007-12-19 23:59:04 +00001820
Hal Finkel414a1bd2013-09-18 03:29:45 +00001821/// SemaConvertVectorExpr - Handle __builtin_convertvector
1822ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1823 SourceLocation BuiltinLoc,
1824 SourceLocation RParenLoc) {
1825 ExprValueKind VK = VK_RValue;
1826 ExprObjectKind OK = OK_Ordinary;
1827 QualType DstTy = TInfo->getType();
1828 QualType SrcTy = E->getType();
1829
1830 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1831 return ExprError(Diag(BuiltinLoc,
1832 diag::err_convertvector_non_vector)
1833 << E->getSourceRange());
1834 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1835 return ExprError(Diag(BuiltinLoc,
1836 diag::err_convertvector_non_vector_type));
1837
1838 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1839 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1840 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1841 if (SrcElts != DstElts)
1842 return ExprError(Diag(BuiltinLoc,
1843 diag::err_convertvector_incompatible_vector)
1844 << E->getSourceRange());
1845 }
1846
1847 return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
1848 BuiltinLoc, RParenLoc));
1849
1850}
1851
Daniel Dunbar4493f792008-07-21 22:59:13 +00001852/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1853// This is declared to take (const void*, ...) and can take two
1854// optional constant int args.
1855bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001856 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001857
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001858 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001859 return Diag(TheCall->getLocEnd(),
1860 diag::err_typecheck_call_too_many_args_at_most)
1861 << 0 /*function call*/ << 3 << NumArgs
1862 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001863
1864 // Argument 0 is checked for us and the remaining arguments must be
1865 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001866 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001867 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001868
1869 // We can't check the value of a dependent argument.
1870 if (Arg->isTypeDependent() || Arg->isValueDependent())
1871 continue;
1872
Eli Friedman9aef7262009-12-04 00:30:06 +00001873 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001874 if (SemaBuiltinConstantArg(TheCall, i, Result))
1875 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001876
Daniel Dunbar4493f792008-07-21 22:59:13 +00001877 // FIXME: gcc issues a warning and rewrites these to 0. These
1878 // seems especially odd for the third argument since the default
1879 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001880 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001881 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001882 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001883 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001884 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001885 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001886 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001887 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001888 }
1889 }
1890
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001891 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001892}
1893
Eric Christopher691ebc32010-04-17 02:26:23 +00001894/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1895/// TheCall is a constant expression.
1896bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1897 llvm::APSInt &Result) {
1898 Expr *Arg = TheCall->getArg(ArgNum);
1899 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1900 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1901
1902 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1903
1904 if (!Arg->isIntegerConstantExpr(Result, Context))
1905 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001906 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001907
Chris Lattner21fb98e2009-09-23 06:06:36 +00001908 return false;
1909}
1910
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001911/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1912/// int type). This simply type checks that type is one of the defined
1913/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001914// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001915bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001916 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001917
1918 // We can't check the value of a dependent argument.
1919 if (TheCall->getArg(1)->isTypeDependent() ||
1920 TheCall->getArg(1)->isValueDependent())
1921 return false;
1922
Eric Christopher691ebc32010-04-17 02:26:23 +00001923 // Check constant-ness first.
1924 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1925 return true;
1926
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001927 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001928 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001929 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1930 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001931 }
1932
1933 return false;
1934}
1935
Eli Friedman586d6a82009-05-03 06:04:26 +00001936/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001937/// This checks that val is a constant 1.
1938bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1939 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001940 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001941
Eric Christopher691ebc32010-04-17 02:26:23 +00001942 // TODO: This is less than ideal. Overload this to take a value.
1943 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1944 return true;
1945
1946 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001947 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1948 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1949
1950 return false;
1951}
1952
Richard Smith0e218972013-08-05 18:49:43 +00001953namespace {
1954enum StringLiteralCheckType {
1955 SLCT_NotALiteral,
1956 SLCT_UncheckedLiteral,
1957 SLCT_CheckedLiteral
1958};
1959}
1960
Richard Smith831421f2012-06-25 20:30:08 +00001961// Determine if an expression is a string literal or constant string.
1962// If this function returns false on the arguments to a function expecting a
1963// format string, we will usually need to emit a warning.
1964// True string literals are then checked by CheckFormatString.
Richard Smith0e218972013-08-05 18:49:43 +00001965static StringLiteralCheckType
1966checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
1967 bool HasVAListArg, unsigned format_idx,
1968 unsigned firstDataArg, Sema::FormatStringType Type,
1969 Sema::VariadicCallType CallType, bool InFunctionCall,
1970 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001971 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001972 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001973 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001974
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001975 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001976
Richard Smith0e218972013-08-05 18:49:43 +00001977 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikiea73cdcb2012-02-10 21:07:25 +00001978 // Technically -Wformat-nonliteral does not warn about this case.
1979 // The behavior of printf and friends in this case is implementation
1980 // dependent. Ideally if the format string cannot be null then
1981 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith0e218972013-08-05 18:49:43 +00001982 return SLCT_UncheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001983
Ted Kremenekd30ef872009-01-12 23:09:09 +00001984 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001985 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001986 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001987 // The expression is a literal if both sub-expressions were, and it was
1988 // completely checked only if both sub-expressions were checked.
1989 const AbstractConditionalOperator *C =
1990 cast<AbstractConditionalOperator>(E);
1991 StringLiteralCheckType Left =
Richard Smith0e218972013-08-05 18:49:43 +00001992 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001993 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00001994 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00001995 if (Left == SLCT_NotALiteral)
1996 return SLCT_NotALiteral;
1997 StringLiteralCheckType Right =
Richard Smith0e218972013-08-05 18:49:43 +00001998 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001999 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002000 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002001 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002002 }
2003
2004 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00002005 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2006 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002007 }
2008
John McCall56ca35d2011-02-17 10:25:35 +00002009 case Stmt::OpaqueValueExprClass:
2010 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2011 E = src;
2012 goto tryAgain;
2013 }
Richard Smith831421f2012-06-25 20:30:08 +00002014 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00002015
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00002016 case Stmt::PredefinedExprClass:
2017 // While __func__, etc., are technically not string literals, they
2018 // cannot contain format specifiers and thus are not a security
2019 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00002020 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00002021
Ted Kremenek082d9362009-03-20 21:35:28 +00002022 case Stmt::DeclRefExprClass: {
2023 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002024
Ted Kremenek082d9362009-03-20 21:35:28 +00002025 // As an exception, do not flag errors for variables binding to
2026 // const string literals.
2027 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2028 bool isConstant = false;
2029 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00002030
Richard Smith0e218972013-08-05 18:49:43 +00002031 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2032 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002033 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smith0e218972013-08-05 18:49:43 +00002034 isConstant = T.isConstant(S.Context) &&
2035 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00002036 } else if (T->isObjCObjectPointerType()) {
2037 // In ObjC, there is usually no "const ObjectPointer" type,
2038 // so don't check if the pointee type is constant.
Richard Smith0e218972013-08-05 18:49:43 +00002039 isConstant = T.isConstant(S.Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00002040 }
Mike Stump1eb44332009-09-09 15:08:12 +00002041
Ted Kremenek082d9362009-03-20 21:35:28 +00002042 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002043 if (const Expr *Init = VD->getAnyInitializer()) {
2044 // Look through initializers like const char c[] = { "foo" }
2045 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2046 if (InitList->isStringLiteralInit())
2047 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2048 }
Richard Smith0e218972013-08-05 18:49:43 +00002049 return checkFormatStringExpr(S, Init, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002050 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002051 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002052 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002053 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002054 }
Mike Stump1eb44332009-09-09 15:08:12 +00002055
Anders Carlssond966a552009-06-28 19:55:58 +00002056 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2057 // special check to see if the format string is a function parameter
2058 // of the function calling the printf function. If the function
2059 // has an attribute indicating it is a printf-like function, then we
2060 // should suppress warnings concerning non-literals being used in a call
2061 // to a vprintf function. For example:
2062 //
2063 // void
2064 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2065 // va_list ap;
2066 // va_start(ap, fmt);
2067 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2068 // ...
Richard Smith0e218972013-08-05 18:49:43 +00002069 // }
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002070 if (HasVAListArg) {
2071 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2072 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2073 int PVIndex = PV->getFunctionScopeIndex() + 1;
2074 for (specific_attr_iterator<FormatAttr>
2075 i = ND->specific_attr_begin<FormatAttr>(),
2076 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
2077 FormatAttr *PVFormat = *i;
2078 // adjust for implicit parameter
2079 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2080 if (MD->isInstance())
2081 ++PVIndex;
2082 // We also check if the formats are compatible.
2083 // We can't pass a 'scanf' string to a 'printf' function.
2084 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smith0e218972013-08-05 18:49:43 +00002085 Type == S.GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00002086 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002087 }
2088 }
2089 }
2090 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002091 }
Mike Stump1eb44332009-09-09 15:08:12 +00002092
Richard Smith831421f2012-06-25 20:30:08 +00002093 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00002094 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00002095
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002096 case Stmt::CallExprClass:
2097 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00002098 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002099 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2100 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2101 unsigned ArgIndex = FA->getFormatIdx();
2102 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2103 if (MD->isInstance())
2104 --ArgIndex;
2105 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002106
Richard Smith0e218972013-08-05 18:49:43 +00002107 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002108 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002109 Type, CallType, InFunctionCall,
2110 CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002111 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2112 unsigned BuiltinID = FD->getBuiltinID();
2113 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2114 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2115 const Expr *Arg = CE->getArg(0);
Richard Smith0e218972013-08-05 18:49:43 +00002116 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002117 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002118 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002119 InFunctionCall, CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002120 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00002121 }
2122 }
Mike Stump1eb44332009-09-09 15:08:12 +00002123
Richard Smith831421f2012-06-25 20:30:08 +00002124 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00002125 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002126 case Stmt::ObjCStringLiteralClass:
2127 case Stmt::StringLiteralClass: {
2128 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002129
Ted Kremenek082d9362009-03-20 21:35:28 +00002130 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00002131 StrE = ObjCFExpr->getString();
2132 else
Ted Kremenek082d9362009-03-20 21:35:28 +00002133 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002134
Ted Kremenekd30ef872009-01-12 23:09:09 +00002135 if (StrE) {
Richard Smith0e218972013-08-05 18:49:43 +00002136 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2137 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002138 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002139 }
Mike Stump1eb44332009-09-09 15:08:12 +00002140
Richard Smith831421f2012-06-25 20:30:08 +00002141 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002142 }
Mike Stump1eb44332009-09-09 15:08:12 +00002143
Ted Kremenek082d9362009-03-20 21:35:28 +00002144 default:
Richard Smith831421f2012-06-25 20:30:08 +00002145 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002146 }
2147}
2148
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002149void
Mike Stump1eb44332009-09-09 15:08:12 +00002150Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00002151 const Expr * const *ExprArgs,
2152 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00002153 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
2154 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002155 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00002156 const Expr *ArgExpr = ExprArgs[*i];
Nick Lewycky3edf3872013-01-23 05:08:29 +00002157
2158 // As a special case, transparent unions initialized with zero are
2159 // considered null for the purposes of the nonnull attribute.
2160 if (const RecordType *UT = ArgExpr->getType()->getAsUnionType()) {
2161 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2162 if (const CompoundLiteralExpr *CLE =
2163 dyn_cast<CompoundLiteralExpr>(ArgExpr))
2164 if (const InitListExpr *ILE =
2165 dyn_cast<InitListExpr>(CLE->getInitializer()))
2166 ArgExpr = ILE->getInit(0);
2167 }
2168
2169 bool Result;
2170 if (ArgExpr->EvaluateAsBooleanCondition(Result, Context) && !Result)
Nick Lewycky909a70d2011-03-25 01:44:32 +00002171 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002172 }
2173}
Ted Kremenekd30ef872009-01-12 23:09:09 +00002174
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002175Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmancaa5ab22013-09-03 21:02:22 +00002176 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002177 .Case("scanf", FST_Scanf)
2178 .Cases("printf", "printf0", FST_Printf)
2179 .Cases("NSString", "CFString", FST_NSString)
2180 .Case("strftime", FST_Strftime)
2181 .Case("strfmon", FST_Strfmon)
2182 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2183 .Default(FST_Unknown);
2184}
2185
Jordan Roseddcfbc92012-07-19 18:10:23 +00002186/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00002187/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00002188/// Returns true if a format string has been fully checked.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002189bool Sema::CheckFormatArguments(const FormatAttr *Format,
2190 ArrayRef<const Expr *> Args,
2191 bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002192 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002193 SourceLocation Loc, SourceRange Range,
2194 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith831421f2012-06-25 20:30:08 +00002195 FormatStringInfo FSI;
2196 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002197 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith831421f2012-06-25 20:30:08 +00002198 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smith0e218972013-08-05 18:49:43 +00002199 CallType, Loc, Range, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002200 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002201}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00002202
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002203bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002204 bool HasVAListArg, unsigned format_idx,
2205 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002206 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002207 SourceLocation Loc, SourceRange Range,
2208 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002209 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002210 if (format_idx >= Args.size()) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002211 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00002212 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00002213 }
Mike Stump1eb44332009-09-09 15:08:12 +00002214
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002215 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00002216
Chris Lattner59907c42007-08-10 20:18:51 +00002217 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00002218 //
Ted Kremenek71895b92007-08-14 17:39:48 +00002219 // Dynamically generated format strings are difficult to
2220 // automatically vet at compile time. Requiring that format strings
2221 // are string literals: (1) permits the checking of format strings by
2222 // the compiler and thereby (2) can practically remove the source of
2223 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002224
Mike Stump1eb44332009-09-09 15:08:12 +00002225 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002226 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00002227 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002228 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00002229 StringLiteralCheckType CT =
Richard Smith0e218972013-08-05 18:49:43 +00002230 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2231 format_idx, firstDataArg, Type, CallType,
2232 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002233 if (CT != SLCT_NotALiteral)
2234 // Literal format string found, check done!
2235 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002236
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002237 // Strftime is particular as it always uses a single 'time' argument,
2238 // so it is safe to pass a non-literal string.
2239 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00002240 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002241
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002242 // Do not emit diag when the string param is a macro expansion and the
2243 // format is either NSString or CFString. This is a hack to prevent
2244 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2245 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00002246 if (Type == FST_NSString &&
2247 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00002248 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002249
Chris Lattner655f1412009-04-29 04:59:47 +00002250 // If there are no arguments specified, warn with -Wformat-security, otherwise
2251 // warn only with -Wformat-nonliteral.
Eli Friedman2243e782013-06-18 18:10:01 +00002252 if (Args.size() == firstDataArg)
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002253 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002254 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00002255 << OrigFormatExpr->getSourceRange();
2256 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002257 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002258 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00002259 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00002260 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002261}
Ted Kremenek71895b92007-08-14 17:39:48 +00002262
Ted Kremeneke0e53132010-01-28 23:39:18 +00002263namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00002264class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2265protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00002266 Sema &S;
2267 const StringLiteral *FExpr;
2268 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00002269 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002270 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002271 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00002272 const bool HasVAListArg;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002273 ArrayRef<const Expr *> Args;
Ted Kremenek0d277352010-01-29 01:06:55 +00002274 unsigned FormatIdx;
Richard Smith0e218972013-08-05 18:49:43 +00002275 llvm::SmallBitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00002276 bool usesPositionalArgs;
2277 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00002278 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00002279 Sema::VariadicCallType CallType;
Richard Smith0e218972013-08-05 18:49:43 +00002280 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002281public:
Ted Kremenek826a3452010-07-16 02:11:22 +00002282 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00002283 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002284 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002285 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002286 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00002287 Sema::VariadicCallType callType,
2288 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremeneke0e53132010-01-28 23:39:18 +00002289 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00002290 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2291 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002292 Args(Args), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00002293 usesPositionalArgs(false), atFirstArg(true),
Richard Smith0e218972013-08-05 18:49:43 +00002294 inFunctionCall(inFunctionCall), CallType(callType),
2295 CheckedVarArgs(CheckedVarArgs) {
2296 CoveredArgs.resize(numDataArgs);
2297 CoveredArgs.reset();
2298 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002299
Ted Kremenek07d161f2010-01-29 01:50:07 +00002300 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002301
Ted Kremenek826a3452010-07-16 02:11:22 +00002302 void HandleIncompleteSpecifier(const char *startSpecifier,
2303 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00002304
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002305 void HandleInvalidLengthModifier(
2306 const analyze_format_string::FormatSpecifier &FS,
2307 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002308 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002309
Hans Wennborg76517422012-02-22 10:17:01 +00002310 void HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002311 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002312 const char *startSpecifier, unsigned specifierLen);
2313
2314 void HandleNonStandardConversionSpecifier(
2315 const analyze_format_string::ConversionSpecifier &CS,
2316 const char *startSpecifier, unsigned specifierLen);
2317
Hans Wennborgf8562642012-03-09 10:10:54 +00002318 virtual void HandlePosition(const char *startPos, unsigned posLen);
2319
Ted Kremenekefaff192010-02-27 01:41:03 +00002320 virtual void HandleInvalidPosition(const char *startSpecifier,
2321 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00002322 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00002323
2324 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2325
Ted Kremeneke0e53132010-01-28 23:39:18 +00002326 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002327
Richard Trieu55733de2011-10-28 00:41:25 +00002328 template <typename Range>
2329 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2330 const Expr *ArgumentExpr,
2331 PartialDiagnostic PDiag,
2332 SourceLocation StringLoc,
2333 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002334 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002335
Ted Kremenek826a3452010-07-16 02:11:22 +00002336protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002337 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2338 const char *startSpec,
2339 unsigned specifierLen,
2340 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00002341
2342 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2343 const char *startSpec,
2344 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002345
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002346 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00002347 CharSourceRange getSpecifierRange(const char *startSpecifier,
2348 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002349 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002350
Ted Kremenek0d277352010-01-29 01:06:55 +00002351 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00002352
2353 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2354 const analyze_format_string::ConversionSpecifier &CS,
2355 const char *startSpecifier, unsigned specifierLen,
2356 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00002357
2358 template <typename Range>
2359 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2360 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002361 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002362
2363 void CheckPositionalAndNonpositionalArgs(
2364 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002365};
2366}
2367
Ted Kremenek826a3452010-07-16 02:11:22 +00002368SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002369 return OrigFormatExpr->getSourceRange();
2370}
2371
Ted Kremenek826a3452010-07-16 02:11:22 +00002372CharSourceRange CheckFormatHandler::
2373getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002374 SourceLocation Start = getLocationOfByte(startSpecifier);
2375 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2376
2377 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002378 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002379
2380 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002381}
2382
Ted Kremenek826a3452010-07-16 02:11:22 +00002383SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002384 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002385}
2386
Ted Kremenek826a3452010-07-16 02:11:22 +00002387void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2388 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002389 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2390 getLocationOfByte(startSpecifier),
2391 /*IsStringLocation*/true,
2392 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002393}
2394
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002395void CheckFormatHandler::HandleInvalidLengthModifier(
2396 const analyze_format_string::FormatSpecifier &FS,
2397 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002398 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002399 using namespace analyze_format_string;
2400
2401 const LengthModifier &LM = FS.getLengthModifier();
2402 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2403
2404 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002405 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002406 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002407 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002408 getLocationOfByte(LM.getStart()),
2409 /*IsStringLocation*/true,
2410 getSpecifierRange(startSpecifier, specifierLen));
2411
2412 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2413 << FixedLM->toString()
2414 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2415
2416 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00002417 FixItHint Hint;
2418 if (DiagID == diag::warn_format_nonsensical_length)
2419 Hint = FixItHint::CreateRemoval(LMRange);
2420
2421 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002422 getLocationOfByte(LM.getStart()),
2423 /*IsStringLocation*/true,
2424 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002425 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002426 }
2427}
2428
Hans Wennborg76517422012-02-22 10:17:01 +00002429void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002430 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002431 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002432 using namespace analyze_format_string;
2433
2434 const LengthModifier &LM = FS.getLengthModifier();
2435 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2436
2437 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002438 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose8be066e2012-09-08 04:00:12 +00002439 if (FixedLM) {
2440 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2441 << LM.toString() << 0,
2442 getLocationOfByte(LM.getStart()),
2443 /*IsStringLocation*/true,
2444 getSpecifierRange(startSpecifier, specifierLen));
2445
2446 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2447 << FixedLM->toString()
2448 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2449
2450 } else {
2451 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2452 << LM.toString() << 0,
2453 getLocationOfByte(LM.getStart()),
2454 /*IsStringLocation*/true,
2455 getSpecifierRange(startSpecifier, specifierLen));
2456 }
Hans Wennborg76517422012-02-22 10:17:01 +00002457}
2458
2459void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2460 const analyze_format_string::ConversionSpecifier &CS,
2461 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002462 using namespace analyze_format_string;
2463
2464 // See if we know how to fix this conversion specifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002465 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose670941c2012-09-13 02:11:15 +00002466 if (FixedCS) {
2467 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2468 << CS.toString() << /*conversion specifier*/1,
2469 getLocationOfByte(CS.getStart()),
2470 /*IsStringLocation*/true,
2471 getSpecifierRange(startSpecifier, specifierLen));
2472
2473 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2474 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2475 << FixedCS->toString()
2476 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2477 } else {
2478 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2479 << CS.toString() << /*conversion specifier*/1,
2480 getLocationOfByte(CS.getStart()),
2481 /*IsStringLocation*/true,
2482 getSpecifierRange(startSpecifier, specifierLen));
2483 }
Hans Wennborg76517422012-02-22 10:17:01 +00002484}
2485
Hans Wennborgf8562642012-03-09 10:10:54 +00002486void CheckFormatHandler::HandlePosition(const char *startPos,
2487 unsigned posLen) {
2488 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2489 getLocationOfByte(startPos),
2490 /*IsStringLocation*/true,
2491 getSpecifierRange(startPos, posLen));
2492}
2493
Ted Kremenekefaff192010-02-27 01:41:03 +00002494void
Ted Kremenek826a3452010-07-16 02:11:22 +00002495CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2496 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002497 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2498 << (unsigned) p,
2499 getLocationOfByte(startPos), /*IsStringLocation*/true,
2500 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002501}
2502
Ted Kremenek826a3452010-07-16 02:11:22 +00002503void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002504 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002505 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2506 getLocationOfByte(startPos),
2507 /*IsStringLocation*/true,
2508 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002509}
2510
Ted Kremenek826a3452010-07-16 02:11:22 +00002511void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002512 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002513 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002514 EmitFormatDiagnostic(
2515 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2516 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2517 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002518 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002519}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002520
Jordan Rose48716662012-07-19 18:10:08 +00002521// Note that this may return NULL if there was an error parsing or building
2522// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002523const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002524 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002525}
2526
2527void CheckFormatHandler::DoneProcessing() {
2528 // Does the number of data arguments exceed the number of
2529 // format conversions in the format string?
2530 if (!HasVAListArg) {
2531 // Find any arguments that weren't covered.
2532 CoveredArgs.flip();
2533 signed notCoveredArg = CoveredArgs.find_first();
2534 if (notCoveredArg >= 0) {
2535 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002536 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2537 SourceLocation Loc = E->getLocStart();
2538 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2539 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2540 Loc, /*IsStringLocation*/false,
2541 getFormatStringRange());
2542 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002543 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002544 }
2545 }
2546}
2547
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002548bool
2549CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2550 SourceLocation Loc,
2551 const char *startSpec,
2552 unsigned specifierLen,
2553 const char *csStart,
2554 unsigned csLen) {
2555
2556 bool keepGoing = true;
2557 if (argIndex < NumDataArgs) {
2558 // Consider the argument coverered, even though the specifier doesn't
2559 // make sense.
2560 CoveredArgs.set(argIndex);
2561 }
2562 else {
2563 // If argIndex exceeds the number of data arguments we
2564 // don't issue a warning because that is just a cascade of warnings (and
2565 // they may have intended '%%' anyway). We don't want to continue processing
2566 // the format string after this point, however, as we will like just get
2567 // gibberish when trying to match arguments.
2568 keepGoing = false;
2569 }
2570
Richard Trieu55733de2011-10-28 00:41:25 +00002571 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2572 << StringRef(csStart, csLen),
2573 Loc, /*IsStringLocation*/true,
2574 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002575
2576 return keepGoing;
2577}
2578
Richard Trieu55733de2011-10-28 00:41:25 +00002579void
2580CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2581 const char *startSpec,
2582 unsigned specifierLen) {
2583 EmitFormatDiagnostic(
2584 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2585 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2586}
2587
Ted Kremenek666a1972010-07-26 19:45:42 +00002588bool
2589CheckFormatHandler::CheckNumArgs(
2590 const analyze_format_string::FormatSpecifier &FS,
2591 const analyze_format_string::ConversionSpecifier &CS,
2592 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2593
2594 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002595 PartialDiagnostic PDiag = FS.usesPositionalArg()
2596 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2597 << (argIndex+1) << NumDataArgs)
2598 : S.PDiag(diag::warn_printf_insufficient_data_args);
2599 EmitFormatDiagnostic(
2600 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2601 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002602 return false;
2603 }
2604 return true;
2605}
2606
Richard Trieu55733de2011-10-28 00:41:25 +00002607template<typename Range>
2608void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2609 SourceLocation Loc,
2610 bool IsStringLocation,
2611 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002612 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002613 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002614 Loc, IsStringLocation, StringRange, FixIt);
2615}
2616
2617/// \brief If the format string is not within the funcion call, emit a note
2618/// so that the function call and string are in diagnostic messages.
2619///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002620/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002621/// call and only one diagnostic message will be produced. Otherwise, an
2622/// extra note will be emitted pointing to location of the format string.
2623///
2624/// \param ArgumentExpr the expression that is passed as the format string
2625/// argument in the function call. Used for getting locations when two
2626/// diagnostics are emitted.
2627///
2628/// \param PDiag the callee should already have provided any strings for the
2629/// diagnostic message. This function only adds locations and fixits
2630/// to diagnostics.
2631///
2632/// \param Loc primary location for diagnostic. If two diagnostics are
2633/// required, one will be at Loc and a new SourceLocation will be created for
2634/// the other one.
2635///
2636/// \param IsStringLocation if true, Loc points to the format string should be
2637/// used for the note. Otherwise, Loc points to the argument list and will
2638/// be used with PDiag.
2639///
2640/// \param StringRange some or all of the string to highlight. This is
2641/// templated so it can accept either a CharSourceRange or a SourceRange.
2642///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002643/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002644template<typename Range>
2645void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2646 const Expr *ArgumentExpr,
2647 PartialDiagnostic PDiag,
2648 SourceLocation Loc,
2649 bool IsStringLocation,
2650 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002651 ArrayRef<FixItHint> FixIt) {
2652 if (InFunctionCall) {
2653 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2654 D << StringRange;
2655 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2656 I != E; ++I) {
2657 D << *I;
2658 }
2659 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00002660 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2661 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00002662
2663 const Sema::SemaDiagnosticBuilder &Note =
2664 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2665 diag::note_format_string_defined);
2666
2667 Note << StringRange;
2668 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2669 I != E; ++I) {
2670 Note << *I;
2671 }
Richard Trieu55733de2011-10-28 00:41:25 +00002672 }
2673}
2674
Ted Kremenek826a3452010-07-16 02:11:22 +00002675//===--- CHECK: Printf format string checking ------------------------------===//
2676
2677namespace {
2678class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002679 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002680public:
2681 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2682 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002683 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002684 const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002685 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002686 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00002687 Sema::VariadicCallType CallType,
2688 llvm::SmallBitVector &CheckedVarArgs)
2689 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2690 numDataArgs, beg, hasVAListArg, Args,
2691 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2692 ObjCContext(isObjC)
Jordan Roseddcfbc92012-07-19 18:10:23 +00002693 {}
2694
Ted Kremenek826a3452010-07-16 02:11:22 +00002695
2696 bool HandleInvalidPrintfConversionSpecifier(
2697 const analyze_printf::PrintfSpecifier &FS,
2698 const char *startSpecifier,
2699 unsigned specifierLen);
2700
2701 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2702 const char *startSpecifier,
2703 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002704 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2705 const char *StartSpecifier,
2706 unsigned SpecifierLen,
2707 const Expr *E);
2708
Ted Kremenek826a3452010-07-16 02:11:22 +00002709 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2710 const char *startSpecifier, unsigned specifierLen);
2711 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2712 const analyze_printf::OptionalAmount &Amt,
2713 unsigned type,
2714 const char *startSpecifier, unsigned specifierLen);
2715 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2716 const analyze_printf::OptionalFlag &flag,
2717 const char *startSpecifier, unsigned specifierLen);
2718 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2719 const analyze_printf::OptionalFlag &ignoredFlag,
2720 const analyze_printf::OptionalFlag &flag,
2721 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002722 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith831421f2012-06-25 20:30:08 +00002723 const Expr *E, const CharSourceRange &CSR);
2724
Ted Kremenek826a3452010-07-16 02:11:22 +00002725};
2726}
2727
2728bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2729 const analyze_printf::PrintfSpecifier &FS,
2730 const char *startSpecifier,
2731 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002732 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002733 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002734
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002735 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2736 getLocationOfByte(CS.getStart()),
2737 startSpecifier, specifierLen,
2738 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002739}
2740
Ted Kremenek826a3452010-07-16 02:11:22 +00002741bool CheckPrintfHandler::HandleAmount(
2742 const analyze_format_string::OptionalAmount &Amt,
2743 unsigned k, const char *startSpecifier,
2744 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002745
2746 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002747 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002748 unsigned argIndex = Amt.getArgIndex();
2749 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002750 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2751 << k,
2752 getLocationOfByte(Amt.getStart()),
2753 /*IsStringLocation*/true,
2754 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002755 // Don't do any more checking. We will just emit
2756 // spurious errors.
2757 return false;
2758 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002759
Ted Kremenek0d277352010-01-29 01:06:55 +00002760 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002761 // Although not in conformance with C99, we also allow the argument to be
2762 // an 'unsigned int' as that is a reasonably safe case. GCC also
2763 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002764 CoveredArgs.set(argIndex);
2765 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002766 if (!Arg)
2767 return false;
2768
Ted Kremenek0d277352010-01-29 01:06:55 +00002769 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002770
Hans Wennborgf3749f42012-08-07 08:11:26 +00002771 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2772 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002773
Hans Wennborgf3749f42012-08-07 08:11:26 +00002774 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002775 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002776 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002777 << T << Arg->getSourceRange(),
2778 getLocationOfByte(Amt.getStart()),
2779 /*IsStringLocation*/true,
2780 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002781 // Don't do any more checking. We will just emit
2782 // spurious errors.
2783 return false;
2784 }
2785 }
2786 }
2787 return true;
2788}
Ted Kremenek0d277352010-01-29 01:06:55 +00002789
Tom Caree4ee9662010-06-17 19:00:27 +00002790void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002791 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002792 const analyze_printf::OptionalAmount &Amt,
2793 unsigned type,
2794 const char *startSpecifier,
2795 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002796 const analyze_printf::PrintfConversionSpecifier &CS =
2797 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002798
Richard Trieu55733de2011-10-28 00:41:25 +00002799 FixItHint fixit =
2800 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2801 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2802 Amt.getConstantLength()))
2803 : FixItHint();
2804
2805 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2806 << type << CS.toString(),
2807 getLocationOfByte(Amt.getStart()),
2808 /*IsStringLocation*/true,
2809 getSpecifierRange(startSpecifier, specifierLen),
2810 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002811}
2812
Ted Kremenek826a3452010-07-16 02:11:22 +00002813void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002814 const analyze_printf::OptionalFlag &flag,
2815 const char *startSpecifier,
2816 unsigned specifierLen) {
2817 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002818 const analyze_printf::PrintfConversionSpecifier &CS =
2819 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002820 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2821 << flag.toString() << CS.toString(),
2822 getLocationOfByte(flag.getPosition()),
2823 /*IsStringLocation*/true,
2824 getSpecifierRange(startSpecifier, specifierLen),
2825 FixItHint::CreateRemoval(
2826 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002827}
2828
2829void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002830 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002831 const analyze_printf::OptionalFlag &ignoredFlag,
2832 const analyze_printf::OptionalFlag &flag,
2833 const char *startSpecifier,
2834 unsigned specifierLen) {
2835 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002836 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2837 << ignoredFlag.toString() << flag.toString(),
2838 getLocationOfByte(ignoredFlag.getPosition()),
2839 /*IsStringLocation*/true,
2840 getSpecifierRange(startSpecifier, specifierLen),
2841 FixItHint::CreateRemoval(
2842 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002843}
2844
Richard Smith831421f2012-06-25 20:30:08 +00002845// Determines if the specified is a C++ class or struct containing
2846// a member with the specified name and kind (e.g. a CXXMethodDecl named
2847// "c_str()").
2848template<typename MemberKind>
2849static llvm::SmallPtrSet<MemberKind*, 1>
2850CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2851 const RecordType *RT = Ty->getAs<RecordType>();
2852 llvm::SmallPtrSet<MemberKind*, 1> Results;
2853
2854 if (!RT)
2855 return Results;
2856 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2857 if (!RD)
2858 return Results;
2859
2860 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2861 Sema::LookupMemberName);
2862
2863 // We just need to include all members of the right kind turned up by the
2864 // filter, at this point.
2865 if (S.LookupQualifiedName(R, RT->getDecl()))
2866 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2867 NamedDecl *decl = (*I)->getUnderlyingDecl();
2868 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2869 Results.insert(FK);
2870 }
2871 return Results;
2872}
2873
2874// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002875// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002876// Returns true when a c_str() conversion method is found.
2877bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgf3749f42012-08-07 08:11:26 +00002878 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith831421f2012-06-25 20:30:08 +00002879 const CharSourceRange &CSR) {
2880 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2881
2882 MethodSet Results =
2883 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2884
2885 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2886 MI != ME; ++MI) {
2887 const CXXMethodDecl *Method = *MI;
2888 if (Method->getNumParams() == 0 &&
Hans Wennborgf3749f42012-08-07 08:11:26 +00002889 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith831421f2012-06-25 20:30:08 +00002890 // FIXME: Suggest parens if the expression needs them.
2891 SourceLocation EndLoc =
2892 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2893 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2894 << "c_str()"
2895 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2896 return true;
2897 }
2898 }
2899
2900 return false;
2901}
2902
Ted Kremeneke0e53132010-01-28 23:39:18 +00002903bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002904CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002905 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002906 const char *startSpecifier,
2907 unsigned specifierLen) {
2908
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002909 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002910 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002911 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002912
Ted Kremenekbaa40062010-07-19 22:01:06 +00002913 if (FS.consumesDataArgument()) {
2914 if (atFirstArg) {
2915 atFirstArg = false;
2916 usesPositionalArgs = FS.usesPositionalArg();
2917 }
2918 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002919 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2920 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002921 return false;
2922 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002923 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002924
Ted Kremenekefaff192010-02-27 01:41:03 +00002925 // First check if the field width, precision, and conversion specifier
2926 // have matching data arguments.
2927 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2928 startSpecifier, specifierLen)) {
2929 return false;
2930 }
2931
2932 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2933 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002934 return false;
2935 }
2936
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002937 if (!CS.consumesDataArgument()) {
2938 // FIXME: Technically specifying a precision or field width here
2939 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002940 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002941 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002942
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002943 // Consume the argument.
2944 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002945 if (argIndex < NumDataArgs) {
2946 // The check to see if the argIndex is valid will come later.
2947 // We set the bit here because we may exit early from this
2948 // function if we encounter some other error.
2949 CoveredArgs.set(argIndex);
2950 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002951
2952 // Check for using an Objective-C specific conversion specifier
2953 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002954 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002955 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2956 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002957 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002958
Tom Caree4ee9662010-06-17 19:00:27 +00002959 // Check for invalid use of field width
2960 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002961 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002962 startSpecifier, specifierLen);
2963 }
2964
2965 // Check for invalid use of precision
2966 if (!FS.hasValidPrecision()) {
2967 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2968 startSpecifier, specifierLen);
2969 }
2970
2971 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002972 if (!FS.hasValidThousandsGroupingPrefix())
2973 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002974 if (!FS.hasValidLeadingZeros())
2975 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2976 if (!FS.hasValidPlusPrefix())
2977 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002978 if (!FS.hasValidSpacePrefix())
2979 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002980 if (!FS.hasValidAlternativeForm())
2981 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2982 if (!FS.hasValidLeftJustified())
2983 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2984
2985 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002986 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2987 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2988 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002989 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2990 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2991 startSpecifier, specifierLen);
2992
2993 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002994 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00002995 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2996 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002997 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00002998 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002999 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003000 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3001 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00003002
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003003 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3004 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3005
Ted Kremenekda51f0d2010-01-29 01:43:31 +00003006 // The remaining checks depend on the data arguments.
3007 if (HasVAListArg)
3008 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003009
Ted Kremenek666a1972010-07-26 19:45:42 +00003010 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00003011 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003012
Jordan Rose48716662012-07-19 18:10:08 +00003013 const Expr *Arg = getDataArg(argIndex);
3014 if (!Arg)
3015 return true;
3016
3017 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00003018}
3019
Jordan Roseec087352012-09-05 22:56:26 +00003020static bool requiresParensToAddCast(const Expr *E) {
3021 // FIXME: We should have a general way to reason about operator
3022 // precedence and whether parens are actually needed here.
3023 // Take care of a few common cases where they aren't.
3024 const Expr *Inside = E->IgnoreImpCasts();
3025 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3026 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3027
3028 switch (Inside->getStmtClass()) {
3029 case Stmt::ArraySubscriptExprClass:
3030 case Stmt::CallExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003031 case Stmt::CharacterLiteralClass:
3032 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003033 case Stmt::DeclRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003034 case Stmt::FloatingLiteralClass:
3035 case Stmt::IntegerLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003036 case Stmt::MemberExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003037 case Stmt::ObjCArrayLiteralClass:
3038 case Stmt::ObjCBoolLiteralExprClass:
3039 case Stmt::ObjCBoxedExprClass:
3040 case Stmt::ObjCDictionaryLiteralClass:
3041 case Stmt::ObjCEncodeExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003042 case Stmt::ObjCIvarRefExprClass:
3043 case Stmt::ObjCMessageExprClass:
3044 case Stmt::ObjCPropertyRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003045 case Stmt::ObjCStringLiteralClass:
3046 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003047 case Stmt::ParenExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003048 case Stmt::StringLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003049 case Stmt::UnaryOperatorClass:
3050 return false;
3051 default:
3052 return true;
3053 }
3054}
3055
Richard Smith831421f2012-06-25 20:30:08 +00003056bool
3057CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3058 const char *StartSpecifier,
3059 unsigned SpecifierLen,
3060 const Expr *E) {
3061 using namespace analyze_format_string;
3062 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003063 // Now type check the data expression that matches the
3064 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00003065 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3066 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00003067 if (!AT.isValid())
3068 return true;
Jordan Roseec087352012-09-05 22:56:26 +00003069
Jordan Rose448ac3e2012-12-05 18:44:40 +00003070 QualType ExprTy = E->getType();
Ted Kremenek02be9682013-04-10 06:26:26 +00003071 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3072 ExprTy = TET->getUnderlyingExpr()->getType();
3073 }
3074
Jordan Rose448ac3e2012-12-05 18:44:40 +00003075 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003076 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00003077
Jordan Rose614a8652012-09-05 22:56:19 +00003078 // Look through argument promotions for our error message's reported type.
3079 // This includes the integral and floating promotions, but excludes array
3080 // and function pointer decay; seeing that an argument intended to be a
3081 // string has type 'char [6]' is probably more confusing than 'char *'.
3082 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3083 if (ICE->getCastKind() == CK_IntegralCast ||
3084 ICE->getCastKind() == CK_FloatingCast) {
3085 E = ICE->getSubExpr();
Jordan Rose448ac3e2012-12-05 18:44:40 +00003086 ExprTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00003087
3088 // Check if we didn't match because of an implicit cast from a 'char'
3089 // or 'short' to an 'int'. This is done because printf is a varargs
3090 // function.
3091 if (ICE->getType() == S.Context.IntTy ||
3092 ICE->getType() == S.Context.UnsignedIntTy) {
3093 // All further checking is done on the subexpression.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003094 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003095 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00003096 }
Jordan Roseee0259d2012-06-04 22:48:57 +00003097 }
Jordan Rose448ac3e2012-12-05 18:44:40 +00003098 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3099 // Special case for 'a', which has type 'int' in C.
3100 // Note, however, that we do /not/ want to treat multibyte constants like
3101 // 'MooV' as characters! This form is deprecated but still exists.
3102 if (ExprTy == S.Context.IntTy)
3103 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3104 ExprTy = S.Context.CharTy;
Jordan Rose614a8652012-09-05 22:56:19 +00003105 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003106
Jordan Rose2cd34402012-12-05 18:44:49 +00003107 // %C in an Objective-C context prints a unichar, not a wchar_t.
3108 // If the argument is an integer of some kind, believe the %C and suggest
3109 // a cast instead of changing the conversion specifier.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003110 QualType IntendedTy = ExprTy;
Jordan Rose2cd34402012-12-05 18:44:49 +00003111 if (ObjCContext &&
3112 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3113 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3114 !ExprTy->isCharType()) {
3115 // 'unichar' is defined as a typedef of unsigned short, but we should
3116 // prefer using the typedef if it is visible.
3117 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenek656465d2013-10-15 05:25:17 +00003118
3119 // While we are here, check if the value is an IntegerLiteral that happens
3120 // to be within the valid range.
3121 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3122 const llvm::APInt &V = IL->getValue();
3123 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3124 return true;
3125 }
3126
Jordan Rose2cd34402012-12-05 18:44:49 +00003127 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3128 Sema::LookupOrdinaryName);
3129 if (S.LookupName(Result, S.getCurScope())) {
3130 NamedDecl *ND = Result.getFoundDecl();
3131 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3132 if (TD->getUnderlyingType() == IntendedTy)
3133 IntendedTy = S.Context.getTypedefType(TD);
3134 }
3135 }
3136 }
3137
3138 // Special-case some of Darwin's platform-independence types by suggesting
3139 // casts to primitive types that are known to be large enough.
3140 bool ShouldNotPrintDirectly = false;
Jordan Roseec087352012-09-05 22:56:26 +00003141 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenek6edb0292013-03-25 22:28:37 +00003142 // Use a 'while' to peel off layers of typedefs.
3143 QualType TyTy = IntendedTy;
3144 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseec087352012-09-05 22:56:26 +00003145 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose2cd34402012-12-05 18:44:49 +00003146 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseec087352012-09-05 22:56:26 +00003147 .Case("NSInteger", S.Context.LongTy)
3148 .Case("NSUInteger", S.Context.UnsignedLongTy)
3149 .Case("SInt32", S.Context.IntTy)
3150 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose2cd34402012-12-05 18:44:49 +00003151 .Default(QualType());
3152
3153 if (!CastTy.isNull()) {
3154 ShouldNotPrintDirectly = true;
3155 IntendedTy = CastTy;
Ted Kremenek6edb0292013-03-25 22:28:37 +00003156 break;
Jordan Rose2cd34402012-12-05 18:44:49 +00003157 }
Ted Kremenek6edb0292013-03-25 22:28:37 +00003158 TyTy = UserTy->desugar();
Jordan Roseec087352012-09-05 22:56:26 +00003159 }
3160 }
3161
Jordan Rose614a8652012-09-05 22:56:19 +00003162 // We may be able to offer a FixItHint if it is a supported type.
3163 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00003164 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00003165 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003166
Jordan Rose614a8652012-09-05 22:56:19 +00003167 if (success) {
3168 // Get the fix string from the fixed format specifier
3169 SmallString<16> buf;
3170 llvm::raw_svector_ostream os(buf);
3171 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003172
Jordan Roseec087352012-09-05 22:56:26 +00003173 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3174
Jordan Rose2cd34402012-12-05 18:44:49 +00003175 if (IntendedTy == ExprTy) {
3176 // In this case, the specifier is wrong and should be changed to match
3177 // the argument.
3178 EmitFormatDiagnostic(
3179 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3180 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3181 << E->getSourceRange(),
3182 E->getLocStart(),
3183 /*IsStringLocation*/false,
3184 SpecRange,
3185 FixItHint::CreateReplacement(SpecRange, os.str()));
3186
3187 } else {
Jordan Roseec087352012-09-05 22:56:26 +00003188 // The canonical type for formatting this value is different from the
3189 // actual type of the expression. (This occurs, for example, with Darwin's
3190 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3191 // should be printed as 'long' for 64-bit compatibility.)
3192 // Rather than emitting a normal format/argument mismatch, we want to
3193 // add a cast to the recommended type (and correct the format string
3194 // if necessary).
3195 SmallString<16> CastBuf;
3196 llvm::raw_svector_ostream CastFix(CastBuf);
3197 CastFix << "(";
3198 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3199 CastFix << ")";
3200
3201 SmallVector<FixItHint,4> Hints;
3202 if (!AT.matchesType(S.Context, IntendedTy))
3203 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3204
3205 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3206 // If there's already a cast present, just replace it.
3207 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3208 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3209
3210 } else if (!requiresParensToAddCast(E)) {
3211 // If the expression has high enough precedence,
3212 // just write the C-style cast.
3213 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3214 CastFix.str()));
3215 } else {
3216 // Otherwise, add parens around the expression as well as the cast.
3217 CastFix << "(";
3218 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3219 CastFix.str()));
3220
3221 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3222 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3223 }
3224
Jordan Rose2cd34402012-12-05 18:44:49 +00003225 if (ShouldNotPrintDirectly) {
3226 // The expression has a type that should not be printed directly.
3227 // We extract the name from the typedef because we don't want to show
3228 // the underlying type in the diagnostic.
3229 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseec087352012-09-05 22:56:26 +00003230
Jordan Rose2cd34402012-12-05 18:44:49 +00003231 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3232 << Name << IntendedTy
3233 << E->getSourceRange(),
3234 E->getLocStart(), /*IsStringLocation=*/false,
3235 SpecRange, Hints);
3236 } else {
3237 // In this case, the expression could be printed using a different
3238 // specifier, but we've decided that the specifier is probably correct
3239 // and we should cast instead. Just use the normal warning message.
3240 EmitFormatDiagnostic(
3241 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3242 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3243 << E->getSourceRange(),
3244 E->getLocStart(), /*IsStringLocation*/false,
3245 SpecRange, Hints);
3246 }
Jordan Roseec087352012-09-05 22:56:26 +00003247 }
Jordan Rose614a8652012-09-05 22:56:19 +00003248 } else {
3249 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3250 SpecifierLen);
3251 // Since the warning for passing non-POD types to variadic functions
3252 // was deferred until now, we emit a warning for non-POD
3253 // arguments here.
Richard Smith0e218972013-08-05 18:49:43 +00003254 switch (S.isValidVarArgType(ExprTy)) {
3255 case Sema::VAK_Valid:
3256 case Sema::VAK_ValidInCXX11:
Jordan Rose614a8652012-09-05 22:56:19 +00003257 EmitFormatDiagnostic(
Richard Smith0e218972013-08-05 18:49:43 +00003258 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3259 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3260 << CSR
3261 << E->getSourceRange(),
3262 E->getLocStart(), /*IsStringLocation*/false, CSR);
3263 break;
3264
3265 case Sema::VAK_Undefined:
3266 EmitFormatDiagnostic(
3267 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith80ad52f2013-01-02 11:42:31 +00003268 << S.getLangOpts().CPlusPlus11
Jordan Rose448ac3e2012-12-05 18:44:40 +00003269 << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00003270 << CallType
3271 << AT.getRepresentativeTypeName(S.Context)
3272 << CSR
3273 << E->getSourceRange(),
3274 E->getLocStart(), /*IsStringLocation*/false, CSR);
Jordan Rose614a8652012-09-05 22:56:19 +00003275 checkForCStrMembers(AT, E, CSR);
Richard Smith0e218972013-08-05 18:49:43 +00003276 break;
3277
3278 case Sema::VAK_Invalid:
3279 if (ExprTy->isObjCObjectType())
3280 EmitFormatDiagnostic(
3281 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3282 << S.getLangOpts().CPlusPlus11
3283 << ExprTy
3284 << CallType
3285 << AT.getRepresentativeTypeName(S.Context)
3286 << CSR
3287 << E->getSourceRange(),
3288 E->getLocStart(), /*IsStringLocation*/false, CSR);
3289 else
3290 // FIXME: If this is an initializer list, suggest removing the braces
3291 // or inserting a cast to the target type.
3292 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3293 << isa<InitListExpr>(E) << ExprTy << CallType
3294 << AT.getRepresentativeTypeName(S.Context)
3295 << E->getSourceRange();
3296 break;
3297 }
3298
3299 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3300 "format string specifier index out of range");
3301 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003302 }
3303
Ted Kremeneke0e53132010-01-28 23:39:18 +00003304 return true;
3305}
3306
Ted Kremenek826a3452010-07-16 02:11:22 +00003307//===--- CHECK: Scanf format string checking ------------------------------===//
3308
3309namespace {
3310class CheckScanfHandler : public CheckFormatHandler {
3311public:
3312 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3313 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003314 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003315 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003316 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00003317 Sema::VariadicCallType CallType,
3318 llvm::SmallBitVector &CheckedVarArgs)
3319 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3320 numDataArgs, beg, hasVAListArg,
3321 Args, formatIdx, inFunctionCall, CallType,
3322 CheckedVarArgs)
Jordan Roseddcfbc92012-07-19 18:10:23 +00003323 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00003324
3325 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3326 const char *startSpecifier,
3327 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003328
3329 bool HandleInvalidScanfConversionSpecifier(
3330 const analyze_scanf::ScanfSpecifier &FS,
3331 const char *startSpecifier,
3332 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00003333
3334 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00003335};
Ted Kremenek07d161f2010-01-29 01:50:07 +00003336}
Ted Kremeneke0e53132010-01-28 23:39:18 +00003337
Ted Kremenekb7c21012010-07-16 18:28:03 +00003338void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3339 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00003340 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3341 getLocationOfByte(end), /*IsStringLocation*/true,
3342 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00003343}
3344
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003345bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3346 const analyze_scanf::ScanfSpecifier &FS,
3347 const char *startSpecifier,
3348 unsigned specifierLen) {
3349
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003350 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003351 FS.getConversionSpecifier();
3352
3353 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3354 getLocationOfByte(CS.getStart()),
3355 startSpecifier, specifierLen,
3356 CS.getStart(), CS.getLength());
3357}
3358
Ted Kremenek826a3452010-07-16 02:11:22 +00003359bool CheckScanfHandler::HandleScanfSpecifier(
3360 const analyze_scanf::ScanfSpecifier &FS,
3361 const char *startSpecifier,
3362 unsigned specifierLen) {
3363
3364 using namespace analyze_scanf;
3365 using namespace analyze_format_string;
3366
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003367 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00003368
Ted Kremenekbaa40062010-07-19 22:01:06 +00003369 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3370 // be used to decide if we are using positional arguments consistently.
3371 if (FS.consumesDataArgument()) {
3372 if (atFirstArg) {
3373 atFirstArg = false;
3374 usesPositionalArgs = FS.usesPositionalArg();
3375 }
3376 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003377 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3378 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003379 return false;
3380 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003381 }
3382
3383 // Check if the field with is non-zero.
3384 const OptionalAmount &Amt = FS.getFieldWidth();
3385 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3386 if (Amt.getConstantAmount() == 0) {
3387 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3388 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00003389 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3390 getLocationOfByte(Amt.getStart()),
3391 /*IsStringLocation*/true, R,
3392 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00003393 }
3394 }
3395
3396 if (!FS.consumesDataArgument()) {
3397 // FIXME: Technically specifying a precision or field width here
3398 // makes no sense. Worth issuing a warning at some point.
3399 return true;
3400 }
3401
3402 // Consume the argument.
3403 unsigned argIndex = FS.getArgIndex();
3404 if (argIndex < NumDataArgs) {
3405 // The check to see if the argIndex is valid will come later.
3406 // We set the bit here because we may exit early from this
3407 // function if we encounter some other error.
3408 CoveredArgs.set(argIndex);
3409 }
3410
Ted Kremenek1e51c202010-07-20 20:04:47 +00003411 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003412 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003413 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3414 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003415 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003416 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003417 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003418 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3419 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00003420
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003421 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3422 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3423
Ted Kremenek826a3452010-07-16 02:11:22 +00003424 // The remaining checks depend on the data arguments.
3425 if (HasVAListArg)
3426 return true;
3427
Ted Kremenek666a1972010-07-26 19:45:42 +00003428 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00003429 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00003430
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003431 // Check that the argument type matches the format specifier.
3432 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00003433 if (!Ex)
3434 return true;
3435
Hans Wennborg58e1e542012-08-07 08:59:46 +00003436 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3437 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003438 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00003439 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00003440 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003441
3442 if (success) {
3443 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003444 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003445 llvm::raw_svector_ostream os(buf);
3446 fixedFS.toString(os);
3447
3448 EmitFormatDiagnostic(
3449 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003450 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003451 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003452 Ex->getLocStart(),
3453 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003454 getSpecifierRange(startSpecifier, specifierLen),
3455 FixItHint::CreateReplacement(
3456 getSpecifierRange(startSpecifier, specifierLen),
3457 os.str()));
3458 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003459 EmitFormatDiagnostic(
3460 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003461 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003462 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003463 Ex->getLocStart(),
3464 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003465 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003466 }
3467 }
3468
Ted Kremenek826a3452010-07-16 02:11:22 +00003469 return true;
3470}
3471
3472void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003473 const Expr *OrigFormatExpr,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003474 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003475 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003476 unsigned firstDataArg, FormatStringType Type,
Richard Smith0e218972013-08-05 18:49:43 +00003477 bool inFunctionCall, VariadicCallType CallType,
3478 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003479
Ted Kremeneke0e53132010-01-28 23:39:18 +00003480 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00003481 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003482 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003483 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003484 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3485 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003486 return;
3487 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003488
Ted Kremeneke0e53132010-01-28 23:39:18 +00003489 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00003490 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003491 const char *Str = StrRef.data();
3492 unsigned StrLen = StrRef.size();
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003493 const unsigned numDataArgs = Args.size() - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00003494
Ted Kremeneke0e53132010-01-28 23:39:18 +00003495 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00003496 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00003497 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003498 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003499 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3500 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003501 return;
3502 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003503
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003504 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003505 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003506 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003507 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00003508 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00003509
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003510 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003511 getLangOpts(),
3512 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003513 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003514 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00003515 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003516 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00003517 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00003518
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003519 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003520 getLangOpts(),
3521 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003522 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003523 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00003524}
3525
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003526//===--- CHECK: Standard memory functions ---------------------------------===//
3527
Douglas Gregor2a053a32011-05-03 20:05:22 +00003528/// \brief Determine whether the given type is a dynamic class type (e.g.,
3529/// whether it has a vtable).
3530static bool isDynamicClassType(QualType T) {
3531 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3532 if (CXXRecordDecl *Definition = Record->getDefinition())
3533 if (Definition->isDynamicClass())
3534 return true;
3535
3536 return false;
3537}
3538
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003539/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00003540/// otherwise returns NULL.
3541static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00003542 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00003543 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3544 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3545 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003546
Chandler Carruth000d4282011-06-16 09:09:40 +00003547 return 0;
3548}
3549
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003550/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00003551static QualType getSizeOfArgType(const Expr* E) {
3552 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3553 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3554 if (SizeOf->getKind() == clang::UETT_SizeOf)
3555 return SizeOf->getTypeOfArgument();
3556
3557 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00003558}
3559
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003560/// \brief Check for dangerous or invalid arguments to memset().
3561///
Chandler Carruth929f0132011-06-03 06:23:57 +00003562/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003563/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3564/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003565///
3566/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003567void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00003568 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003569 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00003570 assert(BId != 0);
3571
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003572 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00003573 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00003574 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00003575 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003576 return;
3577
Anna Zaks0a151a12012-01-17 00:37:07 +00003578 unsigned LastArg = (BId == Builtin::BImemset ||
3579 BId == Builtin::BIstrndup ? 1 : 2);
3580 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00003581 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00003582
3583 // We have special checking when the length is a sizeof expression.
3584 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3585 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3586 llvm::FoldingSetNodeID SizeOfArgID;
3587
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003588 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3589 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003590 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003591
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003592 QualType DestTy = Dest->getType();
3593 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3594 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00003595
Chandler Carruth000d4282011-06-16 09:09:40 +00003596 // Never warn about void type pointers. This can be used to suppress
3597 // false positives.
3598 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003599 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003600
Chandler Carruth000d4282011-06-16 09:09:40 +00003601 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3602 // actually comparing the expressions for equality. Because computing the
3603 // expression IDs can be expensive, we only do this if the diagnostic is
3604 // enabled.
3605 if (SizeOfArg &&
3606 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3607 SizeOfArg->getExprLoc())) {
3608 // We only compute IDs for expressions if the warning is enabled, and
3609 // cache the sizeof arg's ID.
3610 if (SizeOfArgID == llvm::FoldingSetNodeID())
3611 SizeOfArg->Profile(SizeOfArgID, Context, true);
3612 llvm::FoldingSetNodeID DestID;
3613 Dest->Profile(DestID, Context, true);
3614 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00003615 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3616 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00003617 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003618 StringRef ReadableName = FnName->getName();
3619
Chandler Carruth000d4282011-06-16 09:09:40 +00003620 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00003621 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00003622 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian7adf4172013-01-30 01:12:44 +00003623 if (!PointeeTy->isIncompleteType() &&
3624 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth000d4282011-06-16 09:09:40 +00003625 ActionIdx = 2; // If the pointee's size is sizeof(char),
3626 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003627
3628 // If the function is defined as a builtin macro, do not show macro
3629 // expansion.
3630 SourceLocation SL = SizeOfArg->getExprLoc();
3631 SourceRange DSR = Dest->getSourceRange();
3632 SourceRange SSR = SizeOfArg->getSourceRange();
3633 SourceManager &SM = PP.getSourceManager();
3634
3635 if (SM.isMacroArgExpansion(SL)) {
3636 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3637 SL = SM.getSpellingLoc(SL);
3638 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3639 SM.getSpellingLoc(DSR.getEnd()));
3640 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3641 SM.getSpellingLoc(SSR.getEnd()));
3642 }
3643
Anna Zaks90c78322012-05-30 23:14:52 +00003644 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00003645 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00003646 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00003647 << PointeeTy
3648 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00003649 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00003650 << SSR);
3651 DiagRuntimeBehavior(SL, SizeOfArg,
3652 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3653 << ActionIdx
3654 << SSR);
3655
Chandler Carruth000d4282011-06-16 09:09:40 +00003656 break;
3657 }
3658 }
3659
3660 // Also check for cases where the sizeof argument is the exact same
3661 // type as the memory argument, and where it points to a user-defined
3662 // record type.
3663 if (SizeOfArgTy != QualType()) {
3664 if (PointeeTy->isRecordType() &&
3665 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3666 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3667 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3668 << FnName << SizeOfArgTy << ArgIdx
3669 << PointeeTy << Dest->getSourceRange()
3670 << LenExpr->getSourceRange());
3671 break;
3672 }
Nico Webere4a1c642011-06-14 16:14:58 +00003673 }
3674
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003675 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00003676 if (isDynamicClassType(PointeeTy)) {
3677
3678 unsigned OperationType = 0;
3679 // "overwritten" if we're warning about the destination for any call
3680 // but memcmp; otherwise a verb appropriate to the call.
3681 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3682 if (BId == Builtin::BImemcpy)
3683 OperationType = 1;
3684 else if(BId == Builtin::BImemmove)
3685 OperationType = 2;
3686 else if (BId == Builtin::BImemcmp)
3687 OperationType = 3;
3688 }
3689
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003690 DiagRuntimeBehavior(
3691 Dest->getExprLoc(), Dest,
3692 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003693 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003694 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003695 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003696 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003697 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3698 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003699 DiagRuntimeBehavior(
3700 Dest->getExprLoc(), Dest,
3701 PDiag(diag::warn_arc_object_memaccess)
3702 << ArgIdx << FnName << PointeeTy
3703 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003704 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003705 continue;
John McCallf85e1932011-06-15 23:02:42 +00003706
3707 DiagRuntimeBehavior(
3708 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003709 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003710 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3711 break;
3712 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003713 }
3714}
3715
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003716// A little helper routine: ignore addition and subtraction of integer literals.
3717// This intentionally does not ignore all integer constant expressions because
3718// we don't want to remove sizeof().
3719static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3720 Ex = Ex->IgnoreParenCasts();
3721
3722 for (;;) {
3723 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3724 if (!BO || !BO->isAdditiveOp())
3725 break;
3726
3727 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3728 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3729
3730 if (isa<IntegerLiteral>(RHS))
3731 Ex = LHS;
3732 else if (isa<IntegerLiteral>(LHS))
3733 Ex = RHS;
3734 else
3735 break;
3736 }
3737
3738 return Ex;
3739}
3740
Anna Zaks0f38ace2012-08-08 21:42:23 +00003741static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3742 ASTContext &Context) {
3743 // Only handle constant-sized or VLAs, but not flexible members.
3744 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3745 // Only issue the FIXIT for arrays of size > 1.
3746 if (CAT->getSize().getSExtValue() <= 1)
3747 return false;
3748 } else if (!Ty->isVariableArrayType()) {
3749 return false;
3750 }
3751 return true;
3752}
3753
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003754// Warn if the user has made the 'size' argument to strlcpy or strlcat
3755// be the size of the source, instead of the destination.
3756void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3757 IdentifierInfo *FnName) {
3758
3759 // Don't crash if the user has the wrong number of arguments
3760 if (Call->getNumArgs() != 3)
3761 return;
3762
3763 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3764 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3765 const Expr *CompareWithSrc = NULL;
3766
3767 // Look for 'strlcpy(dst, x, sizeof(x))'
3768 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3769 CompareWithSrc = Ex;
3770 else {
3771 // Look for 'strlcpy(dst, x, strlen(x))'
3772 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003773 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003774 && SizeCall->getNumArgs() == 1)
3775 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3776 }
3777 }
3778
3779 if (!CompareWithSrc)
3780 return;
3781
3782 // Determine if the argument to sizeof/strlen is equal to the source
3783 // argument. In principle there's all kinds of things you could do
3784 // here, for instance creating an == expression and evaluating it with
3785 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3786 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3787 if (!SrcArgDRE)
3788 return;
3789
3790 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3791 if (!CompareWithSrcDRE ||
3792 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3793 return;
3794
3795 const Expr *OriginalSizeArg = Call->getArg(2);
3796 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3797 << OriginalSizeArg->getSourceRange() << FnName;
3798
3799 // Output a FIXIT hint if the destination is an array (rather than a
3800 // pointer to an array). This could be enhanced to handle some
3801 // pointers if we know the actual size, like if DstArg is 'array+2'
3802 // we could say 'sizeof(array)-2'.
3803 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00003804 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00003805 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00003806
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003807 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003808 llvm::raw_svector_ostream OS(sizeString);
3809 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003810 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003811 OS << ")";
3812
3813 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3814 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3815 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003816}
3817
Anna Zaksc36bedc2012-02-01 19:08:57 +00003818/// Check if two expressions refer to the same declaration.
3819static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3820 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3821 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3822 return D1->getDecl() == D2->getDecl();
3823 return false;
3824}
3825
3826static const Expr *getStrlenExprArg(const Expr *E) {
3827 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3828 const FunctionDecl *FD = CE->getDirectCallee();
3829 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3830 return 0;
3831 return CE->getArg(0)->IgnoreParenCasts();
3832 }
3833 return 0;
3834}
3835
3836// Warn on anti-patterns as the 'size' argument to strncat.
3837// The correct size argument should look like following:
3838// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3839void Sema::CheckStrncatArguments(const CallExpr *CE,
3840 IdentifierInfo *FnName) {
3841 // Don't crash if the user has the wrong number of arguments.
3842 if (CE->getNumArgs() < 3)
3843 return;
3844 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3845 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3846 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3847
3848 // Identify common expressions, which are wrongly used as the size argument
3849 // to strncat and may lead to buffer overflows.
3850 unsigned PatternType = 0;
3851 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3852 // - sizeof(dst)
3853 if (referToTheSameDecl(SizeOfArg, DstArg))
3854 PatternType = 1;
3855 // - sizeof(src)
3856 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3857 PatternType = 2;
3858 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3859 if (BE->getOpcode() == BO_Sub) {
3860 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3861 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3862 // - sizeof(dst) - strlen(dst)
3863 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3864 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3865 PatternType = 1;
3866 // - sizeof(src) - (anything)
3867 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3868 PatternType = 2;
3869 }
3870 }
3871
3872 if (PatternType == 0)
3873 return;
3874
Anna Zaksafdb0412012-02-03 01:27:37 +00003875 // Generate the diagnostic.
3876 SourceLocation SL = LenArg->getLocStart();
3877 SourceRange SR = LenArg->getSourceRange();
3878 SourceManager &SM = PP.getSourceManager();
3879
3880 // If the function is defined as a builtin macro, do not show macro expansion.
3881 if (SM.isMacroArgExpansion(SL)) {
3882 SL = SM.getSpellingLoc(SL);
3883 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3884 SM.getSpellingLoc(SR.getEnd()));
3885 }
3886
Anna Zaks0f38ace2012-08-08 21:42:23 +00003887 // Check if the destination is an array (rather than a pointer to an array).
3888 QualType DstTy = DstArg->getType();
3889 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3890 Context);
3891 if (!isKnownSizeArray) {
3892 if (PatternType == 1)
3893 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3894 else
3895 Diag(SL, diag::warn_strncat_src_size) << SR;
3896 return;
3897 }
3898
Anna Zaksc36bedc2012-02-01 19:08:57 +00003899 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003900 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003901 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003902 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003903
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003904 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003905 llvm::raw_svector_ostream OS(sizeString);
3906 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003907 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003908 OS << ") - ";
3909 OS << "strlen(";
Richard Smithd1420c62012-08-16 03:56:14 +00003910 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003911 OS << ") - 1";
3912
Anna Zaksafdb0412012-02-03 01:27:37 +00003913 Diag(SL, diag::note_strncat_wrong_size)
3914 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003915}
3916
Ted Kremenek06de2762007-08-17 16:46:58 +00003917//===--- CHECK: Return Address of Stack Variable --------------------------===//
3918
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003919static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3920 Decl *ParentDecl);
3921static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3922 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003923
3924/// CheckReturnStackAddr - Check if a return statement returns the address
3925/// of a stack variable.
3926void
3927Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3928 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003929
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003930 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003931 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003932
3933 // Perform checking for returned stack addresses, local blocks,
3934 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003935 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003936 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003937 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003938 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003939 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003940 }
3941
3942 if (stackE == 0)
3943 return; // Nothing suspicious was found.
3944
3945 SourceLocation diagLoc;
3946 SourceRange diagRange;
3947 if (refVars.empty()) {
3948 diagLoc = stackE->getLocStart();
3949 diagRange = stackE->getSourceRange();
3950 } else {
3951 // We followed through a reference variable. 'stackE' contains the
3952 // problematic expression but we will warn at the return statement pointing
3953 // at the reference variable. We will later display the "trail" of
3954 // reference variables using notes.
3955 diagLoc = refVars[0]->getLocStart();
3956 diagRange = refVars[0]->getSourceRange();
3957 }
3958
3959 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3960 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3961 : diag::warn_ret_stack_addr)
3962 << DR->getDecl()->getDeclName() << diagRange;
3963 } else if (isa<BlockExpr>(stackE)) { // local block.
3964 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3965 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3966 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3967 } else { // local temporary.
3968 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3969 : diag::warn_ret_local_temp_addr)
3970 << diagRange;
3971 }
3972
3973 // Display the "trail" of reference variables that we followed until we
3974 // found the problematic expression using notes.
3975 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3976 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3977 // If this var binds to another reference var, show the range of the next
3978 // var, otherwise the var binds to the problematic expression, in which case
3979 // show the range of the expression.
3980 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3981 : stackE->getSourceRange();
3982 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3983 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003984 }
3985}
3986
3987/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3988/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003989/// to a location on the stack, a local block, an address of a label, or a
3990/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003991/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003992/// encounter a subexpression that (1) clearly does not lead to one of the
3993/// above problematic expressions (2) is something we cannot determine leads to
3994/// a problematic expression based on such local checking.
3995///
3996/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3997/// the expression that they point to. Such variables are added to the
3998/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003999///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00004000/// EvalAddr processes expressions that are pointers that are used as
4001/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004002/// At the base case of the recursion is a check for the above problematic
4003/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00004004///
4005/// This implementation handles:
4006///
4007/// * pointer-to-pointer casts
4008/// * implicit conversions from array references to pointers
4009/// * taking the address of fields
4010/// * arbitrary interplay between "&" and "*" operators
4011/// * pointer arithmetic from an address of a stack variable
4012/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004013static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4014 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004015 if (E->isTypeDependent())
Craig Topperb61c2942013-08-02 05:10:31 +00004016 return NULL;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004017
Ted Kremenek06de2762007-08-17 16:46:58 +00004018 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00004019 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00004020 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004021 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004022 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00004023
Peter Collingbournef111d932011-04-15 00:35:48 +00004024 E = E->IgnoreParens();
4025
Ted Kremenek06de2762007-08-17 16:46:58 +00004026 // Our "symbolic interpreter" is just a dispatch off the currently
4027 // viewed AST node. We then recursively traverse the AST by calling
4028 // EvalAddr and EvalVal appropriately.
4029 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004030 case Stmt::DeclRefExprClass: {
4031 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4032
4033 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4034 // If this is a reference variable, follow through to the expression that
4035 // it points to.
4036 if (V->hasLocalStorage() &&
4037 V->getType()->isReferenceType() && V->hasInit()) {
4038 // Add the reference variable to the "trail".
4039 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004040 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004041 }
4042
4043 return NULL;
4044 }
Ted Kremenek06de2762007-08-17 16:46:58 +00004045
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004046 case Stmt::UnaryOperatorClass: {
4047 // The only unary operator that make sense to handle here
4048 // is AddrOf. All others don't make sense as pointers.
4049 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004050
John McCall2de56d12010-08-25 11:45:40 +00004051 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004052 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004053 else
Ted Kremenek06de2762007-08-17 16:46:58 +00004054 return NULL;
4055 }
Mike Stump1eb44332009-09-09 15:08:12 +00004056
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004057 case Stmt::BinaryOperatorClass: {
4058 // Handle pointer arithmetic. All other binary operators are not valid
4059 // in this context.
4060 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00004061 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00004062
John McCall2de56d12010-08-25 11:45:40 +00004063 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004064 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00004065
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004066 Expr *Base = B->getLHS();
4067
4068 // Determine which argument is the real pointer base. It could be
4069 // the RHS argument instead of the LHS.
4070 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00004071
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004072 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004073 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004074 }
Steve Naroff61f40a22008-09-10 19:17:48 +00004075
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004076 // For conditional operators we need to see if either the LHS or RHS are
4077 // valid DeclRefExpr*s. If one of them is valid, we return it.
4078 case Stmt::ConditionalOperatorClass: {
4079 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004080
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004081 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004082 if (Expr *lhsExpr = C->getLHS()) {
4083 // In C++, we can have a throw-expression, which has 'void' type.
4084 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004085 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004086 return LHS;
4087 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004088
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004089 // In C++, we can have a throw-expression, which has 'void' type.
4090 if (C->getRHS()->getType()->isVoidType())
4091 return NULL;
4092
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004093 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004094 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004095
4096 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00004097 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004098 return E; // local block.
4099 return NULL;
4100
4101 case Stmt::AddrLabelExprClass:
4102 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00004103
John McCall80ee6e82011-11-10 05:35:25 +00004104 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004105 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4106 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00004107
Ted Kremenek54b52742008-08-07 00:49:01 +00004108 // For casts, we need to handle conversions from arrays to
4109 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00004110 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00004111 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00004112 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00004113 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00004114 case Stmt::CXXStaticCastExprClass:
4115 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00004116 case Stmt::CXXConstCastExprClass:
4117 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00004118 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4119 switch (cast<CastExpr>(E)->getCastKind()) {
4120 case CK_BitCast:
4121 case CK_LValueToRValue:
4122 case CK_NoOp:
4123 case CK_BaseToDerived:
4124 case CK_DerivedToBase:
4125 case CK_UncheckedDerivedToBase:
4126 case CK_Dynamic:
4127 case CK_CPointerToObjCPointerCast:
4128 case CK_BlockPointerToObjCPointerCast:
4129 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004130 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00004131
4132 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004133 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00004134
4135 default:
4136 return 0;
4137 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004138 }
Mike Stump1eb44332009-09-09 15:08:12 +00004139
Douglas Gregor03e80032011-06-21 17:03:29 +00004140 case Stmt::MaterializeTemporaryExprClass:
4141 if (Expr *Result = EvalAddr(
4142 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004143 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00004144 return Result;
4145
4146 return E;
4147
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004148 // Everything else: we simply don't reason about them.
4149 default:
4150 return NULL;
4151 }
Ted Kremenek06de2762007-08-17 16:46:58 +00004152}
Mike Stump1eb44332009-09-09 15:08:12 +00004153
Ted Kremenek06de2762007-08-17 16:46:58 +00004154
4155/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4156/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004157static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4158 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004159do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00004160 // We should only be called for evaluating non-pointer expressions, or
4161 // expressions with a pointer type that are not used as references but instead
4162 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00004163
Ted Kremenek06de2762007-08-17 16:46:58 +00004164 // Our "symbolic interpreter" is just a dispatch off the currently
4165 // viewed AST node. We then recursively traverse the AST by calling
4166 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00004167
4168 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00004169 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004170 case Stmt::ImplicitCastExprClass: {
4171 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00004172 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004173 E = IE->getSubExpr();
4174 continue;
4175 }
4176 return NULL;
4177 }
4178
John McCall80ee6e82011-11-10 05:35:25 +00004179 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004180 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00004181
Douglas Gregora2813ce2009-10-23 18:54:35 +00004182 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004183 // When we hit a DeclRefExpr we are looking at code that refers to a
4184 // variable's name. If it's not a reference variable we check if it has
4185 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00004186 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004187
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004188 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4189 // Check if it refers to itself, e.g. "int& i = i;".
4190 if (V == ParentDecl)
4191 return DR;
4192
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004193 if (V->hasLocalStorage()) {
4194 if (!V->getType()->isReferenceType())
4195 return DR;
4196
4197 // Reference variable, follow through to the expression that
4198 // it points to.
4199 if (V->hasInit()) {
4200 // Add the reference variable to the "trail".
4201 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004202 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004203 }
4204 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004205 }
Mike Stump1eb44332009-09-09 15:08:12 +00004206
Ted Kremenek06de2762007-08-17 16:46:58 +00004207 return NULL;
4208 }
Mike Stump1eb44332009-09-09 15:08:12 +00004209
Ted Kremenek06de2762007-08-17 16:46:58 +00004210 case Stmt::UnaryOperatorClass: {
4211 // The only unary operator that make sense to handle here
4212 // is Deref. All others don't resolve to a "name." This includes
4213 // handling all sorts of rvalues passed to a unary operator.
4214 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004215
John McCall2de56d12010-08-25 11:45:40 +00004216 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004217 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004218
4219 return NULL;
4220 }
Mike Stump1eb44332009-09-09 15:08:12 +00004221
Ted Kremenek06de2762007-08-17 16:46:58 +00004222 case Stmt::ArraySubscriptExprClass: {
4223 // Array subscripts are potential references to data on the stack. We
4224 // retrieve the DeclRefExpr* for the array variable if it indeed
4225 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004226 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004227 }
Mike Stump1eb44332009-09-09 15:08:12 +00004228
Ted Kremenek06de2762007-08-17 16:46:58 +00004229 case Stmt::ConditionalOperatorClass: {
4230 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004231 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00004232 ConditionalOperator *C = cast<ConditionalOperator>(E);
4233
Anders Carlsson39073232007-11-30 19:04:31 +00004234 // Handle the GNU extension for missing LHS.
4235 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004236 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00004237 return LHS;
4238
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004239 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004240 }
Mike Stump1eb44332009-09-09 15:08:12 +00004241
Ted Kremenek06de2762007-08-17 16:46:58 +00004242 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00004243 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00004244 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004245
Ted Kremenek06de2762007-08-17 16:46:58 +00004246 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00004247 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00004248 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00004249
4250 // Check whether the member type is itself a reference, in which case
4251 // we're not going to refer to the member, but to what the member refers to.
4252 if (M->getMemberDecl()->getType()->isReferenceType())
4253 return NULL;
4254
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004255 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004256 }
Mike Stump1eb44332009-09-09 15:08:12 +00004257
Douglas Gregor03e80032011-06-21 17:03:29 +00004258 case Stmt::MaterializeTemporaryExprClass:
4259 if (Expr *Result = EvalVal(
4260 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004261 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00004262 return Result;
4263
4264 return E;
4265
Ted Kremenek06de2762007-08-17 16:46:58 +00004266 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004267 // Check that we don't return or take the address of a reference to a
4268 // temporary. This is only useful in C++.
4269 if (!E->isTypeDependent() && E->isRValue())
4270 return E;
4271
4272 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00004273 return NULL;
4274 }
Ted Kremenek68957a92010-08-04 20:01:07 +00004275} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00004276}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004277
4278//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4279
4280/// Check for comparisons of floating point operands using != and ==.
4281/// Issue a warning if these are no self-comparisons, as they are not likely
4282/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00004283void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00004284 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4285 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004286
4287 // Special case: check for x == x (which is OK).
4288 // Do not emit warnings for such cases.
4289 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4290 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4291 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00004292 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004293
4294
Ted Kremenek1b500bb2007-11-29 00:59:04 +00004295 // Special case: check for comparisons against literals that can be exactly
4296 // represented by APFloat. In such cases, do not emit a warning. This
4297 // is a heuristic: often comparison against such literals are used to
4298 // detect if a value in a variable has not changed. This clearly can
4299 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00004300 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4301 if (FLL->isExact())
4302 return;
4303 } else
4304 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4305 if (FLR->isExact())
4306 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004307
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004308 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00004309 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
4310 if (CL->isBuiltinCall())
4311 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004312
David Blaikie980343b2012-07-16 20:47:22 +00004313 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
4314 if (CR->isBuiltinCall())
4315 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004316
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004317 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00004318 Diag(Loc, diag::warn_floatingpoint_eq)
4319 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004320}
John McCallba26e582010-01-04 23:21:16 +00004321
John McCallf2370c92010-01-06 05:24:50 +00004322//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4323//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00004324
John McCallf2370c92010-01-06 05:24:50 +00004325namespace {
John McCallba26e582010-01-04 23:21:16 +00004326
John McCallf2370c92010-01-06 05:24:50 +00004327/// Structure recording the 'active' range of an integer-valued
4328/// expression.
4329struct IntRange {
4330 /// The number of bits active in the int.
4331 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00004332
John McCallf2370c92010-01-06 05:24:50 +00004333 /// True if the int is known not to have negative values.
4334 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00004335
John McCallf2370c92010-01-06 05:24:50 +00004336 IntRange(unsigned Width, bool NonNegative)
4337 : Width(Width), NonNegative(NonNegative)
4338 {}
John McCallba26e582010-01-04 23:21:16 +00004339
John McCall1844a6e2010-11-10 23:38:19 +00004340 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00004341 static IntRange forBoolType() {
4342 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00004343 }
4344
John McCall1844a6e2010-11-10 23:38:19 +00004345 /// Returns the range of an opaque value of the given integral type.
4346 static IntRange forValueOfType(ASTContext &C, QualType T) {
4347 return forValueOfCanonicalType(C,
4348 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00004349 }
4350
John McCall1844a6e2010-11-10 23:38:19 +00004351 /// Returns the range of an opaque value of a canonical integral type.
4352 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00004353 assert(T->isCanonicalUnqualified());
4354
4355 if (const VectorType *VT = dyn_cast<VectorType>(T))
4356 T = VT->getElementType().getTypePtr();
4357 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4358 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00004359
David Majnemerf9eaf982013-06-07 22:07:20 +00004360 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00004361 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemerf9eaf982013-06-07 22:07:20 +00004362 EnumDecl *Enum = ET->getDecl();
4363 if (!Enum->isCompleteDefinition())
4364 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall091f23f2010-11-09 22:22:12 +00004365
David Majnemerf9eaf982013-06-07 22:07:20 +00004366 unsigned NumPositive = Enum->getNumPositiveBits();
4367 unsigned NumNegative = Enum->getNumNegativeBits();
John McCall323ed742010-05-06 08:58:33 +00004368
David Majnemerf9eaf982013-06-07 22:07:20 +00004369 if (NumNegative == 0)
4370 return IntRange(NumPositive, true/*NonNegative*/);
4371 else
4372 return IntRange(std::max(NumPositive + 1, NumNegative),
4373 false/*NonNegative*/);
John McCall323ed742010-05-06 08:58:33 +00004374 }
John McCallf2370c92010-01-06 05:24:50 +00004375
4376 const BuiltinType *BT = cast<BuiltinType>(T);
4377 assert(BT->isInteger());
4378
4379 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4380 }
4381
John McCall1844a6e2010-11-10 23:38:19 +00004382 /// Returns the "target" range of a canonical integral type, i.e.
4383 /// the range of values expressible in the type.
4384 ///
4385 /// This matches forValueOfCanonicalType except that enums have the
4386 /// full range of their type, not the range of their enumerators.
4387 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4388 assert(T->isCanonicalUnqualified());
4389
4390 if (const VectorType *VT = dyn_cast<VectorType>(T))
4391 T = VT->getElementType().getTypePtr();
4392 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4393 T = CT->getElementType().getTypePtr();
4394 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00004395 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00004396
4397 const BuiltinType *BT = cast<BuiltinType>(T);
4398 assert(BT->isInteger());
4399
4400 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4401 }
4402
4403 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004404 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00004405 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00004406 L.NonNegative && R.NonNegative);
4407 }
4408
John McCall1844a6e2010-11-10 23:38:19 +00004409 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004410 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00004411 return IntRange(std::min(L.Width, R.Width),
4412 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00004413 }
4414};
4415
Ted Kremenek0692a192012-01-31 05:37:37 +00004416static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4417 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004418 if (value.isSigned() && value.isNegative())
4419 return IntRange(value.getMinSignedBits(), false);
4420
4421 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00004422 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004423
4424 // isNonNegative() just checks the sign bit without considering
4425 // signedness.
4426 return IntRange(value.getActiveBits(), true);
4427}
4428
Ted Kremenek0692a192012-01-31 05:37:37 +00004429static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4430 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004431 if (result.isInt())
4432 return GetValueRange(C, result.getInt(), MaxWidth);
4433
4434 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00004435 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4436 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4437 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4438 R = IntRange::join(R, El);
4439 }
John McCallf2370c92010-01-06 05:24:50 +00004440 return R;
4441 }
4442
4443 if (result.isComplexInt()) {
4444 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4445 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4446 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00004447 }
4448
4449 // This can happen with lossless casts to intptr_t of "based" lvalues.
4450 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00004451 // FIXME: The only reason we need to pass the type in here is to get
4452 // the sign right on this one case. It would be nice if APValue
4453 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00004454 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004455 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00004456}
John McCallf2370c92010-01-06 05:24:50 +00004457
Eli Friedman09bddcf2013-07-08 20:20:06 +00004458static QualType GetExprType(Expr *E) {
4459 QualType Ty = E->getType();
4460 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4461 Ty = AtomicRHS->getValueType();
4462 return Ty;
4463}
4464
John McCallf2370c92010-01-06 05:24:50 +00004465/// Pseudo-evaluate the given integer expression, estimating the
4466/// range of values it might take.
4467///
4468/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00004469static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004470 E = E->IgnoreParens();
4471
4472 // Try a full evaluation first.
4473 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004474 if (E->EvaluateAsRValue(result, C))
Eli Friedman09bddcf2013-07-08 20:20:06 +00004475 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004476
4477 // I think we only want to look through implicit casts here; if the
4478 // user has an explicit widening cast, we should treat the value as
4479 // being of the new, wider type.
4480 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00004481 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00004482 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4483
Eli Friedman09bddcf2013-07-08 20:20:06 +00004484 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCallf2370c92010-01-06 05:24:50 +00004485
John McCall2de56d12010-08-25 11:45:40 +00004486 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00004487
John McCallf2370c92010-01-06 05:24:50 +00004488 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00004489 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00004490 return OutputTypeRange;
4491
4492 IntRange SubRange
4493 = GetExprRange(C, CE->getSubExpr(),
4494 std::min(MaxWidth, OutputTypeRange.Width));
4495
4496 // Bail out if the subexpr's range is as wide as the cast type.
4497 if (SubRange.Width >= OutputTypeRange.Width)
4498 return OutputTypeRange;
4499
4500 // Otherwise, we take the smaller width, and we're non-negative if
4501 // either the output type or the subexpr is.
4502 return IntRange(SubRange.Width,
4503 SubRange.NonNegative || OutputTypeRange.NonNegative);
4504 }
4505
4506 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4507 // If we can fold the condition, just take that operand.
4508 bool CondResult;
4509 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4510 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4511 : CO->getFalseExpr(),
4512 MaxWidth);
4513
4514 // Otherwise, conservatively merge.
4515 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4516 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4517 return IntRange::join(L, R);
4518 }
4519
4520 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4521 switch (BO->getOpcode()) {
4522
4523 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00004524 case BO_LAnd:
4525 case BO_LOr:
4526 case BO_LT:
4527 case BO_GT:
4528 case BO_LE:
4529 case BO_GE:
4530 case BO_EQ:
4531 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00004532 return IntRange::forBoolType();
4533
John McCall862ff872011-07-13 06:35:24 +00004534 // The type of the assignments is the type of the LHS, so the RHS
4535 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00004536 case BO_MulAssign:
4537 case BO_DivAssign:
4538 case BO_RemAssign:
4539 case BO_AddAssign:
4540 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00004541 case BO_XorAssign:
4542 case BO_OrAssign:
4543 // TODO: bitfields?
Eli Friedman09bddcf2013-07-08 20:20:06 +00004544 return IntRange::forValueOfType(C, GetExprType(E));
John McCallc0cd21d2010-02-23 19:22:29 +00004545
John McCall862ff872011-07-13 06:35:24 +00004546 // Simple assignments just pass through the RHS, which will have
4547 // been coerced to the LHS type.
4548 case BO_Assign:
4549 // TODO: bitfields?
4550 return GetExprRange(C, BO->getRHS(), MaxWidth);
4551
John McCallf2370c92010-01-06 05:24:50 +00004552 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004553 case BO_PtrMemD:
4554 case BO_PtrMemI:
Eli Friedman09bddcf2013-07-08 20:20:06 +00004555 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004556
John McCall60fad452010-01-06 22:07:33 +00004557 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00004558 case BO_And:
4559 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00004560 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4561 GetExprRange(C, BO->getRHS(), MaxWidth));
4562
John McCallf2370c92010-01-06 05:24:50 +00004563 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00004564 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00004565 // ...except that we want to treat '1 << (blah)' as logically
4566 // positive. It's an important idiom.
4567 if (IntegerLiteral *I
4568 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4569 if (I->getValue() == 1) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00004570 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall3aae6092010-04-07 01:14:35 +00004571 return IntRange(R.Width, /*NonNegative*/ true);
4572 }
4573 }
4574 // fallthrough
4575
John McCall2de56d12010-08-25 11:45:40 +00004576 case BO_ShlAssign:
Eli Friedman09bddcf2013-07-08 20:20:06 +00004577 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004578
John McCall60fad452010-01-06 22:07:33 +00004579 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00004580 case BO_Shr:
4581 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00004582 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4583
4584 // If the shift amount is a positive constant, drop the width by
4585 // that much.
4586 llvm::APSInt shift;
4587 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4588 shift.isNonNegative()) {
4589 unsigned zext = shift.getZExtValue();
4590 if (zext >= L.Width)
4591 L.Width = (L.NonNegative ? 0 : 1);
4592 else
4593 L.Width -= zext;
4594 }
4595
4596 return L;
4597 }
4598
4599 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00004600 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00004601 return GetExprRange(C, BO->getRHS(), MaxWidth);
4602
John McCall60fad452010-01-06 22:07:33 +00004603 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00004604 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00004605 if (BO->getLHS()->getType()->isPointerType())
Eli Friedman09bddcf2013-07-08 20:20:06 +00004606 return IntRange::forValueOfType(C, GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004607 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00004608
John McCall00fe7612011-07-14 22:39:48 +00004609 // The width of a division result is mostly determined by the size
4610 // of the LHS.
4611 case BO_Div: {
4612 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00004613 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004614 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4615
4616 // If the divisor is constant, use that.
4617 llvm::APSInt divisor;
4618 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4619 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4620 if (log2 >= L.Width)
4621 L.Width = (L.NonNegative ? 0 : 1);
4622 else
4623 L.Width = std::min(L.Width - log2, MaxWidth);
4624 return L;
4625 }
4626
4627 // Otherwise, just use the LHS's width.
4628 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4629 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4630 }
4631
4632 // The result of a remainder can't be larger than the result of
4633 // either side.
4634 case BO_Rem: {
4635 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00004636 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004637 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4638 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4639
4640 IntRange meet = IntRange::meet(L, R);
4641 meet.Width = std::min(meet.Width, MaxWidth);
4642 return meet;
4643 }
4644
4645 // The default behavior is okay for these.
4646 case BO_Mul:
4647 case BO_Add:
4648 case BO_Xor:
4649 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00004650 break;
4651 }
4652
John McCall00fe7612011-07-14 22:39:48 +00004653 // The default case is to treat the operation as if it were closed
4654 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004655 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4656 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4657 return IntRange::join(L, R);
4658 }
4659
4660 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4661 switch (UO->getOpcode()) {
4662 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004663 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004664 return IntRange::forBoolType();
4665
4666 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004667 case UO_Deref:
4668 case UO_AddrOf: // should be impossible
Eli Friedman09bddcf2013-07-08 20:20:06 +00004669 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004670
4671 default:
4672 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4673 }
4674 }
4675
Ted Kremenek728a1fb2013-10-14 18:55:27 +00004676 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
4677 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
4678
John McCall993f43f2013-05-06 21:39:12 +00004679 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004680 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004681 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004682
Eli Friedman09bddcf2013-07-08 20:20:06 +00004683 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004684}
John McCall51313c32010-01-04 23:31:57 +00004685
Ted Kremenek0692a192012-01-31 05:37:37 +00004686static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00004687 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCall323ed742010-05-06 08:58:33 +00004688}
4689
John McCall51313c32010-01-04 23:31:57 +00004690/// Checks whether the given value, which currently has the given
4691/// source semantics, has the same value when coerced through the
4692/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004693static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4694 const llvm::fltSemantics &Src,
4695 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004696 llvm::APFloat truncated = value;
4697
4698 bool ignored;
4699 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4700 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4701
4702 return truncated.bitwiseIsEqual(value);
4703}
4704
4705/// Checks whether the given value, which currently has the given
4706/// source semantics, has the same value when coerced through the
4707/// target semantics.
4708///
4709/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004710static bool IsSameFloatAfterCast(const APValue &value,
4711 const llvm::fltSemantics &Src,
4712 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004713 if (value.isFloat())
4714 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4715
4716 if (value.isVector()) {
4717 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4718 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4719 return false;
4720 return true;
4721 }
4722
4723 assert(value.isComplexFloat());
4724 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4725 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4726}
4727
Ted Kremenek0692a192012-01-31 05:37:37 +00004728static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004729
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004730static bool IsZero(Sema &S, Expr *E) {
4731 // Suppress cases where we are comparing against an enum constant.
4732 if (const DeclRefExpr *DR =
4733 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4734 if (isa<EnumConstantDecl>(DR->getDecl()))
4735 return false;
4736
4737 // Suppress cases where the '0' value is expanded from a macro.
4738 if (E->getLocStart().isMacroID())
4739 return false;
4740
John McCall323ed742010-05-06 08:58:33 +00004741 llvm::APSInt Value;
4742 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4743}
4744
John McCall372e1032010-10-06 00:25:24 +00004745static bool HasEnumType(Expr *E) {
4746 // Strip off implicit integral promotions.
4747 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004748 if (ICE->getCastKind() != CK_IntegralCast &&
4749 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004750 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004751 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004752 }
4753
4754 return E->getType()->isEnumeralType();
4755}
4756
Ted Kremenek0692a192012-01-31 05:37:37 +00004757static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004758 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004759 if (E->isValueDependent())
4760 return;
4761
John McCall2de56d12010-08-25 11:45:40 +00004762 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004763 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004764 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004765 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004766 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004767 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004768 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004769 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004770 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004771 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004772 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004773 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004774 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004775 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004776 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004777 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4778 }
4779}
4780
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004781static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004782 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004783 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004784 bool RhsConstant) {
Richard Trieu526e6272012-11-14 22:50:24 +00004785 // 0 values are handled later by CheckTrivialUnsignedComparison().
4786 if (Value == 0)
4787 return;
4788
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004789 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004790 QualType OtherT = Other->getType();
4791 QualType ConstantT = Constant->getType();
Richard Trieu526e6272012-11-14 22:50:24 +00004792 QualType CommonT = E->getLHS()->getType();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004793 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004794 return;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004795 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004796 && "comparison with non-integer type");
Richard Trieu526e6272012-11-14 22:50:24 +00004797
4798 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu526e6272012-11-14 22:50:24 +00004799 bool CommonSigned = CommonT->isSignedIntegerType();
4800
4801 bool EqualityOnly = false;
4802
4803 // TODO: Investigate using GetExprRange() to get tighter bounds on
4804 // on the bit ranges.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004805 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu526e6272012-11-14 22:50:24 +00004806 unsigned OtherWidth = OtherRange.Width;
4807
4808 if (CommonSigned) {
4809 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedmand87de7b2012-11-30 23:09:29 +00004810 if (!OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004811 // Check that the constant is representable in type OtherT.
4812 if (ConstantSigned) {
4813 if (OtherWidth >= Value.getMinSignedBits())
4814 return;
4815 } else { // !ConstantSigned
4816 if (OtherWidth >= Value.getActiveBits() + 1)
4817 return;
4818 }
4819 } else { // !OtherSigned
4820 // Check that the constant is representable in type OtherT.
4821 // Negative values are out of range.
4822 if (ConstantSigned) {
4823 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4824 return;
4825 } else { // !ConstantSigned
4826 if (OtherWidth >= Value.getActiveBits())
4827 return;
4828 }
4829 }
4830 } else { // !CommonSigned
Eli Friedmand87de7b2012-11-30 23:09:29 +00004831 if (OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004832 if (OtherWidth >= Value.getActiveBits())
4833 return;
Eli Friedmand87de7b2012-11-30 23:09:29 +00004834 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu526e6272012-11-14 22:50:24 +00004835 // Check to see if the constant is representable in OtherT.
4836 if (OtherWidth > Value.getActiveBits())
4837 return;
4838 // Check to see if the constant is equivalent to a negative value
4839 // cast to CommonT.
4840 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu5d1cf4f2012-11-15 03:43:50 +00004841 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu526e6272012-11-14 22:50:24 +00004842 return;
4843 // The constant value rests between values that OtherT can represent after
4844 // conversion. Relational comparison still works, but equality
4845 // comparisons will be tautological.
4846 EqualityOnly = true;
4847 } else { // OtherSigned && ConstantSigned
4848 assert(0 && "Two signed types converted to unsigned types.");
4849 }
4850 }
4851
4852 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4853
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004854 bool IsTrue = true;
Richard Trieu526e6272012-11-14 22:50:24 +00004855 if (op == BO_EQ || op == BO_NE) {
4856 IsTrue = op == BO_NE;
4857 } else if (EqualityOnly) {
4858 return;
4859 } else if (RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004860 if (op == BO_GT || op == BO_GE)
Richard Trieu526e6272012-11-14 22:50:24 +00004861 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004862 else // op == BO_LT || op == BO_LE
Richard Trieu526e6272012-11-14 22:50:24 +00004863 IsTrue = PositiveConstant;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004864 } else {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004865 if (op == BO_LT || op == BO_LE)
Richard Trieu526e6272012-11-14 22:50:24 +00004866 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004867 else // op == BO_GT || op == BO_GE
Richard Trieu526e6272012-11-14 22:50:24 +00004868 IsTrue = PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004869 }
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004870
4871 // If this is a comparison to an enum constant, include that
4872 // constant in the diagnostic.
4873 const EnumConstantDecl *ED = 0;
4874 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
4875 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
4876
4877 SmallString<64> PrettySourceValue;
4878 llvm::raw_svector_ostream OS(PrettySourceValue);
4879 if (ED)
Ted Kremenek9de50942013-03-15 22:02:46 +00004880 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004881 else
4882 OS << Value;
4883
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004884 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004885 << OS.str() << OtherT << IsTrue
Richard Trieu526e6272012-11-14 22:50:24 +00004886 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004887}
4888
John McCall323ed742010-05-06 08:58:33 +00004889/// Analyze the operands of the given comparison. Implements the
4890/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004891static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004892 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4893 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004894}
John McCall51313c32010-01-04 23:31:57 +00004895
John McCallba26e582010-01-04 23:21:16 +00004896/// \brief Implements -Wsign-compare.
4897///
Richard Trieudd225092011-09-15 21:56:47 +00004898/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004899static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004900 // The type the comparison is being performed in.
4901 QualType T = E->getLHS()->getType();
4902 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4903 && "comparison with mismatched types");
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00004904 if (E->isValueDependent())
4905 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004906
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004907 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4908 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004909
4910 bool IsComparisonConstant = false;
4911
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004912 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004913 // of 'true' or 'false'.
4914 if (T->isIntegralType(S.Context)) {
4915 llvm::APSInt RHSValue;
4916 bool IsRHSIntegralLiteral =
4917 RHS->isIntegerConstantExpr(RHSValue, S.Context);
4918 llvm::APSInt LHSValue;
4919 bool IsLHSIntegralLiteral =
4920 LHS->isIntegerConstantExpr(LHSValue, S.Context);
4921 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4922 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4923 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4924 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4925 else
4926 IsComparisonConstant =
4927 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004928 } else if (!T->hasUnsignedIntegerRepresentation())
4929 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004930
John McCall323ed742010-05-06 08:58:33 +00004931 // We don't do anything special if this isn't an unsigned integral
4932 // comparison: we're only interested in integral comparisons, and
4933 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004934 //
4935 // We also don't care about value-dependent expressions or expressions
4936 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004937 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00004938 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004939
John McCall323ed742010-05-06 08:58:33 +00004940 // Check to see if one of the (unmodified) operands is of different
4941 // signedness.
4942 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004943 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4944 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004945 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004946 signedOperand = LHS;
4947 unsignedOperand = RHS;
4948 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4949 signedOperand = RHS;
4950 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004951 } else {
John McCall323ed742010-05-06 08:58:33 +00004952 CheckTrivialUnsignedComparison(S, E);
4953 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004954 }
4955
John McCall323ed742010-05-06 08:58:33 +00004956 // Otherwise, calculate the effective range of the signed operand.
4957 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004958
John McCall323ed742010-05-06 08:58:33 +00004959 // Go ahead and analyze implicit conversions in the operands. Note
4960 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004961 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4962 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004963
John McCall323ed742010-05-06 08:58:33 +00004964 // If the signed range is non-negative, -Wsign-compare won't fire,
4965 // but we should still check for comparisons which are always true
4966 // or false.
4967 if (signedRange.NonNegative)
4968 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004969
4970 // For (in)equality comparisons, if the unsigned operand is a
4971 // constant which cannot collide with a overflowed signed operand,
4972 // then reinterpreting the signed operand as unsigned will not
4973 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00004974 if (E->isEqualityOp()) {
4975 unsigned comparisonWidth = S.Context.getIntWidth(T);
4976 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00004977
John McCall323ed742010-05-06 08:58:33 +00004978 // We should never be unable to prove that the unsigned operand is
4979 // non-negative.
4980 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
4981
4982 if (unsignedRange.Width < comparisonWidth)
4983 return;
4984 }
4985
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00004986 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4987 S.PDiag(diag::warn_mixed_sign_comparison)
4988 << LHS->getType() << RHS->getType()
4989 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00004990}
4991
John McCall15d7d122010-11-11 03:21:53 +00004992/// Analyzes an attempt to assign the given value to a bitfield.
4993///
4994/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00004995static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4996 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00004997 assert(Bitfield->isBitField());
4998 if (Bitfield->isInvalidDecl())
4999 return false;
5000
John McCall91b60142010-11-11 05:33:51 +00005001 // White-list bool bitfields.
5002 if (Bitfield->getType()->isBooleanType())
5003 return false;
5004
Douglas Gregor46ff3032011-02-04 13:09:01 +00005005 // Ignore value- or type-dependent expressions.
5006 if (Bitfield->getBitWidth()->isValueDependent() ||
5007 Bitfield->getBitWidth()->isTypeDependent() ||
5008 Init->isValueDependent() ||
5009 Init->isTypeDependent())
5010 return false;
5011
John McCall15d7d122010-11-11 03:21:53 +00005012 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5013
Richard Smith80d4b552011-12-28 19:48:30 +00005014 llvm::APSInt Value;
5015 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00005016 return false;
5017
John McCall15d7d122010-11-11 03:21:53 +00005018 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005019 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00005020
5021 if (OriginalWidth <= FieldWidth)
5022 return false;
5023
Eli Friedman3a643af2012-01-26 23:11:39 +00005024 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00005025 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00005026 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00005027
Eli Friedman3a643af2012-01-26 23:11:39 +00005028 // Check whether the stored value is equal to the original value.
5029 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00005030 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00005031 return false;
5032
Eli Friedman3a643af2012-01-26 23:11:39 +00005033 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00005034 // therefore don't strictly fit into a signed bitfield of width 1.
5035 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00005036 return false;
5037
John McCall15d7d122010-11-11 03:21:53 +00005038 std::string PrettyValue = Value.toString(10);
5039 std::string PrettyTrunc = TruncatedValue.toString(10);
5040
5041 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5042 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5043 << Init->getSourceRange();
5044
5045 return true;
5046}
5047
John McCallbeb22aa2010-11-09 23:24:47 +00005048/// Analyze the given simple or compound assignment for warning-worthy
5049/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00005050static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00005051 // Just recurse on the LHS.
5052 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5053
5054 // We want to recurse on the RHS as normal unless we're assigning to
5055 // a bitfield.
John McCall993f43f2013-05-06 21:39:12 +00005056 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005057 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall15d7d122010-11-11 03:21:53 +00005058 E->getOperatorLoc())) {
5059 // Recurse, ignoring any implicit conversions on the RHS.
5060 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5061 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00005062 }
5063 }
5064
5065 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5066}
5067
John McCall51313c32010-01-04 23:31:57 +00005068/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00005069static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00005070 SourceLocation CContext, unsigned diag,
5071 bool pruneControlFlow = false) {
5072 if (pruneControlFlow) {
5073 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5074 S.PDiag(diag)
5075 << SourceType << T << E->getSourceRange()
5076 << SourceRange(CContext));
5077 return;
5078 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005079 S.Diag(E->getExprLoc(), diag)
5080 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5081}
5082
Chandler Carruthe1b02e02011-04-05 06:47:57 +00005083/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00005084static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00005085 SourceLocation CContext, unsigned diag,
5086 bool pruneControlFlow = false) {
5087 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00005088}
5089
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005090/// Diagnose an implicit cast from a literal expression. Does not warn when the
5091/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00005092void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5093 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005094 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00005095 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005096 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00005097 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5098 T->hasUnsignedIntegerRepresentation());
5099 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00005100 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005101 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00005102 return;
5103
Eli Friedman4e1a82c2013-08-29 23:44:43 +00005104 // FIXME: Force the precision of the source value down so we don't print
5105 // digits which are usually useless (we don't really care here if we
5106 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5107 // would automatically print the shortest representation, but it's a bit
5108 // tricky to implement.
David Blaikiebe0ee872012-05-15 16:56:36 +00005109 SmallString<16> PrettySourceValue;
Eli Friedman4e1a82c2013-08-29 23:44:43 +00005110 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5111 precision = (precision * 59 + 195) / 196;
5112 Value.toString(PrettySourceValue, precision);
5113
David Blaikiede7e7b82012-05-15 17:18:27 +00005114 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00005115 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5116 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5117 else
David Blaikiede7e7b82012-05-15 17:18:27 +00005118 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00005119
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005120 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00005121 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5122 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00005123}
5124
John McCall091f23f2010-11-09 22:22:12 +00005125std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5126 if (!Range.Width) return "0";
5127
5128 llvm::APSInt ValueInRange = Value;
5129 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00005130 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00005131 return ValueInRange.toString(10);
5132}
5133
Hans Wennborg88617a22012-08-28 15:44:30 +00005134static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5135 if (!isa<ImplicitCastExpr>(Ex))
5136 return false;
5137
5138 Expr *InnerE = Ex->IgnoreParenImpCasts();
5139 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5140 const Type *Source =
5141 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5142 if (Target->isDependentType())
5143 return false;
5144
5145 const BuiltinType *FloatCandidateBT =
5146 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5147 const Type *BoolCandidateType = ToBool ? Target : Source;
5148
5149 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5150 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5151}
5152
5153void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5154 SourceLocation CC) {
5155 unsigned NumArgs = TheCall->getNumArgs();
5156 for (unsigned i = 0; i < NumArgs; ++i) {
5157 Expr *CurrA = TheCall->getArg(i);
5158 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5159 continue;
5160
5161 bool IsSwapped = ((i > 0) &&
5162 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5163 IsSwapped |= ((i < (NumArgs - 1)) &&
5164 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5165 if (IsSwapped) {
5166 // Warn on this floating-point to bool conversion.
5167 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5168 CurrA->getType(), CC,
5169 diag::warn_impcast_floating_point_to_bool);
5170 }
5171 }
5172}
5173
John McCall323ed742010-05-06 08:58:33 +00005174void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005175 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00005176 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00005177
John McCall323ed742010-05-06 08:58:33 +00005178 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5179 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5180 if (Source == Target) return;
5181 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00005182
Chandler Carruth108f7562011-07-26 05:40:03 +00005183 // If the conversion context location is invalid don't complain. We also
5184 // don't want to emit a warning if the issue occurs from the expansion of
5185 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5186 // delay this check as long as possible. Once we detect we are in that
5187 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00005188 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00005189 return;
5190
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005191 // Diagnose implicit casts to bool.
5192 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5193 if (isa<StringLiteral>(E))
5194 // Warn on string literal to bool. Checks for string literals in logical
5195 // expressions, for instances, assert(0 && "error here"), is prevented
5196 // by a check in AnalyzeImplicitConversions().
5197 return DiagnoseImpCast(S, E, T, CC,
5198 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00005199 if (Source->isFunctionType()) {
5200 // Warn on function to bool. Checks free functions and static member
5201 // functions. Weakly imported functions are excluded from the check,
5202 // since it's common to test their value to check whether the linker
5203 // found a definition for them.
5204 ValueDecl *D = 0;
5205 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
5206 D = R->getDecl();
5207 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
5208 D = M->getMemberDecl();
5209 }
5210
5211 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00005212 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
5213 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
5214 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00005215 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
5216 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
5217 QualType ReturnType;
5218 UnresolvedSet<4> NonTemplateOverloads;
David Blaikiec8fa5252013-06-21 23:54:45 +00005219 S.tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
David Blaikie2def7732011-12-09 21:42:37 +00005220 if (!ReturnType.isNull()
5221 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
5222 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
5223 << FixItHint::CreateInsertion(
5224 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00005225 return;
5226 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00005227 }
5228 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005229 }
John McCall51313c32010-01-04 23:31:57 +00005230
5231 // Strip vector types.
5232 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005233 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005234 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005235 return;
John McCallb4eb64d2010-10-08 02:01:28 +00005236 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005237 }
Chris Lattnerb792b302011-06-14 04:51:15 +00005238
5239 // If the vector cast is cast between two vectors of the same size, it is
5240 // a bitcast, not a conversion.
5241 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5242 return;
John McCall51313c32010-01-04 23:31:57 +00005243
5244 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5245 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5246 }
5247
5248 // Strip complex types.
5249 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005250 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005251 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005252 return;
5253
John McCallb4eb64d2010-10-08 02:01:28 +00005254 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005255 }
John McCall51313c32010-01-04 23:31:57 +00005256
5257 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5258 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5259 }
5260
5261 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5262 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5263
5264 // If the source is floating point...
5265 if (SourceBT && SourceBT->isFloatingPoint()) {
5266 // ...and the target is floating point...
5267 if (TargetBT && TargetBT->isFloatingPoint()) {
5268 // ...then warn if we're dropping FP rank.
5269
5270 // Builtin FP kinds are ordered by increasing FP rank.
5271 if (SourceBT->getKind() > TargetBT->getKind()) {
5272 // Don't warn about float constants that are precisely
5273 // representable in the target type.
5274 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00005275 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00005276 // Value might be a float, a float vector, or a float complex.
5277 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00005278 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5279 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00005280 return;
5281 }
5282
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005283 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005284 return;
5285
John McCallb4eb64d2010-10-08 02:01:28 +00005286 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00005287 }
5288 return;
5289 }
5290
Ted Kremenekef9ff882011-03-10 20:03:42 +00005291 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00005292 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005293 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005294 return;
5295
Chandler Carrutha5b93322011-02-17 11:05:49 +00005296 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00005297 // We also want to warn on, e.g., "int i = -1.234"
5298 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5299 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5300 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5301
Chandler Carruthf65076e2011-04-10 08:36:24 +00005302 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5303 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00005304 } else {
5305 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5306 }
5307 }
John McCall51313c32010-01-04 23:31:57 +00005308
Hans Wennborg88617a22012-08-28 15:44:30 +00005309 // If the target is bool, warn if expr is a function or method call.
5310 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5311 isa<CallExpr>(E)) {
5312 // Check last argument of function call to see if it is an
5313 // implicit cast from a type matching the type the result
5314 // is being cast to.
5315 CallExpr *CEx = cast<CallExpr>(E);
5316 unsigned NumArgs = CEx->getNumArgs();
5317 if (NumArgs > 0) {
5318 Expr *LastA = CEx->getArg(NumArgs - 1);
5319 Expr *InnerE = LastA->IgnoreParenImpCasts();
5320 const Type *InnerType =
5321 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5322 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5323 // Warn on this floating-point to bool conversion
5324 DiagnoseImpCast(S, E, T, CC,
5325 diag::warn_impcast_floating_point_to_bool);
5326 }
5327 }
5328 }
John McCall51313c32010-01-04 23:31:57 +00005329 return;
5330 }
5331
Richard Trieu1838ca52011-05-29 19:59:02 +00005332 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00005333 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiee81b43b2012-11-08 00:41:20 +00005334 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikie896c7dd2013-02-16 00:56:22 +00005335 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieb1360492012-03-16 20:30:12 +00005336 SourceLocation Loc = E->getSourceRange().getBegin();
5337 if (Loc.isMacroID())
5338 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00005339 if (!Loc.isMacroID() || CC.isMacroID())
5340 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5341 << T << clang::SourceRange(CC)
Richard Smith8adf8372013-09-20 00:27:40 +00005342 << FixItHint::CreateReplacement(Loc,
5343 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieu1838ca52011-05-29 19:59:02 +00005344 }
5345
David Blaikieb26331b2012-06-19 21:19:06 +00005346 if (!Source->isIntegerType() || !Target->isIntegerType())
5347 return;
5348
David Blaikiebe0ee872012-05-15 16:56:36 +00005349 // TODO: remove this early return once the false positives for constant->bool
5350 // in templates, macros, etc, are reduced or removed.
5351 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5352 return;
5353
John McCall323ed742010-05-06 08:58:33 +00005354 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00005355 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00005356
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005357 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer25ffbef2013-03-28 19:07:11 +00005358 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005359 // TODO: this should happen for bitfield stores, too.
5360 llvm::APSInt Value(32);
5361 if (E->isIntegerConstantExpr(Value, S.Context)) {
5362 if (S.SourceMgr.isInSystemMacro(CC))
5363 return;
5364
John McCall091f23f2010-11-09 22:22:12 +00005365 std::string PrettySourceValue = Value.toString(10);
5366 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005367
Ted Kremenek5e745da2011-10-22 02:37:33 +00005368 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5369 S.PDiag(diag::warn_impcast_integer_precision_constant)
5370 << PrettySourceValue << PrettyTargetValue
5371 << E->getType() << T << E->getSourceRange()
5372 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00005373 return;
5374 }
5375
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005376 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5377 if (S.SourceMgr.isInSystemMacro(CC))
5378 return;
5379
David Blaikie37050842012-04-12 22:40:54 +00005380 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00005381 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5382 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00005383 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00005384 }
5385
5386 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5387 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5388 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005389
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005390 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005391 return;
5392
John McCall323ed742010-05-06 08:58:33 +00005393 unsigned DiagID = diag::warn_impcast_integer_sign;
5394
5395 // Traditionally, gcc has warned about this under -Wsign-compare.
5396 // We also want to warn about it in -Wconversion.
5397 // So if -Wconversion is off, use a completely identical diagnostic
5398 // in the sign-compare group.
5399 // The conditional-checking code will
5400 if (ICContext) {
5401 DiagID = diag::warn_impcast_integer_sign_conditional;
5402 *ICContext = true;
5403 }
5404
John McCallb4eb64d2010-10-08 02:01:28 +00005405 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00005406 }
5407
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005408 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005409 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5410 // type, to give us better diagnostics.
5411 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00005412 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005413 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5414 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5415 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5416 SourceType = S.Context.getTypeDeclType(Enum);
5417 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5418 }
5419 }
5420
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005421 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5422 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall83972f12013-03-09 00:54:27 +00005423 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5424 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00005425 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005426 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005427 return;
5428
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005429 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005430 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005431 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005432
John McCall51313c32010-01-04 23:31:57 +00005433 return;
5434}
5435
David Blaikie9fb1ac52012-05-15 21:57:38 +00005436void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5437 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00005438
5439void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00005440 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00005441 E = E->IgnoreParenImpCasts();
5442
5443 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00005444 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00005445
John McCallb4eb64d2010-10-08 02:01:28 +00005446 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005447 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005448 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00005449 return;
5450}
5451
David Blaikie9fb1ac52012-05-15 21:57:38 +00005452void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5453 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00005454 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00005455
5456 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00005457 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5458 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005459
5460 // If -Wconversion would have warned about either of the candidates
5461 // for a signedness conversion to the context type...
5462 if (!Suspicious) return;
5463
5464 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005465 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5466 CC))
John McCall323ed742010-05-06 08:58:33 +00005467 return;
5468
John McCall323ed742010-05-06 08:58:33 +00005469 // ...then check whether it would have warned about either of the
5470 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00005471 if (E->getType() == T) return;
5472
5473 Suspicious = false;
5474 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5475 E->getType(), CC, &Suspicious);
5476 if (!Suspicious)
5477 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00005478 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005479}
5480
5481/// AnalyzeImplicitConversions - Find and report any interesting
5482/// implicit conversions in the given expression. There are a couple
5483/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005484void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005485 QualType T = OrigE->getType();
5486 Expr *E = OrigE->IgnoreParenImpCasts();
5487
Douglas Gregorf8b6e152011-10-10 17:38:18 +00005488 if (E->isTypeDependent() || E->isValueDependent())
5489 return;
5490
John McCall323ed742010-05-06 08:58:33 +00005491 // For conditional operators, we analyze the arguments as if they
5492 // were being fed directly into the output.
5493 if (isa<ConditionalOperator>(E)) {
5494 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00005495 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00005496 return;
5497 }
5498
Hans Wennborg88617a22012-08-28 15:44:30 +00005499 // Check implicit argument conversions for function calls.
5500 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5501 CheckImplicitArgumentConversions(S, Call, CC);
5502
John McCall323ed742010-05-06 08:58:33 +00005503 // Go ahead and check any implicit conversions we might have skipped.
5504 // The non-canonical typecheck is just an optimization;
5505 // CheckImplicitConversion will filter out dead implicit conversions.
5506 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005507 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00005508
5509 // Now continue drilling into this expression.
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005510
5511 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005512 if (POE->getResultExpr())
5513 E = POE->getResultExpr();
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005514 }
5515
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005516 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5517 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5518
John McCall323ed742010-05-06 08:58:33 +00005519 // Skip past explicit casts.
5520 if (isa<ExplicitCastExpr>(E)) {
5521 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00005522 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005523 }
5524
John McCallbeb22aa2010-11-09 23:24:47 +00005525 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5526 // Do a somewhat different check with comparison operators.
5527 if (BO->isComparisonOp())
5528 return AnalyzeComparison(S, BO);
5529
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005530 // And with simple assignments.
5531 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00005532 return AnalyzeAssignment(S, BO);
5533 }
John McCall323ed742010-05-06 08:58:33 +00005534
5535 // These break the otherwise-useful invariant below. Fortunately,
5536 // we don't really need to recurse into them, because any internal
5537 // expressions should have been analyzed already when they were
5538 // built into statements.
5539 if (isa<StmtExpr>(E)) return;
5540
5541 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005542 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00005543
5544 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00005545 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005546 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5547 bool IsLogicalOperator = BO && BO->isLogicalOp();
5548 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00005549 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00005550 if (!ChildExpr)
5551 continue;
5552
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005553 if (IsLogicalOperator &&
5554 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5555 // Ignore checking string literals that are in logical operators.
5556 continue;
5557 AnalyzeImplicitConversions(S, ChildExpr, CC);
5558 }
John McCall323ed742010-05-06 08:58:33 +00005559}
5560
5561} // end anonymous namespace
5562
5563/// Diagnoses "dangerous" implicit conversions within the given
5564/// expression (which is a full expression). Implements -Wconversion
5565/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005566///
5567/// \param CC the "context" location of the implicit conversion, i.e.
5568/// the most location of the syntactic entity requiring the implicit
5569/// conversion
5570void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005571 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00005572 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00005573 return;
5574
5575 // Don't diagnose for value- or type-dependent expressions.
5576 if (E->isTypeDependent() || E->isValueDependent())
5577 return;
5578
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005579 // Check for array bounds violations in cases where the check isn't triggered
5580 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5581 // ArraySubscriptExpr is on the RHS of a variable initialization.
5582 CheckArrayAccess(E);
5583
John McCallb4eb64d2010-10-08 02:01:28 +00005584 // This is not the right CC for (e.g.) a variable initialization.
5585 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005586}
5587
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005588/// Diagnose when expression is an integer constant expression and its evaluation
5589/// results in integer overflow
5590void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanian1fd8d462013-03-15 20:47:07 +00005591 if (isa<BinaryOperator>(E->IgnoreParens())) {
Robert Wilhelme7205c02013-08-10 12:33:24 +00005592 SmallVector<PartialDiagnosticAt, 4> Diags;
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005593 E->EvaluateForOverflow(Context, &Diags);
5594 }
5595}
5596
Richard Smith6c3af3d2013-01-17 01:17:56 +00005597namespace {
5598/// \brief Visitor for expressions which looks for unsequenced operations on the
5599/// same object.
5600class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smith0c0b3902013-06-30 10:40:20 +00005601 typedef EvaluatedExprVisitor<SequenceChecker> Base;
5602
Richard Smith6c3af3d2013-01-17 01:17:56 +00005603 /// \brief A tree of sequenced regions within an expression. Two regions are
5604 /// unsequenced if one is an ancestor or a descendent of the other. When we
5605 /// finish processing an expression with sequencing, such as a comma
5606 /// expression, we fold its tree nodes into its parent, since they are
5607 /// unsequenced with respect to nodes we will visit later.
5608 class SequenceTree {
5609 struct Value {
5610 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5611 unsigned Parent : 31;
5612 bool Merged : 1;
5613 };
Robert Wilhelme7205c02013-08-10 12:33:24 +00005614 SmallVector<Value, 8> Values;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005615
5616 public:
5617 /// \brief A region within an expression which may be sequenced with respect
5618 /// to some other region.
5619 class Seq {
5620 explicit Seq(unsigned N) : Index(N) {}
5621 unsigned Index;
5622 friend class SequenceTree;
5623 public:
5624 Seq() : Index(0) {}
5625 };
5626
5627 SequenceTree() { Values.push_back(Value(0)); }
5628 Seq root() const { return Seq(0); }
5629
5630 /// \brief Create a new sequence of operations, which is an unsequenced
5631 /// subset of \p Parent. This sequence of operations is sequenced with
5632 /// respect to other children of \p Parent.
5633 Seq allocate(Seq Parent) {
5634 Values.push_back(Value(Parent.Index));
5635 return Seq(Values.size() - 1);
5636 }
5637
5638 /// \brief Merge a sequence of operations into its parent.
5639 void merge(Seq S) {
5640 Values[S.Index].Merged = true;
5641 }
5642
5643 /// \brief Determine whether two operations are unsequenced. This operation
5644 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5645 /// should have been merged into its parent as appropriate.
5646 bool isUnsequenced(Seq Cur, Seq Old) {
5647 unsigned C = representative(Cur.Index);
5648 unsigned Target = representative(Old.Index);
5649 while (C >= Target) {
5650 if (C == Target)
5651 return true;
5652 C = Values[C].Parent;
5653 }
5654 return false;
5655 }
5656
5657 private:
5658 /// \brief Pick a representative for a sequence.
5659 unsigned representative(unsigned K) {
5660 if (Values[K].Merged)
5661 // Perform path compression as we go.
5662 return Values[K].Parent = representative(Values[K].Parent);
5663 return K;
5664 }
5665 };
5666
5667 /// An object for which we can track unsequenced uses.
5668 typedef NamedDecl *Object;
5669
5670 /// Different flavors of object usage which we track. We only track the
5671 /// least-sequenced usage of each kind.
5672 enum UsageKind {
5673 /// A read of an object. Multiple unsequenced reads are OK.
5674 UK_Use,
5675 /// A modification of an object which is sequenced before the value
Richard Smith418dd3e2013-06-26 23:16:51 +00005676 /// computation of the expression, such as ++n in C++.
Richard Smith6c3af3d2013-01-17 01:17:56 +00005677 UK_ModAsValue,
5678 /// A modification of an object which is not sequenced before the value
5679 /// computation of the expression, such as n++.
5680 UK_ModAsSideEffect,
5681
5682 UK_Count = UK_ModAsSideEffect + 1
5683 };
5684
5685 struct Usage {
5686 Usage() : Use(0), Seq() {}
5687 Expr *Use;
5688 SequenceTree::Seq Seq;
5689 };
5690
5691 struct UsageInfo {
5692 UsageInfo() : Diagnosed(false) {}
5693 Usage Uses[UK_Count];
5694 /// Have we issued a diagnostic for this variable already?
5695 bool Diagnosed;
5696 };
5697 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5698
5699 Sema &SemaRef;
5700 /// Sequenced regions within the expression.
5701 SequenceTree Tree;
5702 /// Declaration modifications and references which we have seen.
5703 UsageInfoMap UsageMap;
5704 /// The region we are currently within.
5705 SequenceTree::Seq Region;
5706 /// Filled in with declarations which were modified as a side-effect
5707 /// (that is, post-increment operations).
Robert Wilhelme7205c02013-08-10 12:33:24 +00005708 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smith1a2dcd52013-01-17 23:18:09 +00005709 /// Expressions to check later. We defer checking these to reduce
5710 /// stack usage.
Robert Wilhelme7205c02013-08-10 12:33:24 +00005711 SmallVectorImpl<Expr *> &WorkList;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005712
5713 /// RAII object wrapping the visitation of a sequenced subexpression of an
5714 /// expression. At the end of this process, the side-effects of the evaluation
5715 /// become sequenced with respect to the value computation of the result, so
5716 /// we downgrade any UK_ModAsSideEffect within the evaluation to
5717 /// UK_ModAsValue.
5718 struct SequencedSubexpression {
5719 SequencedSubexpression(SequenceChecker &Self)
5720 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5721 Self.ModAsSideEffect = &ModAsSideEffect;
5722 }
5723 ~SequencedSubexpression() {
5724 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5725 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5726 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5727 Self.addUsage(U, ModAsSideEffect[I].first,
5728 ModAsSideEffect[I].second.Use, UK_ModAsValue);
5729 }
5730 Self.ModAsSideEffect = OldModAsSideEffect;
5731 }
5732
5733 SequenceChecker &Self;
Robert Wilhelme7205c02013-08-10 12:33:24 +00005734 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5735 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005736 };
5737
Richard Smith67470052013-06-20 22:21:56 +00005738 /// RAII object wrapping the visitation of a subexpression which we might
5739 /// choose to evaluate as a constant. If any subexpression is evaluated and
5740 /// found to be non-constant, this allows us to suppress the evaluation of
5741 /// the outer expression.
5742 class EvaluationTracker {
5743 public:
5744 EvaluationTracker(SequenceChecker &Self)
5745 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
5746 Self.EvalTracker = this;
5747 }
5748 ~EvaluationTracker() {
5749 Self.EvalTracker = Prev;
5750 if (Prev)
5751 Prev->EvalOK &= EvalOK;
5752 }
5753
5754 bool evaluate(const Expr *E, bool &Result) {
5755 if (!EvalOK || E->isValueDependent())
5756 return false;
5757 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
5758 return EvalOK;
5759 }
5760
5761 private:
5762 SequenceChecker &Self;
5763 EvaluationTracker *Prev;
5764 bool EvalOK;
5765 } *EvalTracker;
5766
Richard Smith6c3af3d2013-01-17 01:17:56 +00005767 /// \brief Find the object which is produced by the specified expression,
5768 /// if any.
5769 Object getObject(Expr *E, bool Mod) const {
5770 E = E->IgnoreParenCasts();
5771 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5772 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5773 return getObject(UO->getSubExpr(), Mod);
5774 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5775 if (BO->getOpcode() == BO_Comma)
5776 return getObject(BO->getRHS(), Mod);
5777 if (Mod && BO->isAssignmentOp())
5778 return getObject(BO->getLHS(), Mod);
5779 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5780 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5781 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5782 return ME->getMemberDecl();
5783 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5784 // FIXME: If this is a reference, map through to its value.
5785 return DRE->getDecl();
5786 return 0;
5787 }
5788
5789 /// \brief Note that an object was modified or used by an expression.
5790 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5791 Usage &U = UI.Uses[UK];
5792 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5793 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5794 ModAsSideEffect->push_back(std::make_pair(O, U));
5795 U.Use = Ref;
5796 U.Seq = Region;
5797 }
5798 }
5799 /// \brief Check whether a modification or use conflicts with a prior usage.
5800 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5801 bool IsModMod) {
5802 if (UI.Diagnosed)
5803 return;
5804
5805 const Usage &U = UI.Uses[OtherKind];
5806 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5807 return;
5808
5809 Expr *Mod = U.Use;
5810 Expr *ModOrUse = Ref;
5811 if (OtherKind == UK_Use)
5812 std::swap(Mod, ModOrUse);
5813
5814 SemaRef.Diag(Mod->getExprLoc(),
5815 IsModMod ? diag::warn_unsequenced_mod_mod
5816 : diag::warn_unsequenced_mod_use)
5817 << O << SourceRange(ModOrUse->getExprLoc());
5818 UI.Diagnosed = true;
5819 }
5820
5821 void notePreUse(Object O, Expr *Use) {
5822 UsageInfo &U = UsageMap[O];
5823 // Uses conflict with other modifications.
5824 checkUsage(O, U, Use, UK_ModAsValue, false);
5825 }
5826 void notePostUse(Object O, Expr *Use) {
5827 UsageInfo &U = UsageMap[O];
5828 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5829 addUsage(U, O, Use, UK_Use);
5830 }
5831
5832 void notePreMod(Object O, Expr *Mod) {
5833 UsageInfo &U = UsageMap[O];
5834 // Modifications conflict with other modifications and with uses.
5835 checkUsage(O, U, Mod, UK_ModAsValue, true);
5836 checkUsage(O, U, Mod, UK_Use, false);
5837 }
5838 void notePostMod(Object O, Expr *Use, UsageKind UK) {
5839 UsageInfo &U = UsageMap[O];
5840 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5841 addUsage(U, O, Use, UK);
5842 }
5843
5844public:
Robert Wilhelme7205c02013-08-10 12:33:24 +00005845 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
5846 : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
5847 WorkList(WorkList), EvalTracker(0) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005848 Visit(E);
5849 }
5850
5851 void VisitStmt(Stmt *S) {
5852 // Skip all statements which aren't expressions for now.
5853 }
5854
5855 void VisitExpr(Expr *E) {
5856 // By default, just recurse to evaluated subexpressions.
Richard Smith0c0b3902013-06-30 10:40:20 +00005857 Base::VisitStmt(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005858 }
5859
5860 void VisitCastExpr(CastExpr *E) {
5861 Object O = Object();
5862 if (E->getCastKind() == CK_LValueToRValue)
5863 O = getObject(E->getSubExpr(), false);
5864
5865 if (O)
5866 notePreUse(O, E);
5867 VisitExpr(E);
5868 if (O)
5869 notePostUse(O, E);
5870 }
5871
5872 void VisitBinComma(BinaryOperator *BO) {
5873 // C++11 [expr.comma]p1:
5874 // Every value computation and side effect associated with the left
5875 // expression is sequenced before every value computation and side
5876 // effect associated with the right expression.
5877 SequenceTree::Seq LHS = Tree.allocate(Region);
5878 SequenceTree::Seq RHS = Tree.allocate(Region);
5879 SequenceTree::Seq OldRegion = Region;
5880
5881 {
5882 SequencedSubexpression SeqLHS(*this);
5883 Region = LHS;
5884 Visit(BO->getLHS());
5885 }
5886
5887 Region = RHS;
5888 Visit(BO->getRHS());
5889
5890 Region = OldRegion;
5891
5892 // Forget that LHS and RHS are sequenced. They are both unsequenced
5893 // with respect to other stuff.
5894 Tree.merge(LHS);
5895 Tree.merge(RHS);
5896 }
5897
5898 void VisitBinAssign(BinaryOperator *BO) {
5899 // The modification is sequenced after the value computation of the LHS
5900 // and RHS, so check it before inspecting the operands and update the
5901 // map afterwards.
5902 Object O = getObject(BO->getLHS(), true);
5903 if (!O)
5904 return VisitExpr(BO);
5905
5906 notePreMod(O, BO);
5907
5908 // C++11 [expr.ass]p7:
5909 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
5910 // only once.
5911 //
5912 // Therefore, for a compound assignment operator, O is considered used
5913 // everywhere except within the evaluation of E1 itself.
5914 if (isa<CompoundAssignOperator>(BO))
5915 notePreUse(O, BO);
5916
5917 Visit(BO->getLHS());
5918
5919 if (isa<CompoundAssignOperator>(BO))
5920 notePostUse(O, BO);
5921
5922 Visit(BO->getRHS());
5923
Richard Smith418dd3e2013-06-26 23:16:51 +00005924 // C++11 [expr.ass]p1:
5925 // the assignment is sequenced [...] before the value computation of the
5926 // assignment expression.
5927 // C11 6.5.16/3 has no such rule.
5928 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5929 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005930 }
5931 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
5932 VisitBinAssign(CAO);
5933 }
5934
5935 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5936 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5937 void VisitUnaryPreIncDec(UnaryOperator *UO) {
5938 Object O = getObject(UO->getSubExpr(), true);
5939 if (!O)
5940 return VisitExpr(UO);
5941
5942 notePreMod(O, UO);
5943 Visit(UO->getSubExpr());
Richard Smith418dd3e2013-06-26 23:16:51 +00005944 // C++11 [expr.pre.incr]p1:
5945 // the expression ++x is equivalent to x+=1
5946 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5947 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005948 }
5949
5950 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5951 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5952 void VisitUnaryPostIncDec(UnaryOperator *UO) {
5953 Object O = getObject(UO->getSubExpr(), true);
5954 if (!O)
5955 return VisitExpr(UO);
5956
5957 notePreMod(O, UO);
5958 Visit(UO->getSubExpr());
5959 notePostMod(O, UO, UK_ModAsSideEffect);
5960 }
5961
5962 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
5963 void VisitBinLOr(BinaryOperator *BO) {
5964 // The side-effects of the LHS of an '&&' are sequenced before the
5965 // value computation of the RHS, and hence before the value computation
5966 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
5967 // as if they were unconditionally sequenced.
Richard Smith67470052013-06-20 22:21:56 +00005968 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005969 {
5970 SequencedSubexpression Sequenced(*this);
5971 Visit(BO->getLHS());
5972 }
5973
5974 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00005975 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00005976 if (!Result)
5977 Visit(BO->getRHS());
5978 } else {
5979 // Check for unsequenced operations in the RHS, treating it as an
5980 // entirely separate evaluation.
5981 //
5982 // FIXME: If there are operations in the RHS which are unsequenced
5983 // with respect to operations outside the RHS, and those operations
5984 // are unconditionally evaluated, diagnose them.
Richard Smith1a2dcd52013-01-17 23:18:09 +00005985 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00005986 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005987 }
5988 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith67470052013-06-20 22:21:56 +00005989 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005990 {
5991 SequencedSubexpression Sequenced(*this);
5992 Visit(BO->getLHS());
5993 }
5994
5995 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00005996 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00005997 if (Result)
5998 Visit(BO->getRHS());
5999 } else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00006000 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00006001 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006002 }
6003
6004 // Only visit the condition, unless we can be sure which subexpression will
6005 // be chosen.
6006 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith67470052013-06-20 22:21:56 +00006007 EvaluationTracker Eval(*this);
Richard Smith418dd3e2013-06-26 23:16:51 +00006008 {
6009 SequencedSubexpression Sequenced(*this);
6010 Visit(CO->getCond());
6011 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006012
6013 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00006014 if (Eval.evaluate(CO->getCond(), Result))
Richard Smith6c3af3d2013-01-17 01:17:56 +00006015 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00006016 else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00006017 WorkList.push_back(CO->getTrueExpr());
6018 WorkList.push_back(CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00006019 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006020 }
6021
Richard Smith0c0b3902013-06-30 10:40:20 +00006022 void VisitCallExpr(CallExpr *CE) {
6023 // C++11 [intro.execution]p15:
6024 // When calling a function [...], every value computation and side effect
6025 // associated with any argument expression, or with the postfix expression
6026 // designating the called function, is sequenced before execution of every
6027 // expression or statement in the body of the function [and thus before
6028 // the value computation of its result].
6029 SequencedSubexpression Sequenced(*this);
6030 Base::VisitCallExpr(CE);
6031
6032 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6033 }
6034
Richard Smith6c3af3d2013-01-17 01:17:56 +00006035 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smith0c0b3902013-06-30 10:40:20 +00006036 // This is a call, so all subexpressions are sequenced before the result.
6037 SequencedSubexpression Sequenced(*this);
6038
Richard Smith6c3af3d2013-01-17 01:17:56 +00006039 if (!CCE->isListInitialization())
6040 return VisitExpr(CCE);
6041
6042 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00006043 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00006044 SequenceTree::Seq Parent = Region;
6045 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6046 E = CCE->arg_end();
6047 I != E; ++I) {
6048 Region = Tree.allocate(Parent);
6049 Elts.push_back(Region);
6050 Visit(*I);
6051 }
6052
6053 // Forget that the initializers are sequenced.
6054 Region = Parent;
6055 for (unsigned I = 0; I < Elts.size(); ++I)
6056 Tree.merge(Elts[I]);
6057 }
6058
6059 void VisitInitListExpr(InitListExpr *ILE) {
6060 if (!SemaRef.getLangOpts().CPlusPlus11)
6061 return VisitExpr(ILE);
6062
6063 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00006064 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00006065 SequenceTree::Seq Parent = Region;
6066 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6067 Expr *E = ILE->getInit(I);
6068 if (!E) continue;
6069 Region = Tree.allocate(Parent);
6070 Elts.push_back(Region);
6071 Visit(E);
6072 }
6073
6074 // Forget that the initializers are sequenced.
6075 Region = Parent;
6076 for (unsigned I = 0; I < Elts.size(); ++I)
6077 Tree.merge(Elts[I]);
6078 }
6079};
6080}
6081
6082void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelme7205c02013-08-10 12:33:24 +00006083 SmallVector<Expr *, 8> WorkList;
Richard Smith1a2dcd52013-01-17 23:18:09 +00006084 WorkList.push_back(E);
6085 while (!WorkList.empty()) {
Robert Wilhelm344472e2013-08-23 16:11:15 +00006086 Expr *Item = WorkList.pop_back_val();
Richard Smith1a2dcd52013-01-17 23:18:09 +00006087 SequenceChecker(*this, Item, WorkList);
6088 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006089}
6090
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006091void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6092 bool IsConstexpr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00006093 CheckImplicitConversions(E, CheckLoc);
6094 CheckUnsequencedOperations(E);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006095 if (!IsConstexpr && !E->isValueDependent())
6096 CheckForIntOverflow(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006097}
6098
John McCall15d7d122010-11-11 03:21:53 +00006099void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6100 FieldDecl *BitField,
6101 Expr *Init) {
6102 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6103}
6104
Mike Stumpf8c49212010-01-21 03:59:47 +00006105/// CheckParmsForFunctionDef - Check that the parameters of the given
6106/// function are appropriate for the definition of a function. This
6107/// takes care of any checks that cannot be performed on the
6108/// declaration itself, e.g., that the types of each of the function
6109/// parameters are complete.
Reid Kleckner8c0501c2013-06-24 14:38:26 +00006110bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6111 ParmVarDecl *const *PEnd,
Douglas Gregor82aa7132010-11-01 18:37:59 +00006112 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00006113 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00006114 for (; P != PEnd; ++P) {
6115 ParmVarDecl *Param = *P;
6116
Mike Stumpf8c49212010-01-21 03:59:47 +00006117 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6118 // function declarator that is part of a function definition of
6119 // that function shall not have incomplete type.
6120 //
6121 // This is also C++ [dcl.fct]p6.
6122 if (!Param->isInvalidDecl() &&
6123 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00006124 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00006125 Param->setInvalidDecl();
6126 HasInvalidParm = true;
6127 }
6128
6129 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6130 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00006131 if (CheckParameterNames &&
6132 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00006133 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006134 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00006135 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00006136
6137 // C99 6.7.5.3p12:
6138 // If the function declarator is not part of a definition of that
6139 // function, parameters may have incomplete type and may use the [*]
6140 // notation in their sequences of declarator specifiers to specify
6141 // variable length array types.
6142 QualType PType = Param->getOriginalType();
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006143 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigd17e3402010-02-01 05:02:49 +00006144 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitfc093362013-03-01 21:41:22 +00006145 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00006146 // information is added for it.
6147 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006148 break;
Sam Weinigd17e3402010-02-01 05:02:49 +00006149 }
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006150 PType= AT->getElementType();
Sam Weinigd17e3402010-02-01 05:02:49 +00006151 }
Reid Kleckner9b601952013-06-21 12:45:15 +00006152
6153 // MSVC destroys objects passed by value in the callee. Therefore a
6154 // function definition which takes such a parameter must be able to call the
6155 // object's destructor.
6156 if (getLangOpts().CPlusPlus &&
6157 Context.getTargetInfo().getCXXABI().isArgumentDestroyedByCallee()) {
6158 if (const RecordType *RT = Param->getType()->getAs<RecordType>())
6159 FinalizeVarWithDestructor(Param, RT);
6160 }
Mike Stumpf8c49212010-01-21 03:59:47 +00006161 }
6162
6163 return HasInvalidParm;
6164}
John McCallb7f4ffe2010-08-12 21:44:57 +00006165
6166/// CheckCastAlign - Implements -Wcast-align, which warns when a
6167/// pointer cast increases the alignment requirements.
6168void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6169 // This is actually a lot of work to potentially be doing on every
6170 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00006171 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6172 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00006173 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00006174 return;
6175
6176 // Ignore dependent types.
6177 if (T->isDependentType() || Op->getType()->isDependentType())
6178 return;
6179
6180 // Require that the destination be a pointer type.
6181 const PointerType *DestPtr = T->getAs<PointerType>();
6182 if (!DestPtr) return;
6183
6184 // If the destination has alignment 1, we're done.
6185 QualType DestPointee = DestPtr->getPointeeType();
6186 if (DestPointee->isIncompleteType()) return;
6187 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6188 if (DestAlign.isOne()) return;
6189
6190 // Require that the source be a pointer type.
6191 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6192 if (!SrcPtr) return;
6193 QualType SrcPointee = SrcPtr->getPointeeType();
6194
6195 // Whitelist casts from cv void*. We already implicitly
6196 // whitelisted casts to cv void*, since they have alignment 1.
6197 // Also whitelist casts involving incomplete types, which implicitly
6198 // includes 'void'.
6199 if (SrcPointee->isIncompleteType()) return;
6200
6201 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6202 if (SrcAlign >= DestAlign) return;
6203
6204 Diag(TRange.getBegin(), diag::warn_cast_align)
6205 << Op->getType() << T
6206 << static_cast<unsigned>(SrcAlign.getQuantity())
6207 << static_cast<unsigned>(DestAlign.getQuantity())
6208 << TRange << Op->getSourceRange();
6209}
6210
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006211static const Type* getElementType(const Expr *BaseExpr) {
6212 const Type* EltType = BaseExpr->getType().getTypePtr();
6213 if (EltType->isAnyPointerType())
6214 return EltType->getPointeeType().getTypePtr();
6215 else if (EltType->isArrayType())
6216 return EltType->getBaseElementTypeUnsafe();
6217 return EltType;
6218}
6219
Chandler Carruthc2684342011-08-05 09:10:50 +00006220/// \brief Check whether this array fits the idiom of a size-one tail padded
6221/// array member of a struct.
6222///
6223/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6224/// commonly used to emulate flexible arrays in C89 code.
6225static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6226 const NamedDecl *ND) {
6227 if (Size != 1 || !ND) return false;
6228
6229 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6230 if (!FD) return false;
6231
6232 // Don't consider sizes resulting from macro expansions or template argument
6233 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00006234
6235 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006236 while (TInfo) {
6237 TypeLoc TL = TInfo->getTypeLoc();
6238 // Look through typedefs.
David Blaikie39e6ab42013-02-18 22:06:02 +00006239 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6240 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006241 TInfo = TDL->getTypeSourceInfo();
6242 continue;
6243 }
David Blaikie39e6ab42013-02-18 22:06:02 +00006244 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6245 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier5e253012013-02-06 00:58:34 +00006246 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6247 return false;
6248 }
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006249 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00006250 }
Chandler Carruthc2684342011-08-05 09:10:50 +00006251
6252 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00006253 if (!RD) return false;
6254 if (RD->isUnion()) return false;
6255 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6256 if (!CRD->isStandardLayout()) return false;
6257 }
Chandler Carruthc2684342011-08-05 09:10:50 +00006258
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00006259 // See if this is the last field decl in the record.
6260 const Decl *D = FD;
6261 while ((D = D->getNextDeclInContext()))
6262 if (isa<FieldDecl>(D))
6263 return false;
6264 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00006265}
6266
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006267void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006268 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00006269 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00006270 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006271 if (IndexExpr->isValueDependent())
6272 return;
6273
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00006274 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006275 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00006276 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006277 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00006278 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00006279 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00006280
Chandler Carruth34064582011-02-17 20:55:08 +00006281 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006282 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00006283 return;
Richard Smith25b009a2011-12-16 19:31:14 +00006284 if (IndexNegated)
6285 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00006286
Chandler Carruthba447122011-08-05 08:07:29 +00006287 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00006288 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6289 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00006290 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00006291 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00006292
Ted Kremenek9e060ca2011-02-23 23:06:04 +00006293 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00006294 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00006295 if (!size.isStrictlyPositive())
6296 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006297
6298 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00006299 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006300 // Make sure we're comparing apples to apples when comparing index to size
6301 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6302 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00006303 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00006304 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006305 if (ptrarith_typesize != array_typesize) {
6306 // There's a cast to a different size type involved
6307 uint64_t ratio = array_typesize / ptrarith_typesize;
6308 // TODO: Be smarter about handling cases where array_typesize is not a
6309 // multiple of ptrarith_typesize
6310 if (ptrarith_typesize * ratio == array_typesize)
6311 size *= llvm::APInt(size.getBitWidth(), ratio);
6312 }
6313 }
6314
Chandler Carruth34064582011-02-17 20:55:08 +00006315 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00006316 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00006317 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00006318 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00006319
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006320 // For array subscripting the index must be less than size, but for pointer
6321 // arithmetic also allow the index (offset) to be equal to size since
6322 // computing the next address after the end of the array is legal and
6323 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00006324 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00006325 return;
6326
6327 // Also don't warn for arrays of size 1 which are members of some
6328 // structure. These are often used to approximate flexible arrays in C89
6329 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006330 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00006331 return;
Chandler Carruth34064582011-02-17 20:55:08 +00006332
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006333 // Suppress the warning if the subscript expression (as identified by the
6334 // ']' location) and the index expression are both from macro expansions
6335 // within a system header.
6336 if (ASE) {
6337 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6338 ASE->getRBracketLoc());
6339 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6340 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6341 IndexExpr->getLocStart());
Eli Friedman24146972013-08-22 00:27:10 +00006342 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006343 return;
6344 }
6345 }
6346
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006347 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006348 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006349 DiagID = diag::warn_array_index_exceeds_bounds;
6350
6351 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6352 PDiag(DiagID) << index.toString(10, true)
6353 << size.toString(10, true)
6354 << (unsigned)size.getLimitedValue(~0U)
6355 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00006356 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006357 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006358 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006359 DiagID = diag::warn_ptr_arith_precedes_bounds;
6360 if (index.isNegative()) index = -index;
6361 }
6362
6363 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6364 PDiag(DiagID) << index.toString(10, true)
6365 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006366 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00006367
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00006368 if (!ND) {
6369 // Try harder to find a NamedDecl to point at in the note.
6370 while (const ArraySubscriptExpr *ASE =
6371 dyn_cast<ArraySubscriptExpr>(BaseExpr))
6372 BaseExpr = ASE->getBase()->IgnoreParenCasts();
6373 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6374 ND = dyn_cast<NamedDecl>(DRE->getDecl());
6375 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6376 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6377 }
6378
Chandler Carruth35001ca2011-02-17 21:10:52 +00006379 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006380 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6381 PDiag(diag::note_array_index_out_of_bounds)
6382 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006383}
6384
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006385void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006386 int AllowOnePastEnd = 0;
6387 while (expr) {
6388 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006389 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006390 case Stmt::ArraySubscriptExprClass: {
6391 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006392 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006393 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006394 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006395 }
6396 case Stmt::UnaryOperatorClass: {
6397 // Only unwrap the * and & unary operators
6398 const UnaryOperator *UO = cast<UnaryOperator>(expr);
6399 expr = UO->getSubExpr();
6400 switch (UO->getOpcode()) {
6401 case UO_AddrOf:
6402 AllowOnePastEnd++;
6403 break;
6404 case UO_Deref:
6405 AllowOnePastEnd--;
6406 break;
6407 default:
6408 return;
6409 }
6410 break;
6411 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006412 case Stmt::ConditionalOperatorClass: {
6413 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
6414 if (const Expr *lhs = cond->getLHS())
6415 CheckArrayAccess(lhs);
6416 if (const Expr *rhs = cond->getRHS())
6417 CheckArrayAccess(rhs);
6418 return;
6419 }
6420 default:
6421 return;
6422 }
Peter Collingbournef111d932011-04-15 00:35:48 +00006423 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006424}
John McCallf85e1932011-06-15 23:02:42 +00006425
6426//===--- CHECK: Objective-C retain cycles ----------------------------------//
6427
6428namespace {
6429 struct RetainCycleOwner {
6430 RetainCycleOwner() : Variable(0), Indirect(false) {}
6431 VarDecl *Variable;
6432 SourceRange Range;
6433 SourceLocation Loc;
6434 bool Indirect;
6435
6436 void setLocsFrom(Expr *e) {
6437 Loc = e->getExprLoc();
6438 Range = e->getSourceRange();
6439 }
6440 };
6441}
6442
6443/// Consider whether capturing the given variable can possibly lead to
6444/// a retain cycle.
6445static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00006446 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00006447 // lifetime. In MRR, it's captured strongly if the variable is
6448 // __block and has an appropriate type.
6449 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6450 return false;
6451
6452 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00006453 if (ref)
6454 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00006455 return true;
6456}
6457
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006458static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00006459 while (true) {
6460 e = e->IgnoreParens();
6461 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6462 switch (cast->getCastKind()) {
6463 case CK_BitCast:
6464 case CK_LValueBitCast:
6465 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00006466 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00006467 e = cast->getSubExpr();
6468 continue;
6469
John McCallf85e1932011-06-15 23:02:42 +00006470 default:
6471 return false;
6472 }
6473 }
6474
6475 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6476 ObjCIvarDecl *ivar = ref->getDecl();
6477 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6478 return false;
6479
6480 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006481 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006482 return false;
6483
6484 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6485 owner.Indirect = true;
6486 return true;
6487 }
6488
6489 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6490 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6491 if (!var) return false;
6492 return considerVariable(var, ref, owner);
6493 }
6494
John McCallf85e1932011-06-15 23:02:42 +00006495 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6496 if (member->isArrow()) return false;
6497
6498 // Don't count this as an indirect ownership.
6499 e = member->getBase();
6500 continue;
6501 }
6502
John McCall4b9c2d22011-11-06 09:01:30 +00006503 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6504 // Only pay attention to pseudo-objects on property references.
6505 ObjCPropertyRefExpr *pre
6506 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6507 ->IgnoreParens());
6508 if (!pre) return false;
6509 if (pre->isImplicitProperty()) return false;
6510 ObjCPropertyDecl *property = pre->getExplicitProperty();
6511 if (!property->isRetaining() &&
6512 !(property->getPropertyIvarDecl() &&
6513 property->getPropertyIvarDecl()->getType()
6514 .getObjCLifetime() == Qualifiers::OCL_Strong))
6515 return false;
6516
6517 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006518 if (pre->isSuperReceiver()) {
6519 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6520 if (!owner.Variable)
6521 return false;
6522 owner.Loc = pre->getLocation();
6523 owner.Range = pre->getSourceRange();
6524 return true;
6525 }
John McCall4b9c2d22011-11-06 09:01:30 +00006526 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6527 ->getSourceExpr());
6528 continue;
6529 }
6530
John McCallf85e1932011-06-15 23:02:42 +00006531 // Array ivars?
6532
6533 return false;
6534 }
6535}
6536
6537namespace {
6538 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6539 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6540 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6541 Variable(variable), Capturer(0) {}
6542
6543 VarDecl *Variable;
6544 Expr *Capturer;
6545
6546 void VisitDeclRefExpr(DeclRefExpr *ref) {
6547 if (ref->getDecl() == Variable && !Capturer)
6548 Capturer = ref;
6549 }
6550
John McCallf85e1932011-06-15 23:02:42 +00006551 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6552 if (Capturer) return;
6553 Visit(ref->getBase());
6554 if (Capturer && ref->isFreeIvar())
6555 Capturer = ref;
6556 }
6557
6558 void VisitBlockExpr(BlockExpr *block) {
6559 // Look inside nested blocks
6560 if (block->getBlockDecl()->capturesVariable(Variable))
6561 Visit(block->getBlockDecl()->getBody());
6562 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00006563
6564 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6565 if (Capturer) return;
6566 if (OVE->getSourceExpr())
6567 Visit(OVE->getSourceExpr());
6568 }
John McCallf85e1932011-06-15 23:02:42 +00006569 };
6570}
6571
6572/// Check whether the given argument is a block which captures a
6573/// variable.
6574static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6575 assert(owner.Variable && owner.Loc.isValid());
6576
6577 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00006578
6579 // Look through [^{...} copy] and Block_copy(^{...}).
6580 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6581 Selector Cmd = ME->getSelector();
6582 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6583 e = ME->getInstanceReceiver();
6584 if (!e)
6585 return 0;
6586 e = e->IgnoreParenCasts();
6587 }
6588 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6589 if (CE->getNumArgs() == 1) {
6590 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00006591 if (Fn) {
6592 const IdentifierInfo *FnI = Fn->getIdentifier();
6593 if (FnI && FnI->isStr("_Block_copy")) {
6594 e = CE->getArg(0)->IgnoreParenCasts();
6595 }
6596 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00006597 }
6598 }
6599
John McCallf85e1932011-06-15 23:02:42 +00006600 BlockExpr *block = dyn_cast<BlockExpr>(e);
6601 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6602 return 0;
6603
6604 FindCaptureVisitor visitor(S.Context, owner.Variable);
6605 visitor.Visit(block->getBlockDecl()->getBody());
6606 return visitor.Capturer;
6607}
6608
6609static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6610 RetainCycleOwner &owner) {
6611 assert(capturer);
6612 assert(owner.Variable && owner.Loc.isValid());
6613
6614 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6615 << owner.Variable << capturer->getSourceRange();
6616 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6617 << owner.Indirect << owner.Range;
6618}
6619
6620/// Check for a keyword selector that starts with the word 'add' or
6621/// 'set'.
6622static bool isSetterLikeSelector(Selector sel) {
6623 if (sel.isUnarySelector()) return false;
6624
Chris Lattner5f9e2722011-07-23 10:55:15 +00006625 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00006626 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006627 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00006628 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006629 else if (str.startswith("add")) {
6630 // Specially whitelist 'addOperationWithBlock:'.
6631 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6632 return false;
6633 str = str.substr(3);
6634 }
John McCallf85e1932011-06-15 23:02:42 +00006635 else
6636 return false;
6637
6638 if (str.empty()) return true;
Jordan Rose3f6f51e2013-02-08 22:30:41 +00006639 return !isLowercase(str.front());
John McCallf85e1932011-06-15 23:02:42 +00006640}
6641
6642/// Check a message send to see if it's likely to cause a retain cycle.
6643void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6644 // Only check instance methods whose selector looks like a setter.
6645 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6646 return;
6647
6648 // Try to find a variable that the receiver is strongly owned by.
6649 RetainCycleOwner owner;
6650 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006651 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006652 return;
6653 } else {
6654 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6655 owner.Variable = getCurMethodDecl()->getSelfDecl();
6656 owner.Loc = msg->getSuperLoc();
6657 owner.Range = msg->getSuperLoc();
6658 }
6659
6660 // Check whether the receiver is captured by any of the arguments.
6661 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6662 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6663 return diagnoseRetainCycle(*this, capturer, owner);
6664}
6665
6666/// Check a property assign to see if it's likely to cause a retain cycle.
6667void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6668 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006669 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00006670 return;
6671
6672 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6673 diagnoseRetainCycle(*this, capturer, owner);
6674}
6675
Jordan Rosee10f4d32012-09-15 02:48:31 +00006676void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6677 RetainCycleOwner Owner;
6678 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6679 return;
6680
6681 // Because we don't have an expression for the variable, we have to set the
6682 // location explicitly here.
6683 Owner.Loc = Var->getLocation();
6684 Owner.Range = Var->getSourceRange();
6685
6686 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6687 diagnoseRetainCycle(*this, Capturer, Owner);
6688}
6689
Ted Kremenek9d084012012-12-21 08:04:28 +00006690static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6691 Expr *RHS, bool isProperty) {
6692 // Check if RHS is an Objective-C object literal, which also can get
6693 // immediately zapped in a weak reference. Note that we explicitly
6694 // allow ObjCStringLiterals, since those are designed to never really die.
6695 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006696
Ted Kremenekd3292c82012-12-21 22:46:35 +00006697 // This enum needs to match with the 'select' in
6698 // warn_objc_arc_literal_assign (off-by-1).
6699 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6700 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6701 return false;
Ted Kremenekf530ff72012-12-21 21:59:39 +00006702
6703 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenekd3292c82012-12-21 22:46:35 +00006704 << (unsigned) Kind
Ted Kremenek9d084012012-12-21 08:04:28 +00006705 << (isProperty ? 0 : 1)
6706 << RHS->getSourceRange();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006707
6708 return true;
Ted Kremenek9d084012012-12-21 08:04:28 +00006709}
6710
Ted Kremenekb29b30f2012-12-21 19:45:30 +00006711static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6712 Qualifiers::ObjCLifetime LT,
6713 Expr *RHS, bool isProperty) {
6714 // Strip off any implicit cast added to get to the one ARC-specific.
6715 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6716 if (cast->getCastKind() == CK_ARCConsumeObject) {
6717 S.Diag(Loc, diag::warn_arc_retained_assign)
6718 << (LT == Qualifiers::OCL_ExplicitNone)
6719 << (isProperty ? 0 : 1)
6720 << RHS->getSourceRange();
6721 return true;
6722 }
6723 RHS = cast->getSubExpr();
6724 }
6725
6726 if (LT == Qualifiers::OCL_Weak &&
6727 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6728 return true;
6729
6730 return false;
6731}
6732
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006733bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6734 QualType LHS, Expr *RHS) {
6735 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6736
6737 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6738 return false;
6739
6740 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6741 return true;
6742
6743 return false;
6744}
6745
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006746void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6747 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006748 QualType LHSType;
6749 // PropertyRef on LHS type need be directly obtained from
6750 // its declaration as it has a PsuedoType.
6751 ObjCPropertyRefExpr *PRE
6752 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6753 if (PRE && !PRE->isImplicitProperty()) {
6754 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6755 if (PD)
6756 LHSType = PD->getType();
6757 }
6758
6759 if (LHSType.isNull())
6760 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00006761
6762 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6763
6764 if (LT == Qualifiers::OCL_Weak) {
6765 DiagnosticsEngine::Level Level =
6766 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6767 if (Level != DiagnosticsEngine::Ignored)
6768 getCurFunction()->markSafeWeakUse(LHS);
6769 }
6770
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006771 if (checkUnsafeAssigns(Loc, LHSType, RHS))
6772 return;
Jordan Rose7a270482012-09-28 22:21:35 +00006773
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006774 // FIXME. Check for other life times.
6775 if (LT != Qualifiers::OCL_None)
6776 return;
6777
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006778 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006779 if (PRE->isImplicitProperty())
6780 return;
6781 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6782 if (!PD)
6783 return;
6784
Bill Wendlingad017fa2012-12-20 19:22:21 +00006785 unsigned Attributes = PD->getPropertyAttributes();
6786 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006787 // when 'assign' attribute was not explicitly specified
6788 // by user, ignore it and rely on property type itself
6789 // for lifetime info.
6790 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6791 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6792 LHSType->isObjCRetainableType())
6793 return;
6794
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006795 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00006796 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006797 Diag(Loc, diag::warn_arc_retained_property_assign)
6798 << RHS->getSourceRange();
6799 return;
6800 }
6801 RHS = cast->getSubExpr();
6802 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006803 }
Bill Wendlingad017fa2012-12-20 19:22:21 +00006804 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006805 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6806 return;
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00006807 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006808 }
6809}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00006810
6811//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6812
6813namespace {
6814bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6815 SourceLocation StmtLoc,
6816 const NullStmt *Body) {
6817 // Do not warn if the body is a macro that expands to nothing, e.g:
6818 //
6819 // #define CALL(x)
6820 // if (condition)
6821 // CALL(0);
6822 //
6823 if (Body->hasLeadingEmptyMacro())
6824 return false;
6825
6826 // Get line numbers of statement and body.
6827 bool StmtLineInvalid;
6828 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6829 &StmtLineInvalid);
6830 if (StmtLineInvalid)
6831 return false;
6832
6833 bool BodyLineInvalid;
6834 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
6835 &BodyLineInvalid);
6836 if (BodyLineInvalid)
6837 return false;
6838
6839 // Warn if null statement and body are on the same line.
6840 if (StmtLine != BodyLine)
6841 return false;
6842
6843 return true;
6844}
6845} // Unnamed namespace
6846
6847void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
6848 const Stmt *Body,
6849 unsigned DiagID) {
6850 // Since this is a syntactic check, don't emit diagnostic for template
6851 // instantiations, this just adds noise.
6852 if (CurrentInstantiationScope)
6853 return;
6854
6855 // The body should be a null statement.
6856 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6857 if (!NBody)
6858 return;
6859
6860 // Do the usual checks.
6861 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6862 return;
6863
6864 Diag(NBody->getSemiLoc(), DiagID);
6865 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6866}
6867
6868void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
6869 const Stmt *PossibleBody) {
6870 assert(!CurrentInstantiationScope); // Ensured by caller
6871
6872 SourceLocation StmtLoc;
6873 const Stmt *Body;
6874 unsigned DiagID;
6875 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
6876 StmtLoc = FS->getRParenLoc();
6877 Body = FS->getBody();
6878 DiagID = diag::warn_empty_for_body;
6879 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
6880 StmtLoc = WS->getCond()->getSourceRange().getEnd();
6881 Body = WS->getBody();
6882 DiagID = diag::warn_empty_while_body;
6883 } else
6884 return; // Neither `for' nor `while'.
6885
6886 // The body should be a null statement.
6887 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6888 if (!NBody)
6889 return;
6890
6891 // Skip expensive checks if diagnostic is disabled.
6892 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
6893 DiagnosticsEngine::Ignored)
6894 return;
6895
6896 // Do the usual checks.
6897 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6898 return;
6899
6900 // `for(...);' and `while(...);' are popular idioms, so in order to keep
6901 // noise level low, emit diagnostics only if for/while is followed by a
6902 // CompoundStmt, e.g.:
6903 // for (int i = 0; i < n; i++);
6904 // {
6905 // a(i);
6906 // }
6907 // or if for/while is followed by a statement with more indentation
6908 // than for/while itself:
6909 // for (int i = 0; i < n; i++);
6910 // a(i);
6911 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
6912 if (!ProbableTypo) {
6913 bool BodyColInvalid;
6914 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
6915 PossibleBody->getLocStart(),
6916 &BodyColInvalid);
6917 if (BodyColInvalid)
6918 return;
6919
6920 bool StmtColInvalid;
6921 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
6922 S->getLocStart(),
6923 &StmtColInvalid);
6924 if (StmtColInvalid)
6925 return;
6926
6927 if (BodyCol > StmtCol)
6928 ProbableTypo = true;
6929 }
6930
6931 if (ProbableTypo) {
6932 Diag(NBody->getSemiLoc(), DiagID);
6933 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6934 }
6935}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006936
6937//===--- Layout compatibility ----------------------------------------------//
6938
6939namespace {
6940
6941bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
6942
6943/// \brief Check if two enumeration types are layout-compatible.
6944bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
6945 // C++11 [dcl.enum] p8:
6946 // Two enumeration types are layout-compatible if they have the same
6947 // underlying type.
6948 return ED1->isComplete() && ED2->isComplete() &&
6949 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
6950}
6951
6952/// \brief Check if two fields are layout-compatible.
6953bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
6954 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
6955 return false;
6956
6957 if (Field1->isBitField() != Field2->isBitField())
6958 return false;
6959
6960 if (Field1->isBitField()) {
6961 // Make sure that the bit-fields are the same length.
6962 unsigned Bits1 = Field1->getBitWidthValue(C);
6963 unsigned Bits2 = Field2->getBitWidthValue(C);
6964
6965 if (Bits1 != Bits2)
6966 return false;
6967 }
6968
6969 return true;
6970}
6971
6972/// \brief Check if two standard-layout structs are layout-compatible.
6973/// (C++11 [class.mem] p17)
6974bool isLayoutCompatibleStruct(ASTContext &C,
6975 RecordDecl *RD1,
6976 RecordDecl *RD2) {
6977 // If both records are C++ classes, check that base classes match.
6978 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
6979 // If one of records is a CXXRecordDecl we are in C++ mode,
6980 // thus the other one is a CXXRecordDecl, too.
6981 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
6982 // Check number of base classes.
6983 if (D1CXX->getNumBases() != D2CXX->getNumBases())
6984 return false;
6985
6986 // Check the base classes.
6987 for (CXXRecordDecl::base_class_const_iterator
6988 Base1 = D1CXX->bases_begin(),
6989 BaseEnd1 = D1CXX->bases_end(),
6990 Base2 = D2CXX->bases_begin();
6991 Base1 != BaseEnd1;
6992 ++Base1, ++Base2) {
6993 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
6994 return false;
6995 }
6996 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
6997 // If only RD2 is a C++ class, it should have zero base classes.
6998 if (D2CXX->getNumBases() > 0)
6999 return false;
7000 }
7001
7002 // Check the fields.
7003 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7004 Field2End = RD2->field_end(),
7005 Field1 = RD1->field_begin(),
7006 Field1End = RD1->field_end();
7007 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7008 if (!isLayoutCompatible(C, *Field1, *Field2))
7009 return false;
7010 }
7011 if (Field1 != Field1End || Field2 != Field2End)
7012 return false;
7013
7014 return true;
7015}
7016
7017/// \brief Check if two standard-layout unions are layout-compatible.
7018/// (C++11 [class.mem] p18)
7019bool isLayoutCompatibleUnion(ASTContext &C,
7020 RecordDecl *RD1,
7021 RecordDecl *RD2) {
7022 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
7023 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
7024 Field2End = RD2->field_end();
7025 Field2 != Field2End; ++Field2) {
7026 UnmatchedFields.insert(*Field2);
7027 }
7028
7029 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
7030 Field1End = RD1->field_end();
7031 Field1 != Field1End; ++Field1) {
7032 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7033 I = UnmatchedFields.begin(),
7034 E = UnmatchedFields.end();
7035
7036 for ( ; I != E; ++I) {
7037 if (isLayoutCompatible(C, *Field1, *I)) {
7038 bool Result = UnmatchedFields.erase(*I);
7039 (void) Result;
7040 assert(Result);
7041 break;
7042 }
7043 }
7044 if (I == E)
7045 return false;
7046 }
7047
7048 return UnmatchedFields.empty();
7049}
7050
7051bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7052 if (RD1->isUnion() != RD2->isUnion())
7053 return false;
7054
7055 if (RD1->isUnion())
7056 return isLayoutCompatibleUnion(C, RD1, RD2);
7057 else
7058 return isLayoutCompatibleStruct(C, RD1, RD2);
7059}
7060
7061/// \brief Check if two types are layout-compatible in C++11 sense.
7062bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7063 if (T1.isNull() || T2.isNull())
7064 return false;
7065
7066 // C++11 [basic.types] p11:
7067 // If two types T1 and T2 are the same type, then T1 and T2 are
7068 // layout-compatible types.
7069 if (C.hasSameType(T1, T2))
7070 return true;
7071
7072 T1 = T1.getCanonicalType().getUnqualifiedType();
7073 T2 = T2.getCanonicalType().getUnqualifiedType();
7074
7075 const Type::TypeClass TC1 = T1->getTypeClass();
7076 const Type::TypeClass TC2 = T2->getTypeClass();
7077
7078 if (TC1 != TC2)
7079 return false;
7080
7081 if (TC1 == Type::Enum) {
7082 return isLayoutCompatible(C,
7083 cast<EnumType>(T1)->getDecl(),
7084 cast<EnumType>(T2)->getDecl());
7085 } else if (TC1 == Type::Record) {
7086 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7087 return false;
7088
7089 return isLayoutCompatible(C,
7090 cast<RecordType>(T1)->getDecl(),
7091 cast<RecordType>(T2)->getDecl());
7092 }
7093
7094 return false;
7095}
7096}
7097
7098//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7099
7100namespace {
7101/// \brief Given a type tag expression find the type tag itself.
7102///
7103/// \param TypeExpr Type tag expression, as it appears in user's code.
7104///
7105/// \param VD Declaration of an identifier that appears in a type tag.
7106///
7107/// \param MagicValue Type tag magic value.
7108bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7109 const ValueDecl **VD, uint64_t *MagicValue) {
7110 while(true) {
7111 if (!TypeExpr)
7112 return false;
7113
7114 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7115
7116 switch (TypeExpr->getStmtClass()) {
7117 case Stmt::UnaryOperatorClass: {
7118 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7119 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7120 TypeExpr = UO->getSubExpr();
7121 continue;
7122 }
7123 return false;
7124 }
7125
7126 case Stmt::DeclRefExprClass: {
7127 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7128 *VD = DRE->getDecl();
7129 return true;
7130 }
7131
7132 case Stmt::IntegerLiteralClass: {
7133 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7134 llvm::APInt MagicValueAPInt = IL->getValue();
7135 if (MagicValueAPInt.getActiveBits() <= 64) {
7136 *MagicValue = MagicValueAPInt.getZExtValue();
7137 return true;
7138 } else
7139 return false;
7140 }
7141
7142 case Stmt::BinaryConditionalOperatorClass:
7143 case Stmt::ConditionalOperatorClass: {
7144 const AbstractConditionalOperator *ACO =
7145 cast<AbstractConditionalOperator>(TypeExpr);
7146 bool Result;
7147 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7148 if (Result)
7149 TypeExpr = ACO->getTrueExpr();
7150 else
7151 TypeExpr = ACO->getFalseExpr();
7152 continue;
7153 }
7154 return false;
7155 }
7156
7157 case Stmt::BinaryOperatorClass: {
7158 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7159 if (BO->getOpcode() == BO_Comma) {
7160 TypeExpr = BO->getRHS();
7161 continue;
7162 }
7163 return false;
7164 }
7165
7166 default:
7167 return false;
7168 }
7169 }
7170}
7171
7172/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7173///
7174/// \param TypeExpr Expression that specifies a type tag.
7175///
7176/// \param MagicValues Registered magic values.
7177///
7178/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7179/// kind.
7180///
7181/// \param TypeInfo Information about the corresponding C type.
7182///
7183/// \returns true if the corresponding C type was found.
7184bool GetMatchingCType(
7185 const IdentifierInfo *ArgumentKind,
7186 const Expr *TypeExpr, const ASTContext &Ctx,
7187 const llvm::DenseMap<Sema::TypeTagMagicValue,
7188 Sema::TypeTagData> *MagicValues,
7189 bool &FoundWrongKind,
7190 Sema::TypeTagData &TypeInfo) {
7191 FoundWrongKind = false;
7192
7193 // Variable declaration that has type_tag_for_datatype attribute.
7194 const ValueDecl *VD = NULL;
7195
7196 uint64_t MagicValue;
7197
7198 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7199 return false;
7200
7201 if (VD) {
7202 for (specific_attr_iterator<TypeTagForDatatypeAttr>
7203 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
7204 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
7205 I != E; ++I) {
7206 if (I->getArgumentKind() != ArgumentKind) {
7207 FoundWrongKind = true;
7208 return false;
7209 }
7210 TypeInfo.Type = I->getMatchingCType();
7211 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7212 TypeInfo.MustBeNull = I->getMustBeNull();
7213 return true;
7214 }
7215 return false;
7216 }
7217
7218 if (!MagicValues)
7219 return false;
7220
7221 llvm::DenseMap<Sema::TypeTagMagicValue,
7222 Sema::TypeTagData>::const_iterator I =
7223 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7224 if (I == MagicValues->end())
7225 return false;
7226
7227 TypeInfo = I->second;
7228 return true;
7229}
7230} // unnamed namespace
7231
7232void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7233 uint64_t MagicValue, QualType Type,
7234 bool LayoutCompatible,
7235 bool MustBeNull) {
7236 if (!TypeTagForDatatypeMagicValues)
7237 TypeTagForDatatypeMagicValues.reset(
7238 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7239
7240 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7241 (*TypeTagForDatatypeMagicValues)[Magic] =
7242 TypeTagData(Type, LayoutCompatible, MustBeNull);
7243}
7244
7245namespace {
7246bool IsSameCharType(QualType T1, QualType T2) {
7247 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7248 if (!BT1)
7249 return false;
7250
7251 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7252 if (!BT2)
7253 return false;
7254
7255 BuiltinType::Kind T1Kind = BT1->getKind();
7256 BuiltinType::Kind T2Kind = BT2->getKind();
7257
7258 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
7259 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
7260 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7261 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7262}
7263} // unnamed namespace
7264
7265void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7266 const Expr * const *ExprArgs) {
7267 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7268 bool IsPointerAttr = Attr->getIsPointer();
7269
7270 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7271 bool FoundWrongKind;
7272 TypeTagData TypeInfo;
7273 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7274 TypeTagForDatatypeMagicValues.get(),
7275 FoundWrongKind, TypeInfo)) {
7276 if (FoundWrongKind)
7277 Diag(TypeTagExpr->getExprLoc(),
7278 diag::warn_type_tag_for_datatype_wrong_kind)
7279 << TypeTagExpr->getSourceRange();
7280 return;
7281 }
7282
7283 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7284 if (IsPointerAttr) {
7285 // Skip implicit cast of pointer to `void *' (as a function argument).
7286 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5a249802012-11-03 16:07:49 +00007287 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkob57ce4e2012-11-03 22:10:18 +00007288 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00007289 ArgumentExpr = ICE->getSubExpr();
7290 }
7291 QualType ArgumentType = ArgumentExpr->getType();
7292
7293 // Passing a `void*' pointer shouldn't trigger a warning.
7294 if (IsPointerAttr && ArgumentType->isVoidPointerType())
7295 return;
7296
7297 if (TypeInfo.MustBeNull) {
7298 // Type tag with matching void type requires a null pointer.
7299 if (!ArgumentExpr->isNullPointerConstant(Context,
7300 Expr::NPC_ValueDependentIsNotNull)) {
7301 Diag(ArgumentExpr->getExprLoc(),
7302 diag::warn_type_safety_null_pointer_required)
7303 << ArgumentKind->getName()
7304 << ArgumentExpr->getSourceRange()
7305 << TypeTagExpr->getSourceRange();
7306 }
7307 return;
7308 }
7309
7310 QualType RequiredType = TypeInfo.Type;
7311 if (IsPointerAttr)
7312 RequiredType = Context.getPointerType(RequiredType);
7313
7314 bool mismatch = false;
7315 if (!TypeInfo.LayoutCompatible) {
7316 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7317
7318 // C++11 [basic.fundamental] p1:
7319 // Plain char, signed char, and unsigned char are three distinct types.
7320 //
7321 // But we treat plain `char' as equivalent to `signed char' or `unsigned
7322 // char' depending on the current char signedness mode.
7323 if (mismatch)
7324 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7325 RequiredType->getPointeeType())) ||
7326 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7327 mismatch = false;
7328 } else
7329 if (IsPointerAttr)
7330 mismatch = !isLayoutCompatible(Context,
7331 ArgumentType->getPointeeType(),
7332 RequiredType->getPointeeType());
7333 else
7334 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7335
7336 if (mismatch)
7337 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
7338 << ArgumentType << ArgumentKind->getName()
7339 << TypeInfo.LayoutCompatible << RequiredType
7340 << ArgumentExpr->getSourceRange()
7341 << TypeTagExpr->getSourceRange();
7342}