blob: aa9ba2c8e68d4c50db92d3db94dd1b32351f8112 [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner59907c42007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump1eb44332009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattner59907c42007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall2d887082010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattner59907c42007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikiebe0ee872012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenek23245122007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rose3f6f51e2013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000030#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/Initialization.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Richard Smith0e218972013-08-05 18:49:43 +000035#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000036#include "llvm/ADT/SmallString.h"
Richard Smith0e218972013-08-05 18:49:43 +000037#include "llvm/ADT/STLExtras.h"
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +000038#include "llvm/Support/ConvertUTF.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/Support/raw_ostream.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000040#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000041using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000042using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000043
Chris Lattner60800082009-02-18 17:49:48 +000044SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000046 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +000047 PP.getLangOpts(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000048}
49
John McCall8e10f3b2011-02-26 05:39:39 +000050/// Checks that a call expression's argument count is the desired number.
51/// This is useful when doing custom type-checking. Returns true on error.
52static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53 unsigned argCount = call->getNumArgs();
54 if (argCount == desiredArgCount) return false;
55
56 if (argCount < desiredArgCount)
57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58 << 0 /*function call*/ << desiredArgCount << argCount
59 << call->getSourceRange();
60
61 // Highlight all the excess arguments.
62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63 call->getArg(argCount - 1)->getLocEnd());
64
65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66 << 0 /*function call*/ << desiredArgCount << argCount
67 << call->getArg(1)->getSourceRange();
68}
69
Julien Lerougee5939212012-04-28 17:39:16 +000070/// Check that the first argument to __builtin_annotation is an integer
71/// and the second argument is a non-wide string literal.
72static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73 if (checkArgCount(S, TheCall, 2))
74 return true;
75
76 // First argument should be an integer.
77 Expr *ValArg = TheCall->getArg(0);
78 QualType Ty = ValArg->getType();
79 if (!Ty->isIntegerType()) {
80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81 << ValArg->getSourceRange();
Julien Lerouge77f68bb2011-09-09 22:41:49 +000082 return true;
83 }
Julien Lerougee5939212012-04-28 17:39:16 +000084
85 // Second argument should be a constant string.
86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88 if (!Literal || !Literal->isAscii()) {
89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90 << StrArg->getSourceRange();
91 return true;
92 }
93
94 TheCall->setType(Ty);
Julien Lerouge77f68bb2011-09-09 22:41:49 +000095 return false;
96}
97
Richard Smith5154dce2013-07-11 02:27:57 +000098/// Check that the argument to __builtin_addressof is a glvalue, and set the
99/// result type to the corresponding pointer type.
100static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101 if (checkArgCount(S, TheCall, 1))
102 return true;
103
104 ExprResult Arg(S.Owned(TheCall->getArg(0)));
105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
107 return true;
108
109 TheCall->setArg(0, Arg.take());
110 TheCall->setType(ResultType);
111 return false;
112}
113
John McCall60d7b3a2010-08-24 06:29:42 +0000114ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000115Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +0000116 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000117
Chris Lattner946928f2010-10-01 23:23:24 +0000118 // Find out if any arguments are required to be integer constant expressions.
119 unsigned ICEArguments = 0;
120 ASTContext::GetBuiltinTypeError Error;
121 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
122 if (Error != ASTContext::GE_None)
123 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
124
125 // If any arguments are required to be ICE's, check and diagnose.
126 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
127 // Skip arguments not required to be ICE's.
128 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
129
130 llvm::APSInt Result;
131 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
132 return true;
133 ICEArguments &= ~(1 << ArgNo);
134 }
135
Anders Carlssond406bf02009-08-16 01:56:34 +0000136 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000137 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000138 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000139 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000140 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000141 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000142 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000143 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000144 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000145 if (SemaBuiltinVAStart(TheCall))
146 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000147 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000148 case Builtin::BI__builtin_isgreater:
149 case Builtin::BI__builtin_isgreaterequal:
150 case Builtin::BI__builtin_isless:
151 case Builtin::BI__builtin_islessequal:
152 case Builtin::BI__builtin_islessgreater:
153 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000154 if (SemaBuiltinUnorderedCompare(TheCall))
155 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000156 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000157 case Builtin::BI__builtin_fpclassify:
158 if (SemaBuiltinFPClassification(TheCall, 6))
159 return ExprError();
160 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000161 case Builtin::BI__builtin_isfinite:
162 case Builtin::BI__builtin_isinf:
163 case Builtin::BI__builtin_isinf_sign:
164 case Builtin::BI__builtin_isnan:
165 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000166 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000167 return ExprError();
168 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000169 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000170 return SemaBuiltinShuffleVector(TheCall);
171 // TheCall will be freed by the smart pointer here, but that's fine, since
172 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000173 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000174 if (SemaBuiltinPrefetch(TheCall))
175 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000176 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000177 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000178 if (SemaBuiltinObjectSize(TheCall))
179 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000180 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000181 case Builtin::BI__builtin_longjmp:
182 if (SemaBuiltinLongjmp(TheCall))
183 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000184 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000185
186 case Builtin::BI__builtin_classify_type:
187 if (checkArgCount(*this, TheCall, 1)) return true;
188 TheCall->setType(Context.IntTy);
189 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000190 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000191 if (checkArgCount(*this, TheCall, 1)) return true;
192 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000193 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000194 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000195 case Builtin::BI__sync_fetch_and_add_1:
196 case Builtin::BI__sync_fetch_and_add_2:
197 case Builtin::BI__sync_fetch_and_add_4:
198 case Builtin::BI__sync_fetch_and_add_8:
199 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000200 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000201 case Builtin::BI__sync_fetch_and_sub_1:
202 case Builtin::BI__sync_fetch_and_sub_2:
203 case Builtin::BI__sync_fetch_and_sub_4:
204 case Builtin::BI__sync_fetch_and_sub_8:
205 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000206 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000207 case Builtin::BI__sync_fetch_and_or_1:
208 case Builtin::BI__sync_fetch_and_or_2:
209 case Builtin::BI__sync_fetch_and_or_4:
210 case Builtin::BI__sync_fetch_and_or_8:
211 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000212 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000213 case Builtin::BI__sync_fetch_and_and_1:
214 case Builtin::BI__sync_fetch_and_and_2:
215 case Builtin::BI__sync_fetch_and_and_4:
216 case Builtin::BI__sync_fetch_and_and_8:
217 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000218 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000219 case Builtin::BI__sync_fetch_and_xor_1:
220 case Builtin::BI__sync_fetch_and_xor_2:
221 case Builtin::BI__sync_fetch_and_xor_4:
222 case Builtin::BI__sync_fetch_and_xor_8:
223 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000224 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000225 case Builtin::BI__sync_add_and_fetch_1:
226 case Builtin::BI__sync_add_and_fetch_2:
227 case Builtin::BI__sync_add_and_fetch_4:
228 case Builtin::BI__sync_add_and_fetch_8:
229 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000230 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000231 case Builtin::BI__sync_sub_and_fetch_1:
232 case Builtin::BI__sync_sub_and_fetch_2:
233 case Builtin::BI__sync_sub_and_fetch_4:
234 case Builtin::BI__sync_sub_and_fetch_8:
235 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000236 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000237 case Builtin::BI__sync_and_and_fetch_1:
238 case Builtin::BI__sync_and_and_fetch_2:
239 case Builtin::BI__sync_and_and_fetch_4:
240 case Builtin::BI__sync_and_and_fetch_8:
241 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000242 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000243 case Builtin::BI__sync_or_and_fetch_1:
244 case Builtin::BI__sync_or_and_fetch_2:
245 case Builtin::BI__sync_or_and_fetch_4:
246 case Builtin::BI__sync_or_and_fetch_8:
247 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000248 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000249 case Builtin::BI__sync_xor_and_fetch_1:
250 case Builtin::BI__sync_xor_and_fetch_2:
251 case Builtin::BI__sync_xor_and_fetch_4:
252 case Builtin::BI__sync_xor_and_fetch_8:
253 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000254 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000255 case Builtin::BI__sync_val_compare_and_swap_1:
256 case Builtin::BI__sync_val_compare_and_swap_2:
257 case Builtin::BI__sync_val_compare_and_swap_4:
258 case Builtin::BI__sync_val_compare_and_swap_8:
259 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000260 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000261 case Builtin::BI__sync_bool_compare_and_swap_1:
262 case Builtin::BI__sync_bool_compare_and_swap_2:
263 case Builtin::BI__sync_bool_compare_and_swap_4:
264 case Builtin::BI__sync_bool_compare_and_swap_8:
265 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000266 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000267 case Builtin::BI__sync_lock_test_and_set_1:
268 case Builtin::BI__sync_lock_test_and_set_2:
269 case Builtin::BI__sync_lock_test_and_set_4:
270 case Builtin::BI__sync_lock_test_and_set_8:
271 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000272 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000273 case Builtin::BI__sync_lock_release_1:
274 case Builtin::BI__sync_lock_release_2:
275 case Builtin::BI__sync_lock_release_4:
276 case Builtin::BI__sync_lock_release_8:
277 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000278 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000279 case Builtin::BI__sync_swap_1:
280 case Builtin::BI__sync_swap_2:
281 case Builtin::BI__sync_swap_4:
282 case Builtin::BI__sync_swap_8:
283 case Builtin::BI__sync_swap_16:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000284 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithff34d402012-04-12 05:08:17 +0000285#define BUILTIN(ID, TYPE, ATTRS)
286#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
287 case Builtin::BI##ID: \
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000288 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithff34d402012-04-12 05:08:17 +0000289#include "clang/Basic/Builtins.def"
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000290 case Builtin::BI__builtin_annotation:
Julien Lerougee5939212012-04-28 17:39:16 +0000291 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000292 return ExprError();
293 break;
Richard Smith5154dce2013-07-11 02:27:57 +0000294 case Builtin::BI__builtin_addressof:
295 if (SemaBuiltinAddressof(*this, TheCall))
296 return ExprError();
297 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000298 }
299
300 // Since the target specific builtins for each arch overlap, only check those
301 // of the arch we are compiling for.
302 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000303 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000304 case llvm::Triple::arm:
305 case llvm::Triple::thumb:
306 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
307 return ExprError();
308 break;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000309 case llvm::Triple::aarch64:
310 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
311 return ExprError();
312 break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000313 case llvm::Triple::mips:
314 case llvm::Triple::mipsel:
315 case llvm::Triple::mips64:
316 case llvm::Triple::mips64el:
317 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
318 return ExprError();
319 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000320 default:
321 break;
322 }
323 }
324
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000325 return TheCallResult;
Nate Begeman26a31422010-06-08 02:47:44 +0000326}
327
Nate Begeman61eecf52010-06-14 05:21:25 +0000328// Get the valid immediate range for the specified NEON type code.
329static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000330 NeonTypeFlags Type(t);
331 int IsQuad = Type.isQuad();
332 switch (Type.getEltType()) {
333 case NeonTypeFlags::Int8:
334 case NeonTypeFlags::Poly8:
335 return shift ? 7 : (8 << IsQuad) - 1;
336 case NeonTypeFlags::Int16:
337 case NeonTypeFlags::Poly16:
338 return shift ? 15 : (4 << IsQuad) - 1;
339 case NeonTypeFlags::Int32:
340 return shift ? 31 : (2 << IsQuad) - 1;
341 case NeonTypeFlags::Int64:
342 return shift ? 63 : (1 << IsQuad) - 1;
343 case NeonTypeFlags::Float16:
344 assert(!shift && "cannot shift float types!");
345 return (4 << IsQuad) - 1;
346 case NeonTypeFlags::Float32:
347 assert(!shift && "cannot shift float types!");
348 return (2 << IsQuad) - 1;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000349 case NeonTypeFlags::Float64:
350 assert(!shift && "cannot shift float types!");
351 return (1 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000352 }
David Blaikie7530c032012-01-17 06:56:22 +0000353 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000354}
355
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000356/// getNeonEltType - Return the QualType corresponding to the elements of
357/// the vector type specified by the NeonTypeFlags. This is used to check
358/// the pointer arguments for Neon load/store intrinsics.
359static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
360 switch (Flags.getEltType()) {
361 case NeonTypeFlags::Int8:
362 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
363 case NeonTypeFlags::Int16:
364 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
365 case NeonTypeFlags::Int32:
366 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
367 case NeonTypeFlags::Int64:
368 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
369 case NeonTypeFlags::Poly8:
370 return Context.SignedCharTy;
371 case NeonTypeFlags::Poly16:
372 return Context.ShortTy;
373 case NeonTypeFlags::Float16:
374 return Context.UnsignedShortTy;
375 case NeonTypeFlags::Float32:
376 return Context.FloatTy;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000377 case NeonTypeFlags::Float64:
378 return Context.DoubleTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000379 }
David Blaikie7530c032012-01-17 06:56:22 +0000380 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000381}
382
Tim Northoverb793f0d2013-08-01 09:23:19 +0000383bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
384 CallExpr *TheCall) {
385
386 llvm::APSInt Result;
387
388 uint64_t mask = 0;
389 unsigned TV = 0;
390 int PtrArgNum = -1;
391 bool HasConstPtr = false;
392 switch (BuiltinID) {
393#define GET_NEON_AARCH64_OVERLOAD_CHECK
394#include "clang/Basic/arm_neon.inc"
395#undef GET_NEON_AARCH64_OVERLOAD_CHECK
396 }
397
398 // For NEON intrinsics which are overloaded on vector element type, validate
399 // the immediate which specifies which variant to emit.
400 unsigned ImmArg = TheCall->getNumArgs() - 1;
401 if (mask) {
402 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
403 return true;
404
405 TV = Result.getLimitedValue(64);
406 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
407 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
408 << TheCall->getArg(ImmArg)->getSourceRange();
409 }
410
411 if (PtrArgNum >= 0) {
412 // Check that pointer arguments have the specified type.
413 Expr *Arg = TheCall->getArg(PtrArgNum);
414 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
415 Arg = ICE->getSubExpr();
416 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
417 QualType RHSTy = RHS.get()->getType();
418 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
419 if (HasConstPtr)
420 EltTy = EltTy.withConst();
421 QualType LHSTy = Context.getPointerType(EltTy);
422 AssignConvertType ConvTy;
423 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
424 if (RHS.isInvalid())
425 return true;
426 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
427 RHS.get(), AA_Assigning))
428 return true;
429 }
430
431 // For NEON intrinsics which take an immediate value as part of the
432 // instruction, range check them here.
433 unsigned i = 0, l = 0, u = 0;
434 switch (BuiltinID) {
435 default:
436 return false;
437#define GET_NEON_AARCH64_IMMEDIATE_CHECK
438#include "clang/Basic/arm_neon.inc"
439#undef GET_NEON_AARCH64_IMMEDIATE_CHECK
440 }
441 ;
442
443 // We can't check the value of a dependent argument.
444 if (TheCall->getArg(i)->isTypeDependent() ||
445 TheCall->getArg(i)->isValueDependent())
446 return false;
447
448 // Check that the immediate argument is actually a constant.
449 if (SemaBuiltinConstantArg(TheCall, i, Result))
450 return true;
451
452 // Range check against the upper/lower values for this isntruction.
453 unsigned Val = Result.getZExtValue();
454 if (Val < l || Val > (u + l))
455 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
456 << l << u + l << TheCall->getArg(i)->getSourceRange();
457
458 return false;
459}
460
Tim Northover09df2b02013-07-16 09:47:53 +0000461bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall) {
462 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
463 BuiltinID == ARM::BI__builtin_arm_strex) &&
464 "unexpected ARM builtin");
465 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex;
466
467 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
468
469 // Ensure that we have the proper number of arguments.
470 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
471 return true;
472
473 // Inspect the pointer argument of the atomic builtin. This should always be
474 // a pointer type, whose element is an integral scalar or pointer type.
475 // Because it is a pointer type, we don't have to worry about any implicit
476 // casts here.
477 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
478 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
479 if (PointerArgRes.isInvalid())
480 return true;
481 PointerArg = PointerArgRes.take();
482
483 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
484 if (!pointerType) {
485 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
486 << PointerArg->getType() << PointerArg->getSourceRange();
487 return true;
488 }
489
490 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
491 // task is to insert the appropriate casts into the AST. First work out just
492 // what the appropriate type is.
493 QualType ValType = pointerType->getPointeeType();
494 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
495 if (IsLdrex)
496 AddrType.addConst();
497
498 // Issue a warning if the cast is dodgy.
499 CastKind CastNeeded = CK_NoOp;
500 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
501 CastNeeded = CK_BitCast;
502 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
503 << PointerArg->getType()
504 << Context.getPointerType(AddrType)
505 << AA_Passing << PointerArg->getSourceRange();
506 }
507
508 // Finally, do the cast and replace the argument with the corrected version.
509 AddrType = Context.getPointerType(AddrType);
510 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
511 if (PointerArgRes.isInvalid())
512 return true;
513 PointerArg = PointerArgRes.take();
514
515 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
516
517 // In general, we allow ints, floats and pointers to be loaded and stored.
518 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
519 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
520 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
521 << PointerArg->getType() << PointerArg->getSourceRange();
522 return true;
523 }
524
525 // But ARM doesn't have instructions to deal with 128-bit versions.
526 if (Context.getTypeSize(ValType) > 64) {
527 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
528 << PointerArg->getType() << PointerArg->getSourceRange();
529 return true;
530 }
531
532 switch (ValType.getObjCLifetime()) {
533 case Qualifiers::OCL_None:
534 case Qualifiers::OCL_ExplicitNone:
535 // okay
536 break;
537
538 case Qualifiers::OCL_Weak:
539 case Qualifiers::OCL_Strong:
540 case Qualifiers::OCL_Autoreleasing:
541 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
542 << ValType << PointerArg->getSourceRange();
543 return true;
544 }
545
546
547 if (IsLdrex) {
548 TheCall->setType(ValType);
549 return false;
550 }
551
552 // Initialize the argument to be stored.
553 ExprResult ValArg = TheCall->getArg(0);
554 InitializedEntity Entity = InitializedEntity::InitializeParameter(
555 Context, ValType, /*consume*/ false);
556 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
557 if (ValArg.isInvalid())
558 return true;
Tim Northover09df2b02013-07-16 09:47:53 +0000559 TheCall->setArg(0, ValArg.get());
Tim Northovera6306fc2013-10-29 12:32:58 +0000560
561 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
562 // but the custom checker bypasses all default analysis.
563 TheCall->setType(Context.IntTy);
Tim Northover09df2b02013-07-16 09:47:53 +0000564 return false;
565}
566
Nate Begeman26a31422010-06-08 02:47:44 +0000567bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000568 llvm::APSInt Result;
569
Tim Northover09df2b02013-07-16 09:47:53 +0000570 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
571 BuiltinID == ARM::BI__builtin_arm_strex) {
572 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall);
573 }
574
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000575 uint64_t mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000576 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000577 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000578 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000579 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000580#define GET_NEON_OVERLOAD_CHECK
581#include "clang/Basic/arm_neon.inc"
582#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000583 }
584
Nate Begeman0d15c532010-06-13 04:47:52 +0000585 // For NEON intrinsics which are overloaded on vector element type, validate
586 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000587 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000588 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000589 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000590 return true;
591
Bob Wilsonda95f732011-11-08 01:16:11 +0000592 TV = Result.getLimitedValue(64);
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000593 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000594 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000595 << TheCall->getArg(ImmArg)->getSourceRange();
596 }
597
Bob Wilson46482552011-11-16 21:32:23 +0000598 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000599 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000600 Expr *Arg = TheCall->getArg(PtrArgNum);
601 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
602 Arg = ICE->getSubExpr();
603 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
604 QualType RHSTy = RHS.get()->getType();
605 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
606 if (HasConstPtr)
607 EltTy = EltTy.withConst();
608 QualType LHSTy = Context.getPointerType(EltTy);
609 AssignConvertType ConvTy;
610 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
611 if (RHS.isInvalid())
612 return true;
613 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
614 RHS.get(), AA_Assigning))
615 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000616 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000617
Nate Begeman0d15c532010-06-13 04:47:52 +0000618 // For NEON intrinsics which take an immediate value as part of the
619 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000620 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000621 switch (BuiltinID) {
622 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000623 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
624 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000625 case ARM::BI__builtin_arm_vcvtr_f:
626 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000627#define GET_NEON_IMMEDIATE_CHECK
628#include "clang/Basic/arm_neon.inc"
629#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000630 };
631
Douglas Gregor592a4232012-06-29 01:05:22 +0000632 // We can't check the value of a dependent argument.
633 if (TheCall->getArg(i)->isTypeDependent() ||
634 TheCall->getArg(i)->isValueDependent())
635 return false;
636
Nate Begeman61eecf52010-06-14 05:21:25 +0000637 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000638 if (SemaBuiltinConstantArg(TheCall, i, Result))
639 return true;
640
Nate Begeman61eecf52010-06-14 05:21:25 +0000641 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000642 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000643 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000644 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000645 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000646
Nate Begeman99c40bb2010-08-03 21:32:34 +0000647 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000648 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000649}
Daniel Dunbarde454282008-10-02 18:44:07 +0000650
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000651bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
652 unsigned i = 0, l = 0, u = 0;
653 switch (BuiltinID) {
654 default: return false;
655 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
656 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyanbe22cb82012-08-27 12:29:20 +0000657 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
658 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
659 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
660 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
661 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000662 };
663
664 // We can't check the value of a dependent argument.
665 if (TheCall->getArg(i)->isTypeDependent() ||
666 TheCall->getArg(i)->isValueDependent())
667 return false;
668
669 // Check that the immediate argument is actually a constant.
670 llvm::APSInt Result;
671 if (SemaBuiltinConstantArg(TheCall, i, Result))
672 return true;
673
674 // Range check against the upper/lower values for this instruction.
675 unsigned Val = Result.getZExtValue();
676 if (Val < l || Val > u)
677 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
678 << l << u << TheCall->getArg(i)->getSourceRange();
679
680 return false;
681}
682
Richard Smith831421f2012-06-25 20:30:08 +0000683/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
684/// parameter with the FormatAttr's correct format_idx and firstDataArg.
685/// Returns true when the format fits the function and the FormatStringInfo has
686/// been populated.
687bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
688 FormatStringInfo *FSI) {
689 FSI->HasVAListArg = Format->getFirstArg() == 0;
690 FSI->FormatIdx = Format->getFormatIdx() - 1;
691 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssond406bf02009-08-16 01:56:34 +0000692
Richard Smith831421f2012-06-25 20:30:08 +0000693 // The way the format attribute works in GCC, the implicit this argument
694 // of member functions is counted. However, it doesn't appear in our own
695 // lists, so decrement format_idx in that case.
696 if (IsCXXMember) {
697 if(FSI->FormatIdx == 0)
698 return false;
699 --FSI->FormatIdx;
700 if (FSI->FirstDataArg != 0)
701 --FSI->FirstDataArg;
702 }
703 return true;
704}
Mike Stump1eb44332009-09-09 15:08:12 +0000705
Richard Smith831421f2012-06-25 20:30:08 +0000706/// Handles the checks for format strings, non-POD arguments to vararg
707/// functions, and NULL arguments passed to non-NULL parameters.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000708void Sema::checkCall(NamedDecl *FDecl,
709 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000710 unsigned NumProtoArgs,
711 bool IsMemberFunction,
712 SourceLocation Loc,
713 SourceRange Range,
714 VariadicCallType CallType) {
Richard Smith0e218972013-08-05 18:49:43 +0000715 // FIXME: We should check as much as we can in the template definition.
Jordan Rose66360e22012-10-02 01:49:54 +0000716 if (CurContext->isDependentContext())
717 return;
Daniel Dunbarde454282008-10-02 18:44:07 +0000718
Ted Kremenekc82faca2010-09-09 04:33:05 +0000719 // Printf and scanf checking.
Richard Smith0e218972013-08-05 18:49:43 +0000720 llvm::SmallBitVector CheckedVarArgs;
721 if (FDecl) {
Richard Trieu0538f0e2013-06-22 00:20:41 +0000722 for (specific_attr_iterator<FormatAttr>
Benjamin Kramer47abb252013-08-08 11:08:26 +0000723 I = FDecl->specific_attr_begin<FormatAttr>(),
724 E = FDecl->specific_attr_end<FormatAttr>();
Benjamin Kramer541a28f2013-08-09 09:39:17 +0000725 I != E; ++I) {
726 // Only create vector if there are format attributes.
727 CheckedVarArgs.resize(Args.size());
728
Benjamin Kramer47abb252013-08-08 11:08:26 +0000729 CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc, Range,
730 CheckedVarArgs);
Benjamin Kramer541a28f2013-08-09 09:39:17 +0000731 }
Richard Smith0e218972013-08-05 18:49:43 +0000732 }
Richard Smith831421f2012-06-25 20:30:08 +0000733
734 // Refuse POD arguments that weren't caught by the format string
735 // checks above.
Richard Smith0e218972013-08-05 18:49:43 +0000736 if (CallType != VariadicDoesNotApply) {
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000737 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000738 // Args[ArgIdx] can be null in malformed code.
Richard Smith0e218972013-08-05 18:49:43 +0000739 if (const Expr *Arg = Args[ArgIdx]) {
740 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
741 checkVariadicArgument(Arg, CallType);
742 }
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000743 }
Richard Smith0e218972013-08-05 18:49:43 +0000744 }
Mike Stump1eb44332009-09-09 15:08:12 +0000745
Richard Trieu0538f0e2013-06-22 00:20:41 +0000746 if (FDecl) {
747 for (specific_attr_iterator<NonNullAttr>
748 I = FDecl->specific_attr_begin<NonNullAttr>(),
749 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
750 CheckNonNullArguments(*I, Args.data(), Loc);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000751
Richard Trieu0538f0e2013-06-22 00:20:41 +0000752 // Type safety checking.
753 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
754 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
755 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>();
756 i != e; ++i) {
757 CheckArgumentWithTypeTag(*i, Args.data());
758 }
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000759 }
Richard Smith831421f2012-06-25 20:30:08 +0000760}
761
762/// CheckConstructorCall - Check a constructor call for correctness and safety
763/// properties not enforced by the C type system.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000764void Sema::CheckConstructorCall(FunctionDecl *FDecl,
765 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000766 const FunctionProtoType *Proto,
767 SourceLocation Loc) {
768 VariadicCallType CallType =
769 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000770 checkCall(FDecl, Args, Proto->getNumArgs(),
Richard Smith831421f2012-06-25 20:30:08 +0000771 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
772}
773
774/// CheckFunctionCall - Check a direct function call for various correctness
775/// and safety properties not strictly enforced by the C type system.
776bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
777 const FunctionProtoType *Proto) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000778 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
779 isa<CXXMethodDecl>(FDecl);
780 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
781 IsMemberOperatorCall;
Richard Smith831421f2012-06-25 20:30:08 +0000782 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
783 TheCall->getCallee());
784 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Eli Friedman2edcde82012-10-11 00:30:58 +0000785 Expr** Args = TheCall->getArgs();
786 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmandf75b0c2012-10-11 00:34:15 +0000787 if (IsMemberOperatorCall) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000788 // If this is a call to a member operator, hide the first argument
789 // from checkCall.
790 // FIXME: Our choice of AST representation here is less than ideal.
791 ++Args;
792 --NumArgs;
793 }
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000794 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs),
795 NumProtoArgs,
Richard Smith831421f2012-06-25 20:30:08 +0000796 IsMemberFunction, TheCall->getRParenLoc(),
797 TheCall->getCallee()->getSourceRange(), CallType);
798
799 IdentifierInfo *FnInfo = FDecl->getIdentifier();
800 // None of the checks below are needed for functions that don't have
801 // simple names (e.g., C++ conversion functions).
802 if (!FnInfo)
803 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +0000804
Anna Zaks0a151a12012-01-17 00:37:07 +0000805 unsigned CMId = FDecl->getMemoryFunctionKind();
806 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000807 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000808
Anna Zaksd9b859a2012-01-13 21:52:01 +0000809 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000810 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000811 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000812 else if (CMId == Builtin::BIstrncat)
813 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000814 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000815 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000816
Anders Carlssond406bf02009-08-16 01:56:34 +0000817 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000818}
819
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000820bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000821 ArrayRef<const Expr *> Args) {
Richard Smith831421f2012-06-25 20:30:08 +0000822 VariadicCallType CallType =
823 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000824
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000825 checkCall(Method, Args, Method->param_size(),
Richard Smith831421f2012-06-25 20:30:08 +0000826 /*IsMemberFunction=*/false,
827 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000828
829 return false;
830}
831
Richard Trieuf462b012013-06-20 21:03:13 +0000832bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
833 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000834 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
835 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000836 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000837
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000838 QualType Ty = V->getType();
Richard Trieuf462b012013-06-20 21:03:13 +0000839 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000840 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000841
Richard Trieuf462b012013-06-20 21:03:13 +0000842 VariadicCallType CallType;
Richard Trieua4993772013-06-20 23:21:54 +0000843 if (!Proto || !Proto->isVariadic()) {
Richard Trieuf462b012013-06-20 21:03:13 +0000844 CallType = VariadicDoesNotApply;
845 } else if (Ty->isBlockPointerType()) {
846 CallType = VariadicBlock;
847 } else { // Ty->isFunctionPointerType()
848 CallType = VariadicFunction;
849 }
Richard Smith831421f2012-06-25 20:30:08 +0000850 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000851
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000852 checkCall(NDecl,
853 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
854 TheCall->getNumArgs()),
Richard Smith831421f2012-06-25 20:30:08 +0000855 NumProtoArgs, /*IsMemberFunction=*/false,
856 TheCall->getRParenLoc(),
857 TheCall->getCallee()->getSourceRange(), CallType);
858
Anders Carlssond406bf02009-08-16 01:56:34 +0000859 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000860}
861
Richard Trieu0538f0e2013-06-22 00:20:41 +0000862/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
863/// such as function pointers returned from functions.
864bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
865 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
866 TheCall->getCallee());
867 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
868
869 checkCall(/*FDecl=*/0,
870 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
871 TheCall->getNumArgs()),
872 NumProtoArgs, /*IsMemberFunction=*/false,
873 TheCall->getRParenLoc(),
874 TheCall->getCallee()->getSourceRange(), CallType);
875
876 return false;
877}
878
Richard Smithff34d402012-04-12 05:08:17 +0000879ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
880 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000881 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
882 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000883
Richard Smithff34d402012-04-12 05:08:17 +0000884 // All these operations take one of the following forms:
885 enum {
886 // C __c11_atomic_init(A *, C)
887 Init,
888 // C __c11_atomic_load(A *, int)
889 Load,
890 // void __atomic_load(A *, CP, int)
891 Copy,
892 // C __c11_atomic_add(A *, M, int)
893 Arithmetic,
894 // C __atomic_exchange_n(A *, CP, int)
895 Xchg,
896 // void __atomic_exchange(A *, C *, CP, int)
897 GNUXchg,
898 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
899 C11CmpXchg,
900 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
901 GNUCmpXchg
902 } Form = Init;
903 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
904 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
905 // where:
906 // C is an appropriate type,
907 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
908 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
909 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
910 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000911
Richard Smithff34d402012-04-12 05:08:17 +0000912 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
913 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
914 && "need to update code for modified C11 atomics");
915 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
916 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
917 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
918 Op == AtomicExpr::AO__atomic_store_n ||
919 Op == AtomicExpr::AO__atomic_exchange_n ||
920 Op == AtomicExpr::AO__atomic_compare_exchange_n;
921 bool IsAddSub = false;
922
923 switch (Op) {
924 case AtomicExpr::AO__c11_atomic_init:
925 Form = Init;
926 break;
927
928 case AtomicExpr::AO__c11_atomic_load:
929 case AtomicExpr::AO__atomic_load_n:
930 Form = Load;
931 break;
932
933 case AtomicExpr::AO__c11_atomic_store:
934 case AtomicExpr::AO__atomic_load:
935 case AtomicExpr::AO__atomic_store:
936 case AtomicExpr::AO__atomic_store_n:
937 Form = Copy;
938 break;
939
940 case AtomicExpr::AO__c11_atomic_fetch_add:
941 case AtomicExpr::AO__c11_atomic_fetch_sub:
942 case AtomicExpr::AO__atomic_fetch_add:
943 case AtomicExpr::AO__atomic_fetch_sub:
944 case AtomicExpr::AO__atomic_add_fetch:
945 case AtomicExpr::AO__atomic_sub_fetch:
946 IsAddSub = true;
947 // Fall through.
948 case AtomicExpr::AO__c11_atomic_fetch_and:
949 case AtomicExpr::AO__c11_atomic_fetch_or:
950 case AtomicExpr::AO__c11_atomic_fetch_xor:
951 case AtomicExpr::AO__atomic_fetch_and:
952 case AtomicExpr::AO__atomic_fetch_or:
953 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000954 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000955 case AtomicExpr::AO__atomic_and_fetch:
956 case AtomicExpr::AO__atomic_or_fetch:
957 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000958 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000959 Form = Arithmetic;
960 break;
961
962 case AtomicExpr::AO__c11_atomic_exchange:
963 case AtomicExpr::AO__atomic_exchange_n:
964 Form = Xchg;
965 break;
966
967 case AtomicExpr::AO__atomic_exchange:
968 Form = GNUXchg;
969 break;
970
971 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
972 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
973 Form = C11CmpXchg;
974 break;
975
976 case AtomicExpr::AO__atomic_compare_exchange:
977 case AtomicExpr::AO__atomic_compare_exchange_n:
978 Form = GNUCmpXchg;
979 break;
980 }
981
982 // Check we have the right number of arguments.
983 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000984 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000985 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000986 << TheCall->getCallee()->getSourceRange();
987 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000988 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
989 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000990 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000991 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000992 << TheCall->getCallee()->getSourceRange();
993 return ExprError();
994 }
995
Richard Smithff34d402012-04-12 05:08:17 +0000996 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000997 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000998 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
999 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1000 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +00001001 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +00001002 << Ptr->getType() << Ptr->getSourceRange();
1003 return ExprError();
1004 }
1005
Richard Smithff34d402012-04-12 05:08:17 +00001006 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1007 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1008 QualType ValType = AtomTy; // 'C'
1009 if (IsC11) {
1010 if (!AtomTy->isAtomicType()) {
1011 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1012 << Ptr->getType() << Ptr->getSourceRange();
1013 return ExprError();
1014 }
Richard Smithbc57b102012-09-15 06:09:58 +00001015 if (AtomTy.isConstQualified()) {
1016 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1017 << Ptr->getType() << Ptr->getSourceRange();
1018 return ExprError();
1019 }
Richard Smithff34d402012-04-12 05:08:17 +00001020 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +00001021 }
Eli Friedman276b0612011-10-11 02:20:01 +00001022
Richard Smithff34d402012-04-12 05:08:17 +00001023 // For an arithmetic operation, the implied arithmetic must be well-formed.
1024 if (Form == Arithmetic) {
1025 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1026 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1027 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1028 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1029 return ExprError();
1030 }
1031 if (!IsAddSub && !ValType->isIntegerType()) {
1032 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1033 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1034 return ExprError();
1035 }
1036 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1037 // For __atomic_*_n operations, the value type must be a scalar integral or
1038 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +00001039 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +00001040 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1041 return ExprError();
1042 }
1043
Eli Friedmana3d727b2013-09-11 03:49:34 +00001044 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1045 !AtomTy->isScalarType()) {
Richard Smithff34d402012-04-12 05:08:17 +00001046 // For GNU atomics, require a trivially-copyable type. This is not part of
1047 // the GNU atomics specification, but we enforce it for sanity.
1048 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +00001049 << Ptr->getType() << Ptr->getSourceRange();
1050 return ExprError();
1051 }
1052
Richard Smithff34d402012-04-12 05:08:17 +00001053 // FIXME: For any builtin other than a load, the ValType must not be
1054 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +00001055
1056 switch (ValType.getObjCLifetime()) {
1057 case Qualifiers::OCL_None:
1058 case Qualifiers::OCL_ExplicitNone:
1059 // okay
1060 break;
1061
1062 case Qualifiers::OCL_Weak:
1063 case Qualifiers::OCL_Strong:
1064 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +00001065 // FIXME: Can this happen? By this point, ValType should be known
1066 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +00001067 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1068 << ValType << Ptr->getSourceRange();
1069 return ExprError();
1070 }
1071
1072 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +00001073 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +00001074 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +00001075 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +00001076 ResultType = Context.BoolTy;
1077
Richard Smithff34d402012-04-12 05:08:17 +00001078 // The type of a parameter passed 'by value'. In the GNU atomics, such
1079 // arguments are actually passed as pointers.
1080 QualType ByValType = ValType; // 'CP'
1081 if (!IsC11 && !IsN)
1082 ByValType = Ptr->getType();
1083
Eli Friedman276b0612011-10-11 02:20:01 +00001084 // The first argument --- the pointer --- has a fixed type; we
1085 // deduce the types of the rest of the arguments accordingly. Walk
1086 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +00001087 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +00001088 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +00001089 if (i < NumVals[Form] + 1) {
1090 switch (i) {
1091 case 1:
1092 // The second argument is the non-atomic operand. For arithmetic, this
1093 // is always passed by value, and for a compare_exchange it is always
1094 // passed by address. For the rest, GNU uses by-address and C11 uses
1095 // by-value.
1096 assert(Form != Load);
1097 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1098 Ty = ValType;
1099 else if (Form == Copy || Form == Xchg)
1100 Ty = ByValType;
1101 else if (Form == Arithmetic)
1102 Ty = Context.getPointerDiffType();
1103 else
1104 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1105 break;
1106 case 2:
1107 // The third argument to compare_exchange / GNU exchange is a
1108 // (pointer to a) desired value.
1109 Ty = ByValType;
1110 break;
1111 case 3:
1112 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1113 Ty = Context.BoolTy;
1114 break;
1115 }
Eli Friedman276b0612011-10-11 02:20:01 +00001116 } else {
1117 // The order(s) are always converted to int.
1118 Ty = Context.IntTy;
1119 }
Richard Smithff34d402012-04-12 05:08:17 +00001120
Eli Friedman276b0612011-10-11 02:20:01 +00001121 InitializedEntity Entity =
1122 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +00001123 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +00001124 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1125 if (Arg.isInvalid())
1126 return true;
1127 TheCall->setArg(i, Arg.get());
1128 }
1129
Richard Smithff34d402012-04-12 05:08:17 +00001130 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001131 SmallVector<Expr*, 5> SubExprs;
1132 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +00001133 switch (Form) {
1134 case Init:
1135 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +00001136 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001137 break;
1138 case Load:
1139 SubExprs.push_back(TheCall->getArg(1)); // Order
1140 break;
1141 case Copy:
1142 case Arithmetic:
1143 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001144 SubExprs.push_back(TheCall->getArg(2)); // Order
1145 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001146 break;
1147 case GNUXchg:
1148 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1149 SubExprs.push_back(TheCall->getArg(3)); // Order
1150 SubExprs.push_back(TheCall->getArg(1)); // Val1
1151 SubExprs.push_back(TheCall->getArg(2)); // Val2
1152 break;
1153 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001154 SubExprs.push_back(TheCall->getArg(3)); // Order
1155 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001156 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +00001157 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +00001158 break;
1159 case GNUCmpXchg:
1160 SubExprs.push_back(TheCall->getArg(4)); // Order
1161 SubExprs.push_back(TheCall->getArg(1)); // Val1
1162 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1163 SubExprs.push_back(TheCall->getArg(2)); // Val2
1164 SubExprs.push_back(TheCall->getArg(3)); // Weak
1165 break;
Eli Friedman276b0612011-10-11 02:20:01 +00001166 }
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00001167
1168 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1169 SubExprs, ResultType, Op,
1170 TheCall->getRParenLoc());
1171
1172 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1173 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1174 Context.AtomicUsesUnsupportedLibcall(AE))
1175 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1176 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001177
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00001178 return Owned(AE);
Eli Friedman276b0612011-10-11 02:20:01 +00001179}
1180
1181
John McCall5f8d6042011-08-27 01:09:30 +00001182/// checkBuiltinArgument - Given a call to a builtin function, perform
1183/// normal type-checking on the given argument, updating the call in
1184/// place. This is useful when a builtin function requires custom
1185/// type-checking for some of its arguments but not necessarily all of
1186/// them.
1187///
1188/// Returns true on error.
1189static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1190 FunctionDecl *Fn = E->getDirectCallee();
1191 assert(Fn && "builtin call without direct callee!");
1192
1193 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1194 InitializedEntity Entity =
1195 InitializedEntity::InitializeParameter(S.Context, Param);
1196
1197 ExprResult Arg = E->getArg(0);
1198 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1199 if (Arg.isInvalid())
1200 return true;
1201
1202 E->setArg(ArgIndex, Arg.take());
1203 return false;
1204}
1205
Chris Lattner5caa3702009-05-08 06:58:22 +00001206/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1207/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1208/// type of its first argument. The main ActOnCallExpr routines have already
1209/// promoted the types of arguments because all of these calls are prototyped as
1210/// void(...).
1211///
1212/// This function goes through and does final semantic checking for these
1213/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +00001214ExprResult
1215Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001216 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +00001217 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1218 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1219
1220 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +00001221 if (TheCall->getNumArgs() < 1) {
1222 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1223 << 0 << 1 << TheCall->getNumArgs()
1224 << TheCall->getCallee()->getSourceRange();
1225 return ExprError();
1226 }
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Chris Lattner5caa3702009-05-08 06:58:22 +00001228 // Inspect the first argument of the atomic builtin. This should always be
1229 // a pointer type, whose element is an integral scalar or pointer type.
1230 // Because it is a pointer type, we don't have to worry about any implicit
1231 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +00001232 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +00001233 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +00001234 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1235 if (FirstArgResult.isInvalid())
1236 return ExprError();
1237 FirstArg = FirstArgResult.take();
1238 TheCall->setArg(0, FirstArg);
1239
John McCallf85e1932011-06-15 23:02:42 +00001240 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1241 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001242 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1243 << FirstArg->getType() << FirstArg->getSourceRange();
1244 return ExprError();
1245 }
Mike Stump1eb44332009-09-09 15:08:12 +00001246
John McCallf85e1932011-06-15 23:02:42 +00001247 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +00001248 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +00001249 !ValType->isBlockPointerType()) {
1250 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1251 << FirstArg->getType() << FirstArg->getSourceRange();
1252 return ExprError();
1253 }
Chris Lattner5caa3702009-05-08 06:58:22 +00001254
John McCallf85e1932011-06-15 23:02:42 +00001255 switch (ValType.getObjCLifetime()) {
1256 case Qualifiers::OCL_None:
1257 case Qualifiers::OCL_ExplicitNone:
1258 // okay
1259 break;
1260
1261 case Qualifiers::OCL_Weak:
1262 case Qualifiers::OCL_Strong:
1263 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001264 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001265 << ValType << FirstArg->getSourceRange();
1266 return ExprError();
1267 }
1268
John McCallb45ae252011-10-05 07:41:44 +00001269 // Strip any qualifiers off ValType.
1270 ValType = ValType.getUnqualifiedType();
1271
Chandler Carruth8d13d222010-07-18 20:54:12 +00001272 // The majority of builtins return a value, but a few have special return
1273 // types, so allow them to override appropriately below.
1274 QualType ResultType = ValType;
1275
Chris Lattner5caa3702009-05-08 06:58:22 +00001276 // We need to figure out which concrete builtin this maps onto. For example,
1277 // __sync_fetch_and_add with a 2 byte object turns into
1278 // __sync_fetch_and_add_2.
1279#define BUILTIN_ROW(x) \
1280 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1281 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +00001282
Chris Lattner5caa3702009-05-08 06:58:22 +00001283 static const unsigned BuiltinIndices[][5] = {
1284 BUILTIN_ROW(__sync_fetch_and_add),
1285 BUILTIN_ROW(__sync_fetch_and_sub),
1286 BUILTIN_ROW(__sync_fetch_and_or),
1287 BUILTIN_ROW(__sync_fetch_and_and),
1288 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +00001289
Chris Lattner5caa3702009-05-08 06:58:22 +00001290 BUILTIN_ROW(__sync_add_and_fetch),
1291 BUILTIN_ROW(__sync_sub_and_fetch),
1292 BUILTIN_ROW(__sync_and_and_fetch),
1293 BUILTIN_ROW(__sync_or_and_fetch),
1294 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001295
Chris Lattner5caa3702009-05-08 06:58:22 +00001296 BUILTIN_ROW(__sync_val_compare_and_swap),
1297 BUILTIN_ROW(__sync_bool_compare_and_swap),
1298 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001299 BUILTIN_ROW(__sync_lock_release),
1300 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001301 };
Mike Stump1eb44332009-09-09 15:08:12 +00001302#undef BUILTIN_ROW
1303
Chris Lattner5caa3702009-05-08 06:58:22 +00001304 // Determine the index of the size.
1305 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001306 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001307 case 1: SizeIndex = 0; break;
1308 case 2: SizeIndex = 1; break;
1309 case 4: SizeIndex = 2; break;
1310 case 8: SizeIndex = 3; break;
1311 case 16: SizeIndex = 4; break;
1312 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001313 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1314 << FirstArg->getType() << FirstArg->getSourceRange();
1315 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001316 }
Mike Stump1eb44332009-09-09 15:08:12 +00001317
Chris Lattner5caa3702009-05-08 06:58:22 +00001318 // Each of these builtins has one pointer argument, followed by some number of
1319 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1320 // that we ignore. Find out which row of BuiltinIndices to read from as well
1321 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001322 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001323 unsigned BuiltinIndex, NumFixed = 1;
1324 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001325 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001326 case Builtin::BI__sync_fetch_and_add:
1327 case Builtin::BI__sync_fetch_and_add_1:
1328 case Builtin::BI__sync_fetch_and_add_2:
1329 case Builtin::BI__sync_fetch_and_add_4:
1330 case Builtin::BI__sync_fetch_and_add_8:
1331 case Builtin::BI__sync_fetch_and_add_16:
1332 BuiltinIndex = 0;
1333 break;
1334
1335 case Builtin::BI__sync_fetch_and_sub:
1336 case Builtin::BI__sync_fetch_and_sub_1:
1337 case Builtin::BI__sync_fetch_and_sub_2:
1338 case Builtin::BI__sync_fetch_and_sub_4:
1339 case Builtin::BI__sync_fetch_and_sub_8:
1340 case Builtin::BI__sync_fetch_and_sub_16:
1341 BuiltinIndex = 1;
1342 break;
1343
1344 case Builtin::BI__sync_fetch_and_or:
1345 case Builtin::BI__sync_fetch_and_or_1:
1346 case Builtin::BI__sync_fetch_and_or_2:
1347 case Builtin::BI__sync_fetch_and_or_4:
1348 case Builtin::BI__sync_fetch_and_or_8:
1349 case Builtin::BI__sync_fetch_and_or_16:
1350 BuiltinIndex = 2;
1351 break;
1352
1353 case Builtin::BI__sync_fetch_and_and:
1354 case Builtin::BI__sync_fetch_and_and_1:
1355 case Builtin::BI__sync_fetch_and_and_2:
1356 case Builtin::BI__sync_fetch_and_and_4:
1357 case Builtin::BI__sync_fetch_and_and_8:
1358 case Builtin::BI__sync_fetch_and_and_16:
1359 BuiltinIndex = 3;
1360 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001361
Douglas Gregora9766412011-11-28 16:30:08 +00001362 case Builtin::BI__sync_fetch_and_xor:
1363 case Builtin::BI__sync_fetch_and_xor_1:
1364 case Builtin::BI__sync_fetch_and_xor_2:
1365 case Builtin::BI__sync_fetch_and_xor_4:
1366 case Builtin::BI__sync_fetch_and_xor_8:
1367 case Builtin::BI__sync_fetch_and_xor_16:
1368 BuiltinIndex = 4;
1369 break;
1370
1371 case Builtin::BI__sync_add_and_fetch:
1372 case Builtin::BI__sync_add_and_fetch_1:
1373 case Builtin::BI__sync_add_and_fetch_2:
1374 case Builtin::BI__sync_add_and_fetch_4:
1375 case Builtin::BI__sync_add_and_fetch_8:
1376 case Builtin::BI__sync_add_and_fetch_16:
1377 BuiltinIndex = 5;
1378 break;
1379
1380 case Builtin::BI__sync_sub_and_fetch:
1381 case Builtin::BI__sync_sub_and_fetch_1:
1382 case Builtin::BI__sync_sub_and_fetch_2:
1383 case Builtin::BI__sync_sub_and_fetch_4:
1384 case Builtin::BI__sync_sub_and_fetch_8:
1385 case Builtin::BI__sync_sub_and_fetch_16:
1386 BuiltinIndex = 6;
1387 break;
1388
1389 case Builtin::BI__sync_and_and_fetch:
1390 case Builtin::BI__sync_and_and_fetch_1:
1391 case Builtin::BI__sync_and_and_fetch_2:
1392 case Builtin::BI__sync_and_and_fetch_4:
1393 case Builtin::BI__sync_and_and_fetch_8:
1394 case Builtin::BI__sync_and_and_fetch_16:
1395 BuiltinIndex = 7;
1396 break;
1397
1398 case Builtin::BI__sync_or_and_fetch:
1399 case Builtin::BI__sync_or_and_fetch_1:
1400 case Builtin::BI__sync_or_and_fetch_2:
1401 case Builtin::BI__sync_or_and_fetch_4:
1402 case Builtin::BI__sync_or_and_fetch_8:
1403 case Builtin::BI__sync_or_and_fetch_16:
1404 BuiltinIndex = 8;
1405 break;
1406
1407 case Builtin::BI__sync_xor_and_fetch:
1408 case Builtin::BI__sync_xor_and_fetch_1:
1409 case Builtin::BI__sync_xor_and_fetch_2:
1410 case Builtin::BI__sync_xor_and_fetch_4:
1411 case Builtin::BI__sync_xor_and_fetch_8:
1412 case Builtin::BI__sync_xor_and_fetch_16:
1413 BuiltinIndex = 9;
1414 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001415
Chris Lattner5caa3702009-05-08 06:58:22 +00001416 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001417 case Builtin::BI__sync_val_compare_and_swap_1:
1418 case Builtin::BI__sync_val_compare_and_swap_2:
1419 case Builtin::BI__sync_val_compare_and_swap_4:
1420 case Builtin::BI__sync_val_compare_and_swap_8:
1421 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001422 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001423 NumFixed = 2;
1424 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001425
Chris Lattner5caa3702009-05-08 06:58:22 +00001426 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001427 case Builtin::BI__sync_bool_compare_and_swap_1:
1428 case Builtin::BI__sync_bool_compare_and_swap_2:
1429 case Builtin::BI__sync_bool_compare_and_swap_4:
1430 case Builtin::BI__sync_bool_compare_and_swap_8:
1431 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001432 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001433 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001434 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001435 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001436
1437 case Builtin::BI__sync_lock_test_and_set:
1438 case Builtin::BI__sync_lock_test_and_set_1:
1439 case Builtin::BI__sync_lock_test_and_set_2:
1440 case Builtin::BI__sync_lock_test_and_set_4:
1441 case Builtin::BI__sync_lock_test_and_set_8:
1442 case Builtin::BI__sync_lock_test_and_set_16:
1443 BuiltinIndex = 12;
1444 break;
1445
Chris Lattner5caa3702009-05-08 06:58:22 +00001446 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001447 case Builtin::BI__sync_lock_release_1:
1448 case Builtin::BI__sync_lock_release_2:
1449 case Builtin::BI__sync_lock_release_4:
1450 case Builtin::BI__sync_lock_release_8:
1451 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001452 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001453 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001454 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001455 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001456
1457 case Builtin::BI__sync_swap:
1458 case Builtin::BI__sync_swap_1:
1459 case Builtin::BI__sync_swap_2:
1460 case Builtin::BI__sync_swap_4:
1461 case Builtin::BI__sync_swap_8:
1462 case Builtin::BI__sync_swap_16:
1463 BuiltinIndex = 14;
1464 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001465 }
Mike Stump1eb44332009-09-09 15:08:12 +00001466
Chris Lattner5caa3702009-05-08 06:58:22 +00001467 // Now that we know how many fixed arguments we expect, first check that we
1468 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001469 if (TheCall->getNumArgs() < 1+NumFixed) {
1470 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1471 << 0 << 1+NumFixed << TheCall->getNumArgs()
1472 << TheCall->getCallee()->getSourceRange();
1473 return ExprError();
1474 }
Mike Stump1eb44332009-09-09 15:08:12 +00001475
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001476 // Get the decl for the concrete builtin from this, we can tell what the
1477 // concrete integer type we should convert to is.
1478 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1479 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001480 FunctionDecl *NewBuiltinDecl;
1481 if (NewBuiltinID == BuiltinID)
1482 NewBuiltinDecl = FDecl;
1483 else {
1484 // Perform builtin lookup to avoid redeclaring it.
1485 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1486 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1487 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1488 assert(Res.getFoundDecl());
1489 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1490 if (NewBuiltinDecl == 0)
1491 return ExprError();
1492 }
Chandler Carruthd2014572010-07-09 18:59:35 +00001493
John McCallf871d0c2010-08-07 06:22:56 +00001494 // The first argument --- the pointer --- has a fixed type; we
1495 // deduce the types of the rest of the arguments accordingly. Walk
1496 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001497 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001498 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001499
Chris Lattner5caa3702009-05-08 06:58:22 +00001500 // GCC does an implicit conversion to the pointer or integer ValType. This
1501 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001502 // Initialize the argument.
1503 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1504 ValType, /*consume*/ false);
1505 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001506 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001507 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001508
Chris Lattner5caa3702009-05-08 06:58:22 +00001509 // Okay, we have something that *can* be converted to the right type. Check
1510 // to see if there is a potentially weird extension going on here. This can
1511 // happen when you do an atomic operation on something like an char* and
1512 // pass in 42. The 42 gets converted to char. This is even more strange
1513 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001514 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001515 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001516 }
Mike Stump1eb44332009-09-09 15:08:12 +00001517
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001518 ASTContext& Context = this->getASTContext();
1519
1520 // Create a new DeclRefExpr to refer to the new decl.
1521 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1522 Context,
1523 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001524 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001525 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001526 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001527 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001528 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001529 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001530
Chris Lattner5caa3702009-05-08 06:58:22 +00001531 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001532 // FIXME: This loses syntactic information.
1533 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1534 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1535 CK_BuiltinFnToFnPtr);
John Wiegley429bb272011-04-08 18:41:53 +00001536 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001537
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001538 // Change the result type of the call to match the original value type. This
1539 // is arbitrary, but the codegen for these builtins ins design to handle it
1540 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001541 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001542
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001543 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001544}
1545
Chris Lattner69039812009-02-18 06:01:06 +00001546/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001547/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001548/// Note: It might also make sense to do the UTF-16 conversion here (would
1549/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001550bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001551 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001552 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1553
Douglas Gregor5cee1192011-07-27 05:40:30 +00001554 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001555 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1556 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001557 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001558 }
Mike Stump1eb44332009-09-09 15:08:12 +00001559
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001560 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001561 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001562 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001563 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00001564 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001565 UTF16 *ToPtr = &ToBuf[0];
1566
1567 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1568 &ToPtr, ToPtr + NumBytes,
1569 strictConversion);
1570 // Check for conversion failure.
1571 if (Result != conversionOK)
1572 Diag(Arg->getLocStart(),
1573 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1574 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001575 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001576}
1577
Chris Lattnerc27c6652007-12-20 00:05:45 +00001578/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1579/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001580bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1581 Expr *Fn = TheCall->getCallee();
1582 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001583 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001584 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001585 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1586 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001587 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001588 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001589 return true;
1590 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001591
1592 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001593 return Diag(TheCall->getLocEnd(),
1594 diag::err_typecheck_call_too_few_args_at_least)
1595 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001596 }
1597
John McCall5f8d6042011-08-27 01:09:30 +00001598 // Type-check the first argument normally.
1599 if (checkBuiltinArgument(*this, TheCall, 0))
1600 return true;
1601
Chris Lattnerc27c6652007-12-20 00:05:45 +00001602 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001603 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001604 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001605 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001606 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001607 else if (FunctionDecl *FD = getCurFunctionDecl())
1608 isVariadic = FD->isVariadic();
1609 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001610 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001611
Chris Lattnerc27c6652007-12-20 00:05:45 +00001612 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001613 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1614 return true;
1615 }
Mike Stump1eb44332009-09-09 15:08:12 +00001616
Chris Lattner30ce3442007-12-19 23:59:04 +00001617 // Verify that the second argument to the builtin is the last argument of the
1618 // current function or method.
1619 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001620 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Nico Weberb07d4482013-05-24 23:31:57 +00001622 // These are valid if SecondArgIsLastNamedArgument is false after the next
1623 // block.
1624 QualType Type;
1625 SourceLocation ParamLoc;
1626
Anders Carlsson88cf2262008-02-11 04:20:54 +00001627 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1628 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001629 // FIXME: This isn't correct for methods (results in bogus warning).
1630 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001631 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001632 if (CurBlock)
1633 LastArg = *(CurBlock->TheDecl->param_end()-1);
1634 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001635 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001636 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001637 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001638 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weberb07d4482013-05-24 23:31:57 +00001639
1640 Type = PV->getType();
1641 ParamLoc = PV->getLocation();
Chris Lattner30ce3442007-12-19 23:59:04 +00001642 }
1643 }
Mike Stump1eb44332009-09-09 15:08:12 +00001644
Chris Lattner30ce3442007-12-19 23:59:04 +00001645 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001646 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001647 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weberb07d4482013-05-24 23:31:57 +00001648 else if (Type->isReferenceType()) {
1649 Diag(Arg->getLocStart(),
1650 diag::warn_va_start_of_reference_type_is_undefined);
1651 Diag(ParamLoc, diag::note_parameter_type) << Type;
1652 }
1653
Chris Lattner30ce3442007-12-19 23:59:04 +00001654 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001655}
Chris Lattner30ce3442007-12-19 23:59:04 +00001656
Chris Lattner1b9a0792007-12-20 00:26:33 +00001657/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1658/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001659bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1660 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001661 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001662 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001663 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001664 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001665 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001666 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001667 << SourceRange(TheCall->getArg(2)->getLocStart(),
1668 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001669
John Wiegley429bb272011-04-08 18:41:53 +00001670 ExprResult OrigArg0 = TheCall->getArg(0);
1671 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001672
Chris Lattner1b9a0792007-12-20 00:26:33 +00001673 // Do standard promotions between the two arguments, returning their common
1674 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001675 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001676 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1677 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001678
1679 // Make sure any conversions are pushed back into the call; this is
1680 // type safe since unordered compare builtins are declared as "_Bool
1681 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001682 TheCall->setArg(0, OrigArg0.get());
1683 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001684
John Wiegley429bb272011-04-08 18:41:53 +00001685 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001686 return false;
1687
Chris Lattner1b9a0792007-12-20 00:26:33 +00001688 // If the common type isn't a real floating type, then the arguments were
1689 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001690 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001691 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001692 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001693 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1694 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001695
Chris Lattner1b9a0792007-12-20 00:26:33 +00001696 return false;
1697}
1698
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001699/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1700/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001701/// to check everything. We expect the last argument to be a floating point
1702/// value.
1703bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1704 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001705 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001706 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001707 if (TheCall->getNumArgs() > NumArgs)
1708 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001709 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001710 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001711 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001712 (*(TheCall->arg_end()-1))->getLocEnd());
1713
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001714 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001715
Eli Friedman9ac6f622009-08-31 20:06:00 +00001716 if (OrigArg->isTypeDependent())
1717 return false;
1718
Chris Lattner81368fb2010-05-06 05:50:07 +00001719 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001720 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001721 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001722 diag::err_typecheck_call_invalid_unary_fp)
1723 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001724
Chris Lattner81368fb2010-05-06 05:50:07 +00001725 // If this is an implicit conversion from float -> double, remove it.
1726 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1727 Expr *CastArg = Cast->getSubExpr();
1728 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1729 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1730 "promotion from float to double is the only expected cast here");
1731 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001732 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001733 }
1734 }
1735
Eli Friedman9ac6f622009-08-31 20:06:00 +00001736 return false;
1737}
1738
Eli Friedmand38617c2008-05-14 19:38:39 +00001739/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1740// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001741ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001742 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001743 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001744 diag::err_typecheck_call_too_few_args_at_least)
Craig Topperb44545a2013-07-28 21:50:10 +00001745 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1746 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001747
Nate Begeman37b6a572010-06-08 00:16:34 +00001748 // Determine which of the following types of shufflevector we're checking:
1749 // 1) unary, vector mask: (lhs, mask)
1750 // 2) binary, vector mask: (lhs, rhs, mask)
1751 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1752 QualType resType = TheCall->getArg(0)->getType();
1753 unsigned numElements = 0;
Craig Toppere3fbbe92013-07-19 04:46:31 +00001754
Douglas Gregorcde01732009-05-19 22:10:17 +00001755 if (!TheCall->getArg(0)->isTypeDependent() &&
1756 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001757 QualType LHSType = TheCall->getArg(0)->getType();
1758 QualType RHSType = TheCall->getArg(1)->getType();
Craig Toppere3fbbe92013-07-19 04:46:31 +00001759
Craig Topperbbe759c2013-07-29 06:47:04 +00001760 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1761 return ExprError(Diag(TheCall->getLocStart(),
1762 diag::err_shufflevector_non_vector)
1763 << SourceRange(TheCall->getArg(0)->getLocStart(),
1764 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00001765
Nate Begeman37b6a572010-06-08 00:16:34 +00001766 numElements = LHSType->getAs<VectorType>()->getNumElements();
1767 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001768
Nate Begeman37b6a572010-06-08 00:16:34 +00001769 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1770 // with mask. If so, verify that RHS is an integer vector type with the
1771 // same number of elts as lhs.
1772 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru4cb3d902013-07-06 08:00:09 +00001773 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001774 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbbe759c2013-07-29 06:47:04 +00001775 return ExprError(Diag(TheCall->getLocStart(),
1776 diag::err_shufflevector_incompatible_vector)
1777 << SourceRange(TheCall->getArg(1)->getLocStart(),
1778 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00001779 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbbe759c2013-07-29 06:47:04 +00001780 return ExprError(Diag(TheCall->getLocStart(),
1781 diag::err_shufflevector_incompatible_vector)
1782 << SourceRange(TheCall->getArg(0)->getLocStart(),
1783 TheCall->getArg(1)->getLocEnd()));
Nate Begeman37b6a572010-06-08 00:16:34 +00001784 } else if (numElements != numResElements) {
1785 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001786 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001787 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001788 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001789 }
1790
1791 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001792 if (TheCall->getArg(i)->isTypeDependent() ||
1793 TheCall->getArg(i)->isValueDependent())
1794 continue;
1795
Nate Begeman37b6a572010-06-08 00:16:34 +00001796 llvm::APSInt Result(32);
1797 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1798 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00001799 diag::err_shufflevector_nonconstant_argument)
1800 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001801
Craig Topper6f4f8082013-08-03 17:40:38 +00001802 // Allow -1 which will be translated to undef in the IR.
1803 if (Result.isSigned() && Result.isAllOnesValue())
1804 continue;
1805
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001806 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001807 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00001808 diag::err_shufflevector_argument_too_large)
1809 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001810 }
1811
Chris Lattner5f9e2722011-07-23 10:55:15 +00001812 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001813
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001814 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001815 exprs.push_back(TheCall->getArg(i));
1816 TheCall->setArg(i, 0);
1817 }
1818
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001819 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001820 TheCall->getCallee()->getLocStart(),
1821 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001822}
Chris Lattner30ce3442007-12-19 23:59:04 +00001823
Hal Finkel414a1bd2013-09-18 03:29:45 +00001824/// SemaConvertVectorExpr - Handle __builtin_convertvector
1825ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1826 SourceLocation BuiltinLoc,
1827 SourceLocation RParenLoc) {
1828 ExprValueKind VK = VK_RValue;
1829 ExprObjectKind OK = OK_Ordinary;
1830 QualType DstTy = TInfo->getType();
1831 QualType SrcTy = E->getType();
1832
1833 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1834 return ExprError(Diag(BuiltinLoc,
1835 diag::err_convertvector_non_vector)
1836 << E->getSourceRange());
1837 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1838 return ExprError(Diag(BuiltinLoc,
1839 diag::err_convertvector_non_vector_type));
1840
1841 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1842 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1843 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1844 if (SrcElts != DstElts)
1845 return ExprError(Diag(BuiltinLoc,
1846 diag::err_convertvector_incompatible_vector)
1847 << E->getSourceRange());
1848 }
1849
1850 return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
1851 BuiltinLoc, RParenLoc));
1852
1853}
1854
Daniel Dunbar4493f792008-07-21 22:59:13 +00001855/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1856// This is declared to take (const void*, ...) and can take two
1857// optional constant int args.
1858bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001859 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001860
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001861 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001862 return Diag(TheCall->getLocEnd(),
1863 diag::err_typecheck_call_too_many_args_at_most)
1864 << 0 /*function call*/ << 3 << NumArgs
1865 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001866
1867 // Argument 0 is checked for us and the remaining arguments must be
1868 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001869 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001870 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001871
1872 // We can't check the value of a dependent argument.
1873 if (Arg->isTypeDependent() || Arg->isValueDependent())
1874 continue;
1875
Eli Friedman9aef7262009-12-04 00:30:06 +00001876 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001877 if (SemaBuiltinConstantArg(TheCall, i, Result))
1878 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001879
Daniel Dunbar4493f792008-07-21 22:59:13 +00001880 // FIXME: gcc issues a warning and rewrites these to 0. These
1881 // seems especially odd for the third argument since the default
1882 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001883 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001884 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001885 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001886 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001887 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001888 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001889 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001890 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001891 }
1892 }
1893
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001894 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001895}
1896
Eric Christopher691ebc32010-04-17 02:26:23 +00001897/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1898/// TheCall is a constant expression.
1899bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1900 llvm::APSInt &Result) {
1901 Expr *Arg = TheCall->getArg(ArgNum);
1902 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1903 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1904
1905 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1906
1907 if (!Arg->isIntegerConstantExpr(Result, Context))
1908 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001909 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001910
Chris Lattner21fb98e2009-09-23 06:06:36 +00001911 return false;
1912}
1913
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001914/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1915/// int type). This simply type checks that type is one of the defined
1916/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001917// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001918bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001919 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001920
1921 // We can't check the value of a dependent argument.
1922 if (TheCall->getArg(1)->isTypeDependent() ||
1923 TheCall->getArg(1)->isValueDependent())
1924 return false;
1925
Eric Christopher691ebc32010-04-17 02:26:23 +00001926 // Check constant-ness first.
1927 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1928 return true;
1929
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001930 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001931 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001932 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1933 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001934 }
1935
1936 return false;
1937}
1938
Eli Friedman586d6a82009-05-03 06:04:26 +00001939/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001940/// This checks that val is a constant 1.
1941bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1942 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001943 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001944
Eric Christopher691ebc32010-04-17 02:26:23 +00001945 // TODO: This is less than ideal. Overload this to take a value.
1946 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1947 return true;
1948
1949 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001950 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1951 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1952
1953 return false;
1954}
1955
Richard Smith0e218972013-08-05 18:49:43 +00001956namespace {
1957enum StringLiteralCheckType {
1958 SLCT_NotALiteral,
1959 SLCT_UncheckedLiteral,
1960 SLCT_CheckedLiteral
1961};
1962}
1963
Richard Smith831421f2012-06-25 20:30:08 +00001964// Determine if an expression is a string literal or constant string.
1965// If this function returns false on the arguments to a function expecting a
1966// format string, we will usually need to emit a warning.
1967// True string literals are then checked by CheckFormatString.
Richard Smith0e218972013-08-05 18:49:43 +00001968static StringLiteralCheckType
1969checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
1970 bool HasVAListArg, unsigned format_idx,
1971 unsigned firstDataArg, Sema::FormatStringType Type,
1972 Sema::VariadicCallType CallType, bool InFunctionCall,
1973 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001974 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001975 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001976 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001977
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001978 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001979
Richard Smith0e218972013-08-05 18:49:43 +00001980 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikiea73cdcb2012-02-10 21:07:25 +00001981 // Technically -Wformat-nonliteral does not warn about this case.
1982 // The behavior of printf and friends in this case is implementation
1983 // dependent. Ideally if the format string cannot be null then
1984 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith0e218972013-08-05 18:49:43 +00001985 return SLCT_UncheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001986
Ted Kremenekd30ef872009-01-12 23:09:09 +00001987 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001988 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001989 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001990 // The expression is a literal if both sub-expressions were, and it was
1991 // completely checked only if both sub-expressions were checked.
1992 const AbstractConditionalOperator *C =
1993 cast<AbstractConditionalOperator>(E);
1994 StringLiteralCheckType Left =
Richard Smith0e218972013-08-05 18:49:43 +00001995 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001996 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00001997 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00001998 if (Left == SLCT_NotALiteral)
1999 return SLCT_NotALiteral;
2000 StringLiteralCheckType Right =
Richard Smith0e218972013-08-05 18:49:43 +00002001 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00002002 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002003 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002004 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002005 }
2006
2007 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00002008 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2009 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002010 }
2011
John McCall56ca35d2011-02-17 10:25:35 +00002012 case Stmt::OpaqueValueExprClass:
2013 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2014 E = src;
2015 goto tryAgain;
2016 }
Richard Smith831421f2012-06-25 20:30:08 +00002017 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00002018
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00002019 case Stmt::PredefinedExprClass:
2020 // While __func__, etc., are technically not string literals, they
2021 // cannot contain format specifiers and thus are not a security
2022 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00002023 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00002024
Ted Kremenek082d9362009-03-20 21:35:28 +00002025 case Stmt::DeclRefExprClass: {
2026 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Ted Kremenek082d9362009-03-20 21:35:28 +00002028 // As an exception, do not flag errors for variables binding to
2029 // const string literals.
2030 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2031 bool isConstant = false;
2032 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00002033
Richard Smith0e218972013-08-05 18:49:43 +00002034 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2035 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002036 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smith0e218972013-08-05 18:49:43 +00002037 isConstant = T.isConstant(S.Context) &&
2038 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00002039 } else if (T->isObjCObjectPointerType()) {
2040 // In ObjC, there is usually no "const ObjectPointer" type,
2041 // so don't check if the pointee type is constant.
Richard Smith0e218972013-08-05 18:49:43 +00002042 isConstant = T.isConstant(S.Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00002043 }
Mike Stump1eb44332009-09-09 15:08:12 +00002044
Ted Kremenek082d9362009-03-20 21:35:28 +00002045 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002046 if (const Expr *Init = VD->getAnyInitializer()) {
2047 // Look through initializers like const char c[] = { "foo" }
2048 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2049 if (InitList->isStringLiteralInit())
2050 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2051 }
Richard Smith0e218972013-08-05 18:49:43 +00002052 return checkFormatStringExpr(S, Init, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002053 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002054 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002055 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002056 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002057 }
Mike Stump1eb44332009-09-09 15:08:12 +00002058
Anders Carlssond966a552009-06-28 19:55:58 +00002059 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2060 // special check to see if the format string is a function parameter
2061 // of the function calling the printf function. If the function
2062 // has an attribute indicating it is a printf-like function, then we
2063 // should suppress warnings concerning non-literals being used in a call
2064 // to a vprintf function. For example:
2065 //
2066 // void
2067 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2068 // va_list ap;
2069 // va_start(ap, fmt);
2070 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2071 // ...
Richard Smith0e218972013-08-05 18:49:43 +00002072 // }
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002073 if (HasVAListArg) {
2074 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2075 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2076 int PVIndex = PV->getFunctionScopeIndex() + 1;
2077 for (specific_attr_iterator<FormatAttr>
2078 i = ND->specific_attr_begin<FormatAttr>(),
2079 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
2080 FormatAttr *PVFormat = *i;
2081 // adjust for implicit parameter
2082 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2083 if (MD->isInstance())
2084 ++PVIndex;
2085 // We also check if the formats are compatible.
2086 // We can't pass a 'scanf' string to a 'printf' function.
2087 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smith0e218972013-08-05 18:49:43 +00002088 Type == S.GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00002089 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002090 }
2091 }
2092 }
2093 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002094 }
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Richard Smith831421f2012-06-25 20:30:08 +00002096 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00002097 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00002098
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002099 case Stmt::CallExprClass:
2100 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00002101 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002102 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2103 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2104 unsigned ArgIndex = FA->getFormatIdx();
2105 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2106 if (MD->isInstance())
2107 --ArgIndex;
2108 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002109
Richard Smith0e218972013-08-05 18:49:43 +00002110 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002111 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002112 Type, CallType, InFunctionCall,
2113 CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002114 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2115 unsigned BuiltinID = FD->getBuiltinID();
2116 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2117 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2118 const Expr *Arg = CE->getArg(0);
Richard Smith0e218972013-08-05 18:49:43 +00002119 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002120 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002121 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002122 InFunctionCall, CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002123 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00002124 }
2125 }
Mike Stump1eb44332009-09-09 15:08:12 +00002126
Richard Smith831421f2012-06-25 20:30:08 +00002127 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00002128 }
Fariborz Jahanianc85832f2013-10-18 21:20:34 +00002129
2130 case Stmt::ObjCMessageExprClass: {
2131 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(E);
2132 if (const ObjCMethodDecl *MDecl = ME->getMethodDecl()) {
2133 if (const NamedDecl *ND = dyn_cast<NamedDecl>(MDecl)) {
2134 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2135 unsigned ArgIndex = FA->getFormatIdx();
2136 if (ArgIndex <= ME->getNumArgs()) {
2137 const Expr *Arg = ME->getArg(ArgIndex-1);
2138 return checkFormatStringExpr(S, Arg, Args,
2139 HasVAListArg, format_idx,
2140 firstDataArg, Type, CallType,
2141 InFunctionCall, CheckedVarArgs);
2142 }
2143 }
2144 }
2145 }
2146
2147 return SLCT_NotALiteral;
2148 }
2149
Ted Kremenek082d9362009-03-20 21:35:28 +00002150 case Stmt::ObjCStringLiteralClass:
2151 case Stmt::StringLiteralClass: {
2152 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002153
Ted Kremenek082d9362009-03-20 21:35:28 +00002154 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00002155 StrE = ObjCFExpr->getString();
2156 else
Ted Kremenek082d9362009-03-20 21:35:28 +00002157 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002158
Ted Kremenekd30ef872009-01-12 23:09:09 +00002159 if (StrE) {
Richard Smith0e218972013-08-05 18:49:43 +00002160 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2161 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002162 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002163 }
Mike Stump1eb44332009-09-09 15:08:12 +00002164
Richard Smith831421f2012-06-25 20:30:08 +00002165 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002166 }
Mike Stump1eb44332009-09-09 15:08:12 +00002167
Ted Kremenek082d9362009-03-20 21:35:28 +00002168 default:
Richard Smith831421f2012-06-25 20:30:08 +00002169 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002170 }
2171}
2172
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002173void
Mike Stump1eb44332009-09-09 15:08:12 +00002174Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00002175 const Expr * const *ExprArgs,
2176 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00002177 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
2178 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002179 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00002180 const Expr *ArgExpr = ExprArgs[*i];
Nick Lewycky3edf3872013-01-23 05:08:29 +00002181
2182 // As a special case, transparent unions initialized with zero are
2183 // considered null for the purposes of the nonnull attribute.
2184 if (const RecordType *UT = ArgExpr->getType()->getAsUnionType()) {
2185 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2186 if (const CompoundLiteralExpr *CLE =
2187 dyn_cast<CompoundLiteralExpr>(ArgExpr))
2188 if (const InitListExpr *ILE =
2189 dyn_cast<InitListExpr>(CLE->getInitializer()))
2190 ArgExpr = ILE->getInit(0);
2191 }
2192
2193 bool Result;
2194 if (ArgExpr->EvaluateAsBooleanCondition(Result, Context) && !Result)
Nick Lewycky909a70d2011-03-25 01:44:32 +00002195 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002196 }
2197}
Ted Kremenekd30ef872009-01-12 23:09:09 +00002198
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002199Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmancaa5ab22013-09-03 21:02:22 +00002200 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002201 .Case("scanf", FST_Scanf)
2202 .Cases("printf", "printf0", FST_Printf)
2203 .Cases("NSString", "CFString", FST_NSString)
2204 .Case("strftime", FST_Strftime)
2205 .Case("strfmon", FST_Strfmon)
2206 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2207 .Default(FST_Unknown);
2208}
2209
Jordan Roseddcfbc92012-07-19 18:10:23 +00002210/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00002211/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00002212/// Returns true if a format string has been fully checked.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002213bool Sema::CheckFormatArguments(const FormatAttr *Format,
2214 ArrayRef<const Expr *> Args,
2215 bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002216 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002217 SourceLocation Loc, SourceRange Range,
2218 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith831421f2012-06-25 20:30:08 +00002219 FormatStringInfo FSI;
2220 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002221 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith831421f2012-06-25 20:30:08 +00002222 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smith0e218972013-08-05 18:49:43 +00002223 CallType, Loc, Range, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002224 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002225}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00002226
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002227bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002228 bool HasVAListArg, unsigned format_idx,
2229 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002230 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002231 SourceLocation Loc, SourceRange Range,
2232 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002233 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002234 if (format_idx >= Args.size()) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002235 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00002236 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00002237 }
Mike Stump1eb44332009-09-09 15:08:12 +00002238
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002239 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00002240
Chris Lattner59907c42007-08-10 20:18:51 +00002241 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00002242 //
Ted Kremenek71895b92007-08-14 17:39:48 +00002243 // Dynamically generated format strings are difficult to
2244 // automatically vet at compile time. Requiring that format strings
2245 // are string literals: (1) permits the checking of format strings by
2246 // the compiler and thereby (2) can practically remove the source of
2247 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002248
Mike Stump1eb44332009-09-09 15:08:12 +00002249 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002250 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00002251 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002252 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00002253 StringLiteralCheckType CT =
Richard Smith0e218972013-08-05 18:49:43 +00002254 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2255 format_idx, firstDataArg, Type, CallType,
2256 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002257 if (CT != SLCT_NotALiteral)
2258 // Literal format string found, check done!
2259 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002260
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002261 // Strftime is particular as it always uses a single 'time' argument,
2262 // so it is safe to pass a non-literal string.
2263 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00002264 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002265
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002266 // Do not emit diag when the string param is a macro expansion and the
2267 // format is either NSString or CFString. This is a hack to prevent
2268 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2269 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00002270 if (Type == FST_NSString &&
2271 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00002272 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002273
Chris Lattner655f1412009-04-29 04:59:47 +00002274 // If there are no arguments specified, warn with -Wformat-security, otherwise
2275 // warn only with -Wformat-nonliteral.
Eli Friedman2243e782013-06-18 18:10:01 +00002276 if (Args.size() == firstDataArg)
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002277 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002278 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00002279 << OrigFormatExpr->getSourceRange();
2280 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002281 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002282 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00002283 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00002284 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002285}
Ted Kremenek71895b92007-08-14 17:39:48 +00002286
Ted Kremeneke0e53132010-01-28 23:39:18 +00002287namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00002288class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2289protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00002290 Sema &S;
2291 const StringLiteral *FExpr;
2292 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00002293 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002294 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002295 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00002296 const bool HasVAListArg;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002297 ArrayRef<const Expr *> Args;
Ted Kremenek0d277352010-01-29 01:06:55 +00002298 unsigned FormatIdx;
Richard Smith0e218972013-08-05 18:49:43 +00002299 llvm::SmallBitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00002300 bool usesPositionalArgs;
2301 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00002302 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00002303 Sema::VariadicCallType CallType;
Richard Smith0e218972013-08-05 18:49:43 +00002304 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002305public:
Ted Kremenek826a3452010-07-16 02:11:22 +00002306 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00002307 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002308 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002309 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002310 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00002311 Sema::VariadicCallType callType,
2312 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremeneke0e53132010-01-28 23:39:18 +00002313 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00002314 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2315 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002316 Args(Args), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00002317 usesPositionalArgs(false), atFirstArg(true),
Richard Smith0e218972013-08-05 18:49:43 +00002318 inFunctionCall(inFunctionCall), CallType(callType),
2319 CheckedVarArgs(CheckedVarArgs) {
2320 CoveredArgs.resize(numDataArgs);
2321 CoveredArgs.reset();
2322 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002323
Ted Kremenek07d161f2010-01-29 01:50:07 +00002324 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002325
Ted Kremenek826a3452010-07-16 02:11:22 +00002326 void HandleIncompleteSpecifier(const char *startSpecifier,
2327 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00002328
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002329 void HandleInvalidLengthModifier(
2330 const analyze_format_string::FormatSpecifier &FS,
2331 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002332 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002333
Hans Wennborg76517422012-02-22 10:17:01 +00002334 void HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002335 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002336 const char *startSpecifier, unsigned specifierLen);
2337
2338 void HandleNonStandardConversionSpecifier(
2339 const analyze_format_string::ConversionSpecifier &CS,
2340 const char *startSpecifier, unsigned specifierLen);
2341
Hans Wennborgf8562642012-03-09 10:10:54 +00002342 virtual void HandlePosition(const char *startPos, unsigned posLen);
2343
Ted Kremenekefaff192010-02-27 01:41:03 +00002344 virtual void HandleInvalidPosition(const char *startSpecifier,
2345 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00002346 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00002347
2348 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2349
Ted Kremeneke0e53132010-01-28 23:39:18 +00002350 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002351
Richard Trieu55733de2011-10-28 00:41:25 +00002352 template <typename Range>
2353 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2354 const Expr *ArgumentExpr,
2355 PartialDiagnostic PDiag,
2356 SourceLocation StringLoc,
2357 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002358 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002359
Ted Kremenek826a3452010-07-16 02:11:22 +00002360protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002361 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2362 const char *startSpec,
2363 unsigned specifierLen,
2364 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00002365
2366 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2367 const char *startSpec,
2368 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002369
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002370 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00002371 CharSourceRange getSpecifierRange(const char *startSpecifier,
2372 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002373 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002374
Ted Kremenek0d277352010-01-29 01:06:55 +00002375 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00002376
2377 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2378 const analyze_format_string::ConversionSpecifier &CS,
2379 const char *startSpecifier, unsigned specifierLen,
2380 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00002381
2382 template <typename Range>
2383 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2384 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002385 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002386
2387 void CheckPositionalAndNonpositionalArgs(
2388 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002389};
2390}
2391
Ted Kremenek826a3452010-07-16 02:11:22 +00002392SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002393 return OrigFormatExpr->getSourceRange();
2394}
2395
Ted Kremenek826a3452010-07-16 02:11:22 +00002396CharSourceRange CheckFormatHandler::
2397getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002398 SourceLocation Start = getLocationOfByte(startSpecifier);
2399 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2400
2401 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002402 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002403
2404 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002405}
2406
Ted Kremenek826a3452010-07-16 02:11:22 +00002407SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002408 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002409}
2410
Ted Kremenek826a3452010-07-16 02:11:22 +00002411void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2412 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002413 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2414 getLocationOfByte(startSpecifier),
2415 /*IsStringLocation*/true,
2416 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002417}
2418
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002419void CheckFormatHandler::HandleInvalidLengthModifier(
2420 const analyze_format_string::FormatSpecifier &FS,
2421 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002422 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002423 using namespace analyze_format_string;
2424
2425 const LengthModifier &LM = FS.getLengthModifier();
2426 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2427
2428 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002429 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002430 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002431 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002432 getLocationOfByte(LM.getStart()),
2433 /*IsStringLocation*/true,
2434 getSpecifierRange(startSpecifier, specifierLen));
2435
2436 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2437 << FixedLM->toString()
2438 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2439
2440 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00002441 FixItHint Hint;
2442 if (DiagID == diag::warn_format_nonsensical_length)
2443 Hint = FixItHint::CreateRemoval(LMRange);
2444
2445 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002446 getLocationOfByte(LM.getStart()),
2447 /*IsStringLocation*/true,
2448 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002449 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002450 }
2451}
2452
Hans Wennborg76517422012-02-22 10:17:01 +00002453void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002454 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002455 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002456 using namespace analyze_format_string;
2457
2458 const LengthModifier &LM = FS.getLengthModifier();
2459 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2460
2461 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002462 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose8be066e2012-09-08 04:00:12 +00002463 if (FixedLM) {
2464 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2465 << LM.toString() << 0,
2466 getLocationOfByte(LM.getStart()),
2467 /*IsStringLocation*/true,
2468 getSpecifierRange(startSpecifier, specifierLen));
2469
2470 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2471 << FixedLM->toString()
2472 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2473
2474 } else {
2475 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2476 << LM.toString() << 0,
2477 getLocationOfByte(LM.getStart()),
2478 /*IsStringLocation*/true,
2479 getSpecifierRange(startSpecifier, specifierLen));
2480 }
Hans Wennborg76517422012-02-22 10:17:01 +00002481}
2482
2483void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2484 const analyze_format_string::ConversionSpecifier &CS,
2485 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002486 using namespace analyze_format_string;
2487
2488 // See if we know how to fix this conversion specifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002489 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose670941c2012-09-13 02:11:15 +00002490 if (FixedCS) {
2491 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2492 << CS.toString() << /*conversion specifier*/1,
2493 getLocationOfByte(CS.getStart()),
2494 /*IsStringLocation*/true,
2495 getSpecifierRange(startSpecifier, specifierLen));
2496
2497 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2498 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2499 << FixedCS->toString()
2500 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2501 } else {
2502 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2503 << CS.toString() << /*conversion specifier*/1,
2504 getLocationOfByte(CS.getStart()),
2505 /*IsStringLocation*/true,
2506 getSpecifierRange(startSpecifier, specifierLen));
2507 }
Hans Wennborg76517422012-02-22 10:17:01 +00002508}
2509
Hans Wennborgf8562642012-03-09 10:10:54 +00002510void CheckFormatHandler::HandlePosition(const char *startPos,
2511 unsigned posLen) {
2512 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2513 getLocationOfByte(startPos),
2514 /*IsStringLocation*/true,
2515 getSpecifierRange(startPos, posLen));
2516}
2517
Ted Kremenekefaff192010-02-27 01:41:03 +00002518void
Ted Kremenek826a3452010-07-16 02:11:22 +00002519CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2520 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002521 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2522 << (unsigned) p,
2523 getLocationOfByte(startPos), /*IsStringLocation*/true,
2524 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002525}
2526
Ted Kremenek826a3452010-07-16 02:11:22 +00002527void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002528 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002529 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2530 getLocationOfByte(startPos),
2531 /*IsStringLocation*/true,
2532 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002533}
2534
Ted Kremenek826a3452010-07-16 02:11:22 +00002535void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002536 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002537 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002538 EmitFormatDiagnostic(
2539 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2540 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2541 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002542 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002543}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002544
Jordan Rose48716662012-07-19 18:10:08 +00002545// Note that this may return NULL if there was an error parsing or building
2546// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002547const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002548 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002549}
2550
2551void CheckFormatHandler::DoneProcessing() {
2552 // Does the number of data arguments exceed the number of
2553 // format conversions in the format string?
2554 if (!HasVAListArg) {
2555 // Find any arguments that weren't covered.
2556 CoveredArgs.flip();
2557 signed notCoveredArg = CoveredArgs.find_first();
2558 if (notCoveredArg >= 0) {
2559 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002560 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2561 SourceLocation Loc = E->getLocStart();
2562 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2563 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2564 Loc, /*IsStringLocation*/false,
2565 getFormatStringRange());
2566 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002567 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002568 }
2569 }
2570}
2571
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002572bool
2573CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2574 SourceLocation Loc,
2575 const char *startSpec,
2576 unsigned specifierLen,
2577 const char *csStart,
2578 unsigned csLen) {
2579
2580 bool keepGoing = true;
2581 if (argIndex < NumDataArgs) {
2582 // Consider the argument coverered, even though the specifier doesn't
2583 // make sense.
2584 CoveredArgs.set(argIndex);
2585 }
2586 else {
2587 // If argIndex exceeds the number of data arguments we
2588 // don't issue a warning because that is just a cascade of warnings (and
2589 // they may have intended '%%' anyway). We don't want to continue processing
2590 // the format string after this point, however, as we will like just get
2591 // gibberish when trying to match arguments.
2592 keepGoing = false;
2593 }
2594
Richard Trieu55733de2011-10-28 00:41:25 +00002595 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2596 << StringRef(csStart, csLen),
2597 Loc, /*IsStringLocation*/true,
2598 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002599
2600 return keepGoing;
2601}
2602
Richard Trieu55733de2011-10-28 00:41:25 +00002603void
2604CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2605 const char *startSpec,
2606 unsigned specifierLen) {
2607 EmitFormatDiagnostic(
2608 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2609 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2610}
2611
Ted Kremenek666a1972010-07-26 19:45:42 +00002612bool
2613CheckFormatHandler::CheckNumArgs(
2614 const analyze_format_string::FormatSpecifier &FS,
2615 const analyze_format_string::ConversionSpecifier &CS,
2616 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2617
2618 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002619 PartialDiagnostic PDiag = FS.usesPositionalArg()
2620 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2621 << (argIndex+1) << NumDataArgs)
2622 : S.PDiag(diag::warn_printf_insufficient_data_args);
2623 EmitFormatDiagnostic(
2624 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2625 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002626 return false;
2627 }
2628 return true;
2629}
2630
Richard Trieu55733de2011-10-28 00:41:25 +00002631template<typename Range>
2632void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2633 SourceLocation Loc,
2634 bool IsStringLocation,
2635 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002636 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002637 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002638 Loc, IsStringLocation, StringRange, FixIt);
2639}
2640
2641/// \brief If the format string is not within the funcion call, emit a note
2642/// so that the function call and string are in diagnostic messages.
2643///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002644/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002645/// call and only one diagnostic message will be produced. Otherwise, an
2646/// extra note will be emitted pointing to location of the format string.
2647///
2648/// \param ArgumentExpr the expression that is passed as the format string
2649/// argument in the function call. Used for getting locations when two
2650/// diagnostics are emitted.
2651///
2652/// \param PDiag the callee should already have provided any strings for the
2653/// diagnostic message. This function only adds locations and fixits
2654/// to diagnostics.
2655///
2656/// \param Loc primary location for diagnostic. If two diagnostics are
2657/// required, one will be at Loc and a new SourceLocation will be created for
2658/// the other one.
2659///
2660/// \param IsStringLocation if true, Loc points to the format string should be
2661/// used for the note. Otherwise, Loc points to the argument list and will
2662/// be used with PDiag.
2663///
2664/// \param StringRange some or all of the string to highlight. This is
2665/// templated so it can accept either a CharSourceRange or a SourceRange.
2666///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002667/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002668template<typename Range>
2669void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2670 const Expr *ArgumentExpr,
2671 PartialDiagnostic PDiag,
2672 SourceLocation Loc,
2673 bool IsStringLocation,
2674 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002675 ArrayRef<FixItHint> FixIt) {
2676 if (InFunctionCall) {
2677 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2678 D << StringRange;
2679 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2680 I != E; ++I) {
2681 D << *I;
2682 }
2683 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00002684 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2685 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00002686
2687 const Sema::SemaDiagnosticBuilder &Note =
2688 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2689 diag::note_format_string_defined);
2690
2691 Note << StringRange;
2692 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2693 I != E; ++I) {
2694 Note << *I;
2695 }
Richard Trieu55733de2011-10-28 00:41:25 +00002696 }
2697}
2698
Ted Kremenek826a3452010-07-16 02:11:22 +00002699//===--- CHECK: Printf format string checking ------------------------------===//
2700
2701namespace {
2702class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002703 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002704public:
2705 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2706 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002707 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002708 const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002709 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002710 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00002711 Sema::VariadicCallType CallType,
2712 llvm::SmallBitVector &CheckedVarArgs)
2713 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2714 numDataArgs, beg, hasVAListArg, Args,
2715 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2716 ObjCContext(isObjC)
Jordan Roseddcfbc92012-07-19 18:10:23 +00002717 {}
2718
Ted Kremenek826a3452010-07-16 02:11:22 +00002719
2720 bool HandleInvalidPrintfConversionSpecifier(
2721 const analyze_printf::PrintfSpecifier &FS,
2722 const char *startSpecifier,
2723 unsigned specifierLen);
2724
2725 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2726 const char *startSpecifier,
2727 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002728 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2729 const char *StartSpecifier,
2730 unsigned SpecifierLen,
2731 const Expr *E);
2732
Ted Kremenek826a3452010-07-16 02:11:22 +00002733 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2734 const char *startSpecifier, unsigned specifierLen);
2735 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2736 const analyze_printf::OptionalAmount &Amt,
2737 unsigned type,
2738 const char *startSpecifier, unsigned specifierLen);
2739 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2740 const analyze_printf::OptionalFlag &flag,
2741 const char *startSpecifier, unsigned specifierLen);
2742 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2743 const analyze_printf::OptionalFlag &ignoredFlag,
2744 const analyze_printf::OptionalFlag &flag,
2745 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002746 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith831421f2012-06-25 20:30:08 +00002747 const Expr *E, const CharSourceRange &CSR);
2748
Ted Kremenek826a3452010-07-16 02:11:22 +00002749};
2750}
2751
2752bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2753 const analyze_printf::PrintfSpecifier &FS,
2754 const char *startSpecifier,
2755 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002756 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002757 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002758
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002759 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2760 getLocationOfByte(CS.getStart()),
2761 startSpecifier, specifierLen,
2762 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002763}
2764
Ted Kremenek826a3452010-07-16 02:11:22 +00002765bool CheckPrintfHandler::HandleAmount(
2766 const analyze_format_string::OptionalAmount &Amt,
2767 unsigned k, const char *startSpecifier,
2768 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002769
2770 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002771 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002772 unsigned argIndex = Amt.getArgIndex();
2773 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002774 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2775 << k,
2776 getLocationOfByte(Amt.getStart()),
2777 /*IsStringLocation*/true,
2778 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002779 // Don't do any more checking. We will just emit
2780 // spurious errors.
2781 return false;
2782 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002783
Ted Kremenek0d277352010-01-29 01:06:55 +00002784 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002785 // Although not in conformance with C99, we also allow the argument to be
2786 // an 'unsigned int' as that is a reasonably safe case. GCC also
2787 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002788 CoveredArgs.set(argIndex);
2789 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002790 if (!Arg)
2791 return false;
2792
Ted Kremenek0d277352010-01-29 01:06:55 +00002793 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002794
Hans Wennborgf3749f42012-08-07 08:11:26 +00002795 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2796 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002797
Hans Wennborgf3749f42012-08-07 08:11:26 +00002798 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002799 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002800 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002801 << T << Arg->getSourceRange(),
2802 getLocationOfByte(Amt.getStart()),
2803 /*IsStringLocation*/true,
2804 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002805 // Don't do any more checking. We will just emit
2806 // spurious errors.
2807 return false;
2808 }
2809 }
2810 }
2811 return true;
2812}
Ted Kremenek0d277352010-01-29 01:06:55 +00002813
Tom Caree4ee9662010-06-17 19:00:27 +00002814void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002815 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002816 const analyze_printf::OptionalAmount &Amt,
2817 unsigned type,
2818 const char *startSpecifier,
2819 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002820 const analyze_printf::PrintfConversionSpecifier &CS =
2821 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002822
Richard Trieu55733de2011-10-28 00:41:25 +00002823 FixItHint fixit =
2824 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2825 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2826 Amt.getConstantLength()))
2827 : FixItHint();
2828
2829 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2830 << type << CS.toString(),
2831 getLocationOfByte(Amt.getStart()),
2832 /*IsStringLocation*/true,
2833 getSpecifierRange(startSpecifier, specifierLen),
2834 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002835}
2836
Ted Kremenek826a3452010-07-16 02:11:22 +00002837void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002838 const analyze_printf::OptionalFlag &flag,
2839 const char *startSpecifier,
2840 unsigned specifierLen) {
2841 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002842 const analyze_printf::PrintfConversionSpecifier &CS =
2843 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002844 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2845 << flag.toString() << CS.toString(),
2846 getLocationOfByte(flag.getPosition()),
2847 /*IsStringLocation*/true,
2848 getSpecifierRange(startSpecifier, specifierLen),
2849 FixItHint::CreateRemoval(
2850 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002851}
2852
2853void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002854 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002855 const analyze_printf::OptionalFlag &ignoredFlag,
2856 const analyze_printf::OptionalFlag &flag,
2857 const char *startSpecifier,
2858 unsigned specifierLen) {
2859 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002860 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2861 << ignoredFlag.toString() << flag.toString(),
2862 getLocationOfByte(ignoredFlag.getPosition()),
2863 /*IsStringLocation*/true,
2864 getSpecifierRange(startSpecifier, specifierLen),
2865 FixItHint::CreateRemoval(
2866 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002867}
2868
Richard Smith831421f2012-06-25 20:30:08 +00002869// Determines if the specified is a C++ class or struct containing
2870// a member with the specified name and kind (e.g. a CXXMethodDecl named
2871// "c_str()").
2872template<typename MemberKind>
2873static llvm::SmallPtrSet<MemberKind*, 1>
2874CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2875 const RecordType *RT = Ty->getAs<RecordType>();
2876 llvm::SmallPtrSet<MemberKind*, 1> Results;
2877
2878 if (!RT)
2879 return Results;
2880 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2881 if (!RD)
2882 return Results;
2883
2884 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2885 Sema::LookupMemberName);
2886
2887 // We just need to include all members of the right kind turned up by the
2888 // filter, at this point.
2889 if (S.LookupQualifiedName(R, RT->getDecl()))
2890 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2891 NamedDecl *decl = (*I)->getUnderlyingDecl();
2892 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2893 Results.insert(FK);
2894 }
2895 return Results;
2896}
2897
2898// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002899// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002900// Returns true when a c_str() conversion method is found.
2901bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgf3749f42012-08-07 08:11:26 +00002902 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith831421f2012-06-25 20:30:08 +00002903 const CharSourceRange &CSR) {
2904 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2905
2906 MethodSet Results =
2907 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2908
2909 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2910 MI != ME; ++MI) {
2911 const CXXMethodDecl *Method = *MI;
2912 if (Method->getNumParams() == 0 &&
Hans Wennborgf3749f42012-08-07 08:11:26 +00002913 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith831421f2012-06-25 20:30:08 +00002914 // FIXME: Suggest parens if the expression needs them.
2915 SourceLocation EndLoc =
2916 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2917 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2918 << "c_str()"
2919 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2920 return true;
2921 }
2922 }
2923
2924 return false;
2925}
2926
Ted Kremeneke0e53132010-01-28 23:39:18 +00002927bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002928CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002929 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002930 const char *startSpecifier,
2931 unsigned specifierLen) {
2932
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002933 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002934 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002935 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002936
Ted Kremenekbaa40062010-07-19 22:01:06 +00002937 if (FS.consumesDataArgument()) {
2938 if (atFirstArg) {
2939 atFirstArg = false;
2940 usesPositionalArgs = FS.usesPositionalArg();
2941 }
2942 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002943 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2944 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002945 return false;
2946 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002947 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002948
Ted Kremenekefaff192010-02-27 01:41:03 +00002949 // First check if the field width, precision, and conversion specifier
2950 // have matching data arguments.
2951 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2952 startSpecifier, specifierLen)) {
2953 return false;
2954 }
2955
2956 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2957 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002958 return false;
2959 }
2960
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002961 if (!CS.consumesDataArgument()) {
2962 // FIXME: Technically specifying a precision or field width here
2963 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002964 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002965 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002966
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002967 // Consume the argument.
2968 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002969 if (argIndex < NumDataArgs) {
2970 // The check to see if the argIndex is valid will come later.
2971 // We set the bit here because we may exit early from this
2972 // function if we encounter some other error.
2973 CoveredArgs.set(argIndex);
2974 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002975
2976 // Check for using an Objective-C specific conversion specifier
2977 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002978 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002979 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2980 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002981 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002982
Tom Caree4ee9662010-06-17 19:00:27 +00002983 // Check for invalid use of field width
2984 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002985 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002986 startSpecifier, specifierLen);
2987 }
2988
2989 // Check for invalid use of precision
2990 if (!FS.hasValidPrecision()) {
2991 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2992 startSpecifier, specifierLen);
2993 }
2994
2995 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002996 if (!FS.hasValidThousandsGroupingPrefix())
2997 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002998 if (!FS.hasValidLeadingZeros())
2999 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3000 if (!FS.hasValidPlusPrefix())
3001 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00003002 if (!FS.hasValidSpacePrefix())
3003 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00003004 if (!FS.hasValidAlternativeForm())
3005 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3006 if (!FS.hasValidLeftJustified())
3007 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3008
3009 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00003010 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3011 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3012 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00003013 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3014 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3015 startSpecifier, specifierLen);
3016
3017 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003018 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003019 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3020 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003021 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003022 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003023 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003024 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3025 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00003026
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003027 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3028 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3029
Ted Kremenekda51f0d2010-01-29 01:43:31 +00003030 // The remaining checks depend on the data arguments.
3031 if (HasVAListArg)
3032 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003033
Ted Kremenek666a1972010-07-26 19:45:42 +00003034 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00003035 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003036
Jordan Rose48716662012-07-19 18:10:08 +00003037 const Expr *Arg = getDataArg(argIndex);
3038 if (!Arg)
3039 return true;
3040
3041 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00003042}
3043
Jordan Roseec087352012-09-05 22:56:26 +00003044static bool requiresParensToAddCast(const Expr *E) {
3045 // FIXME: We should have a general way to reason about operator
3046 // precedence and whether parens are actually needed here.
3047 // Take care of a few common cases where they aren't.
3048 const Expr *Inside = E->IgnoreImpCasts();
3049 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3050 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3051
3052 switch (Inside->getStmtClass()) {
3053 case Stmt::ArraySubscriptExprClass:
3054 case Stmt::CallExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003055 case Stmt::CharacterLiteralClass:
3056 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003057 case Stmt::DeclRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003058 case Stmt::FloatingLiteralClass:
3059 case Stmt::IntegerLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003060 case Stmt::MemberExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003061 case Stmt::ObjCArrayLiteralClass:
3062 case Stmt::ObjCBoolLiteralExprClass:
3063 case Stmt::ObjCBoxedExprClass:
3064 case Stmt::ObjCDictionaryLiteralClass:
3065 case Stmt::ObjCEncodeExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003066 case Stmt::ObjCIvarRefExprClass:
3067 case Stmt::ObjCMessageExprClass:
3068 case Stmt::ObjCPropertyRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003069 case Stmt::ObjCStringLiteralClass:
3070 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003071 case Stmt::ParenExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003072 case Stmt::StringLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003073 case Stmt::UnaryOperatorClass:
3074 return false;
3075 default:
3076 return true;
3077 }
3078}
3079
Richard Smith831421f2012-06-25 20:30:08 +00003080bool
3081CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3082 const char *StartSpecifier,
3083 unsigned SpecifierLen,
3084 const Expr *E) {
3085 using namespace analyze_format_string;
3086 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003087 // Now type check the data expression that matches the
3088 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00003089 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3090 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00003091 if (!AT.isValid())
3092 return true;
Jordan Roseec087352012-09-05 22:56:26 +00003093
Jordan Rose448ac3e2012-12-05 18:44:40 +00003094 QualType ExprTy = E->getType();
Ted Kremenek02be9682013-04-10 06:26:26 +00003095 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3096 ExprTy = TET->getUnderlyingExpr()->getType();
3097 }
3098
Jordan Rose448ac3e2012-12-05 18:44:40 +00003099 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003100 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00003101
Jordan Rose614a8652012-09-05 22:56:19 +00003102 // Look through argument promotions for our error message's reported type.
3103 // This includes the integral and floating promotions, but excludes array
3104 // and function pointer decay; seeing that an argument intended to be a
3105 // string has type 'char [6]' is probably more confusing than 'char *'.
3106 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3107 if (ICE->getCastKind() == CK_IntegralCast ||
3108 ICE->getCastKind() == CK_FloatingCast) {
3109 E = ICE->getSubExpr();
Jordan Rose448ac3e2012-12-05 18:44:40 +00003110 ExprTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00003111
3112 // Check if we didn't match because of an implicit cast from a 'char'
3113 // or 'short' to an 'int'. This is done because printf is a varargs
3114 // function.
3115 if (ICE->getType() == S.Context.IntTy ||
3116 ICE->getType() == S.Context.UnsignedIntTy) {
3117 // All further checking is done on the subexpression.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003118 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003119 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00003120 }
Jordan Roseee0259d2012-06-04 22:48:57 +00003121 }
Jordan Rose448ac3e2012-12-05 18:44:40 +00003122 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3123 // Special case for 'a', which has type 'int' in C.
3124 // Note, however, that we do /not/ want to treat multibyte constants like
3125 // 'MooV' as characters! This form is deprecated but still exists.
3126 if (ExprTy == S.Context.IntTy)
3127 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3128 ExprTy = S.Context.CharTy;
Jordan Rose614a8652012-09-05 22:56:19 +00003129 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003130
Jordan Rose2cd34402012-12-05 18:44:49 +00003131 // %C in an Objective-C context prints a unichar, not a wchar_t.
3132 // If the argument is an integer of some kind, believe the %C and suggest
3133 // a cast instead of changing the conversion specifier.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003134 QualType IntendedTy = ExprTy;
Jordan Rose2cd34402012-12-05 18:44:49 +00003135 if (ObjCContext &&
3136 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3137 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3138 !ExprTy->isCharType()) {
3139 // 'unichar' is defined as a typedef of unsigned short, but we should
3140 // prefer using the typedef if it is visible.
3141 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenek656465d2013-10-15 05:25:17 +00003142
3143 // While we are here, check if the value is an IntegerLiteral that happens
3144 // to be within the valid range.
3145 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3146 const llvm::APInt &V = IL->getValue();
3147 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3148 return true;
3149 }
3150
Jordan Rose2cd34402012-12-05 18:44:49 +00003151 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3152 Sema::LookupOrdinaryName);
3153 if (S.LookupName(Result, S.getCurScope())) {
3154 NamedDecl *ND = Result.getFoundDecl();
3155 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3156 if (TD->getUnderlyingType() == IntendedTy)
3157 IntendedTy = S.Context.getTypedefType(TD);
3158 }
3159 }
3160 }
3161
3162 // Special-case some of Darwin's platform-independence types by suggesting
3163 // casts to primitive types that are known to be large enough.
3164 bool ShouldNotPrintDirectly = false;
Jordan Roseec087352012-09-05 22:56:26 +00003165 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenek6edb0292013-03-25 22:28:37 +00003166 // Use a 'while' to peel off layers of typedefs.
3167 QualType TyTy = IntendedTy;
3168 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseec087352012-09-05 22:56:26 +00003169 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose2cd34402012-12-05 18:44:49 +00003170 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseec087352012-09-05 22:56:26 +00003171 .Case("NSInteger", S.Context.LongTy)
3172 .Case("NSUInteger", S.Context.UnsignedLongTy)
3173 .Case("SInt32", S.Context.IntTy)
3174 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose2cd34402012-12-05 18:44:49 +00003175 .Default(QualType());
3176
3177 if (!CastTy.isNull()) {
3178 ShouldNotPrintDirectly = true;
3179 IntendedTy = CastTy;
Ted Kremenek6edb0292013-03-25 22:28:37 +00003180 break;
Jordan Rose2cd34402012-12-05 18:44:49 +00003181 }
Ted Kremenek6edb0292013-03-25 22:28:37 +00003182 TyTy = UserTy->desugar();
Jordan Roseec087352012-09-05 22:56:26 +00003183 }
3184 }
3185
Jordan Rose614a8652012-09-05 22:56:19 +00003186 // We may be able to offer a FixItHint if it is a supported type.
3187 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00003188 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00003189 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003190
Jordan Rose614a8652012-09-05 22:56:19 +00003191 if (success) {
3192 // Get the fix string from the fixed format specifier
3193 SmallString<16> buf;
3194 llvm::raw_svector_ostream os(buf);
3195 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003196
Jordan Roseec087352012-09-05 22:56:26 +00003197 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3198
Jordan Rose2cd34402012-12-05 18:44:49 +00003199 if (IntendedTy == ExprTy) {
3200 // In this case, the specifier is wrong and should be changed to match
3201 // the argument.
3202 EmitFormatDiagnostic(
3203 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3204 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3205 << E->getSourceRange(),
3206 E->getLocStart(),
3207 /*IsStringLocation*/false,
3208 SpecRange,
3209 FixItHint::CreateReplacement(SpecRange, os.str()));
3210
3211 } else {
Jordan Roseec087352012-09-05 22:56:26 +00003212 // The canonical type for formatting this value is different from the
3213 // actual type of the expression. (This occurs, for example, with Darwin's
3214 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3215 // should be printed as 'long' for 64-bit compatibility.)
3216 // Rather than emitting a normal format/argument mismatch, we want to
3217 // add a cast to the recommended type (and correct the format string
3218 // if necessary).
3219 SmallString<16> CastBuf;
3220 llvm::raw_svector_ostream CastFix(CastBuf);
3221 CastFix << "(";
3222 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3223 CastFix << ")";
3224
3225 SmallVector<FixItHint,4> Hints;
3226 if (!AT.matchesType(S.Context, IntendedTy))
3227 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3228
3229 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3230 // If there's already a cast present, just replace it.
3231 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3232 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3233
3234 } else if (!requiresParensToAddCast(E)) {
3235 // If the expression has high enough precedence,
3236 // just write the C-style cast.
3237 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3238 CastFix.str()));
3239 } else {
3240 // Otherwise, add parens around the expression as well as the cast.
3241 CastFix << "(";
3242 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3243 CastFix.str()));
3244
3245 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3246 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3247 }
3248
Jordan Rose2cd34402012-12-05 18:44:49 +00003249 if (ShouldNotPrintDirectly) {
3250 // The expression has a type that should not be printed directly.
3251 // We extract the name from the typedef because we don't want to show
3252 // the underlying type in the diagnostic.
3253 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseec087352012-09-05 22:56:26 +00003254
Jordan Rose2cd34402012-12-05 18:44:49 +00003255 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3256 << Name << IntendedTy
3257 << E->getSourceRange(),
3258 E->getLocStart(), /*IsStringLocation=*/false,
3259 SpecRange, Hints);
3260 } else {
3261 // In this case, the expression could be printed using a different
3262 // specifier, but we've decided that the specifier is probably correct
3263 // and we should cast instead. Just use the normal warning message.
3264 EmitFormatDiagnostic(
3265 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3266 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3267 << E->getSourceRange(),
3268 E->getLocStart(), /*IsStringLocation*/false,
3269 SpecRange, Hints);
3270 }
Jordan Roseec087352012-09-05 22:56:26 +00003271 }
Jordan Rose614a8652012-09-05 22:56:19 +00003272 } else {
3273 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3274 SpecifierLen);
3275 // Since the warning for passing non-POD types to variadic functions
3276 // was deferred until now, we emit a warning for non-POD
3277 // arguments here.
Richard Smith0e218972013-08-05 18:49:43 +00003278 switch (S.isValidVarArgType(ExprTy)) {
3279 case Sema::VAK_Valid:
3280 case Sema::VAK_ValidInCXX11:
Jordan Rose614a8652012-09-05 22:56:19 +00003281 EmitFormatDiagnostic(
Richard Smith0e218972013-08-05 18:49:43 +00003282 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3283 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3284 << CSR
3285 << E->getSourceRange(),
3286 E->getLocStart(), /*IsStringLocation*/false, CSR);
3287 break;
3288
3289 case Sema::VAK_Undefined:
3290 EmitFormatDiagnostic(
3291 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith80ad52f2013-01-02 11:42:31 +00003292 << S.getLangOpts().CPlusPlus11
Jordan Rose448ac3e2012-12-05 18:44:40 +00003293 << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00003294 << CallType
3295 << AT.getRepresentativeTypeName(S.Context)
3296 << CSR
3297 << E->getSourceRange(),
3298 E->getLocStart(), /*IsStringLocation*/false, CSR);
Jordan Rose614a8652012-09-05 22:56:19 +00003299 checkForCStrMembers(AT, E, CSR);
Richard Smith0e218972013-08-05 18:49:43 +00003300 break;
3301
3302 case Sema::VAK_Invalid:
3303 if (ExprTy->isObjCObjectType())
3304 EmitFormatDiagnostic(
3305 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3306 << S.getLangOpts().CPlusPlus11
3307 << ExprTy
3308 << CallType
3309 << AT.getRepresentativeTypeName(S.Context)
3310 << CSR
3311 << E->getSourceRange(),
3312 E->getLocStart(), /*IsStringLocation*/false, CSR);
3313 else
3314 // FIXME: If this is an initializer list, suggest removing the braces
3315 // or inserting a cast to the target type.
3316 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3317 << isa<InitListExpr>(E) << ExprTy << CallType
3318 << AT.getRepresentativeTypeName(S.Context)
3319 << E->getSourceRange();
3320 break;
3321 }
3322
3323 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3324 "format string specifier index out of range");
3325 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003326 }
3327
Ted Kremeneke0e53132010-01-28 23:39:18 +00003328 return true;
3329}
3330
Ted Kremenek826a3452010-07-16 02:11:22 +00003331//===--- CHECK: Scanf format string checking ------------------------------===//
3332
3333namespace {
3334class CheckScanfHandler : public CheckFormatHandler {
3335public:
3336 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3337 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003338 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003339 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003340 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00003341 Sema::VariadicCallType CallType,
3342 llvm::SmallBitVector &CheckedVarArgs)
3343 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3344 numDataArgs, beg, hasVAListArg,
3345 Args, formatIdx, inFunctionCall, CallType,
3346 CheckedVarArgs)
Jordan Roseddcfbc92012-07-19 18:10:23 +00003347 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00003348
3349 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3350 const char *startSpecifier,
3351 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003352
3353 bool HandleInvalidScanfConversionSpecifier(
3354 const analyze_scanf::ScanfSpecifier &FS,
3355 const char *startSpecifier,
3356 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00003357
3358 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00003359};
Ted Kremenek07d161f2010-01-29 01:50:07 +00003360}
Ted Kremeneke0e53132010-01-28 23:39:18 +00003361
Ted Kremenekb7c21012010-07-16 18:28:03 +00003362void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3363 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00003364 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3365 getLocationOfByte(end), /*IsStringLocation*/true,
3366 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00003367}
3368
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003369bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3370 const analyze_scanf::ScanfSpecifier &FS,
3371 const char *startSpecifier,
3372 unsigned specifierLen) {
3373
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003374 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003375 FS.getConversionSpecifier();
3376
3377 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3378 getLocationOfByte(CS.getStart()),
3379 startSpecifier, specifierLen,
3380 CS.getStart(), CS.getLength());
3381}
3382
Ted Kremenek826a3452010-07-16 02:11:22 +00003383bool CheckScanfHandler::HandleScanfSpecifier(
3384 const analyze_scanf::ScanfSpecifier &FS,
3385 const char *startSpecifier,
3386 unsigned specifierLen) {
3387
3388 using namespace analyze_scanf;
3389 using namespace analyze_format_string;
3390
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003391 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00003392
Ted Kremenekbaa40062010-07-19 22:01:06 +00003393 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3394 // be used to decide if we are using positional arguments consistently.
3395 if (FS.consumesDataArgument()) {
3396 if (atFirstArg) {
3397 atFirstArg = false;
3398 usesPositionalArgs = FS.usesPositionalArg();
3399 }
3400 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003401 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3402 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003403 return false;
3404 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003405 }
3406
3407 // Check if the field with is non-zero.
3408 const OptionalAmount &Amt = FS.getFieldWidth();
3409 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3410 if (Amt.getConstantAmount() == 0) {
3411 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3412 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00003413 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3414 getLocationOfByte(Amt.getStart()),
3415 /*IsStringLocation*/true, R,
3416 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00003417 }
3418 }
3419
3420 if (!FS.consumesDataArgument()) {
3421 // FIXME: Technically specifying a precision or field width here
3422 // makes no sense. Worth issuing a warning at some point.
3423 return true;
3424 }
3425
3426 // Consume the argument.
3427 unsigned argIndex = FS.getArgIndex();
3428 if (argIndex < NumDataArgs) {
3429 // The check to see if the argIndex is valid will come later.
3430 // We set the bit here because we may exit early from this
3431 // function if we encounter some other error.
3432 CoveredArgs.set(argIndex);
3433 }
3434
Ted Kremenek1e51c202010-07-20 20:04:47 +00003435 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003436 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003437 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3438 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003439 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003440 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003441 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003442 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3443 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00003444
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003445 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3446 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3447
Ted Kremenek826a3452010-07-16 02:11:22 +00003448 // The remaining checks depend on the data arguments.
3449 if (HasVAListArg)
3450 return true;
3451
Ted Kremenek666a1972010-07-26 19:45:42 +00003452 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00003453 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00003454
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003455 // Check that the argument type matches the format specifier.
3456 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00003457 if (!Ex)
3458 return true;
3459
Hans Wennborg58e1e542012-08-07 08:59:46 +00003460 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3461 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003462 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00003463 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00003464 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003465
3466 if (success) {
3467 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003468 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003469 llvm::raw_svector_ostream os(buf);
3470 fixedFS.toString(os);
3471
3472 EmitFormatDiagnostic(
3473 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003474 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003475 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003476 Ex->getLocStart(),
3477 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003478 getSpecifierRange(startSpecifier, specifierLen),
3479 FixItHint::CreateReplacement(
3480 getSpecifierRange(startSpecifier, specifierLen),
3481 os.str()));
3482 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003483 EmitFormatDiagnostic(
3484 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003485 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003486 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003487 Ex->getLocStart(),
3488 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003489 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003490 }
3491 }
3492
Ted Kremenek826a3452010-07-16 02:11:22 +00003493 return true;
3494}
3495
3496void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003497 const Expr *OrigFormatExpr,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003498 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003499 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003500 unsigned firstDataArg, FormatStringType Type,
Richard Smith0e218972013-08-05 18:49:43 +00003501 bool inFunctionCall, VariadicCallType CallType,
3502 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003503
Ted Kremeneke0e53132010-01-28 23:39:18 +00003504 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00003505 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003506 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003507 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003508 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3509 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003510 return;
3511 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003512
Ted Kremeneke0e53132010-01-28 23:39:18 +00003513 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00003514 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003515 const char *Str = StrRef.data();
3516 unsigned StrLen = StrRef.size();
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003517 const unsigned numDataArgs = Args.size() - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00003518
Ted Kremeneke0e53132010-01-28 23:39:18 +00003519 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00003520 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00003521 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003522 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003523 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3524 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003525 return;
3526 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003527
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003528 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003529 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003530 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003531 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00003532 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00003533
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003534 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003535 getLangOpts(),
3536 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003537 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003538 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00003539 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003540 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00003541 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00003542
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003543 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003544 getLangOpts(),
3545 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003546 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003547 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00003548}
3549
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003550//===--- CHECK: Standard memory functions ---------------------------------===//
3551
Douglas Gregor2a053a32011-05-03 20:05:22 +00003552/// \brief Determine whether the given type is a dynamic class type (e.g.,
3553/// whether it has a vtable).
3554static bool isDynamicClassType(QualType T) {
3555 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3556 if (CXXRecordDecl *Definition = Record->getDefinition())
3557 if (Definition->isDynamicClass())
3558 return true;
3559
3560 return false;
3561}
3562
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003563/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00003564/// otherwise returns NULL.
3565static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00003566 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00003567 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3568 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3569 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003570
Chandler Carruth000d4282011-06-16 09:09:40 +00003571 return 0;
3572}
3573
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003574/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00003575static QualType getSizeOfArgType(const Expr* E) {
3576 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3577 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3578 if (SizeOf->getKind() == clang::UETT_SizeOf)
3579 return SizeOf->getTypeOfArgument();
3580
3581 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00003582}
3583
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003584/// \brief Check for dangerous or invalid arguments to memset().
3585///
Chandler Carruth929f0132011-06-03 06:23:57 +00003586/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003587/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3588/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003589///
3590/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003591void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00003592 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003593 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00003594 assert(BId != 0);
3595
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003596 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00003597 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00003598 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00003599 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003600 return;
3601
Anna Zaks0a151a12012-01-17 00:37:07 +00003602 unsigned LastArg = (BId == Builtin::BImemset ||
3603 BId == Builtin::BIstrndup ? 1 : 2);
3604 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00003605 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00003606
3607 // We have special checking when the length is a sizeof expression.
3608 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3609 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3610 llvm::FoldingSetNodeID SizeOfArgID;
3611
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003612 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3613 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003614 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003615
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003616 QualType DestTy = Dest->getType();
3617 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3618 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00003619
Chandler Carruth000d4282011-06-16 09:09:40 +00003620 // Never warn about void type pointers. This can be used to suppress
3621 // false positives.
3622 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003623 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003624
Chandler Carruth000d4282011-06-16 09:09:40 +00003625 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3626 // actually comparing the expressions for equality. Because computing the
3627 // expression IDs can be expensive, we only do this if the diagnostic is
3628 // enabled.
3629 if (SizeOfArg &&
3630 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3631 SizeOfArg->getExprLoc())) {
3632 // We only compute IDs for expressions if the warning is enabled, and
3633 // cache the sizeof arg's ID.
3634 if (SizeOfArgID == llvm::FoldingSetNodeID())
3635 SizeOfArg->Profile(SizeOfArgID, Context, true);
3636 llvm::FoldingSetNodeID DestID;
3637 Dest->Profile(DestID, Context, true);
3638 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00003639 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3640 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00003641 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003642 StringRef ReadableName = FnName->getName();
3643
Chandler Carruth000d4282011-06-16 09:09:40 +00003644 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00003645 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00003646 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian7adf4172013-01-30 01:12:44 +00003647 if (!PointeeTy->isIncompleteType() &&
3648 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth000d4282011-06-16 09:09:40 +00003649 ActionIdx = 2; // If the pointee's size is sizeof(char),
3650 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003651
3652 // If the function is defined as a builtin macro, do not show macro
3653 // expansion.
3654 SourceLocation SL = SizeOfArg->getExprLoc();
3655 SourceRange DSR = Dest->getSourceRange();
3656 SourceRange SSR = SizeOfArg->getSourceRange();
3657 SourceManager &SM = PP.getSourceManager();
3658
3659 if (SM.isMacroArgExpansion(SL)) {
3660 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3661 SL = SM.getSpellingLoc(SL);
3662 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3663 SM.getSpellingLoc(DSR.getEnd()));
3664 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3665 SM.getSpellingLoc(SSR.getEnd()));
3666 }
3667
Anna Zaks90c78322012-05-30 23:14:52 +00003668 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00003669 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00003670 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00003671 << PointeeTy
3672 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00003673 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00003674 << SSR);
3675 DiagRuntimeBehavior(SL, SizeOfArg,
3676 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3677 << ActionIdx
3678 << SSR);
3679
Chandler Carruth000d4282011-06-16 09:09:40 +00003680 break;
3681 }
3682 }
3683
3684 // Also check for cases where the sizeof argument is the exact same
3685 // type as the memory argument, and where it points to a user-defined
3686 // record type.
3687 if (SizeOfArgTy != QualType()) {
3688 if (PointeeTy->isRecordType() &&
3689 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3690 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3691 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3692 << FnName << SizeOfArgTy << ArgIdx
3693 << PointeeTy << Dest->getSourceRange()
3694 << LenExpr->getSourceRange());
3695 break;
3696 }
Nico Webere4a1c642011-06-14 16:14:58 +00003697 }
3698
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003699 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00003700 if (isDynamicClassType(PointeeTy)) {
3701
3702 unsigned OperationType = 0;
3703 // "overwritten" if we're warning about the destination for any call
3704 // but memcmp; otherwise a verb appropriate to the call.
3705 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3706 if (BId == Builtin::BImemcpy)
3707 OperationType = 1;
3708 else if(BId == Builtin::BImemmove)
3709 OperationType = 2;
3710 else if (BId == Builtin::BImemcmp)
3711 OperationType = 3;
3712 }
3713
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003714 DiagRuntimeBehavior(
3715 Dest->getExprLoc(), Dest,
3716 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003717 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003718 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003719 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003720 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003721 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3722 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003723 DiagRuntimeBehavior(
3724 Dest->getExprLoc(), Dest,
3725 PDiag(diag::warn_arc_object_memaccess)
3726 << ArgIdx << FnName << PointeeTy
3727 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003728 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003729 continue;
John McCallf85e1932011-06-15 23:02:42 +00003730
3731 DiagRuntimeBehavior(
3732 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003733 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003734 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3735 break;
3736 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003737 }
3738}
3739
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003740// A little helper routine: ignore addition and subtraction of integer literals.
3741// This intentionally does not ignore all integer constant expressions because
3742// we don't want to remove sizeof().
3743static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3744 Ex = Ex->IgnoreParenCasts();
3745
3746 for (;;) {
3747 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3748 if (!BO || !BO->isAdditiveOp())
3749 break;
3750
3751 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3752 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3753
3754 if (isa<IntegerLiteral>(RHS))
3755 Ex = LHS;
3756 else if (isa<IntegerLiteral>(LHS))
3757 Ex = RHS;
3758 else
3759 break;
3760 }
3761
3762 return Ex;
3763}
3764
Anna Zaks0f38ace2012-08-08 21:42:23 +00003765static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3766 ASTContext &Context) {
3767 // Only handle constant-sized or VLAs, but not flexible members.
3768 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3769 // Only issue the FIXIT for arrays of size > 1.
3770 if (CAT->getSize().getSExtValue() <= 1)
3771 return false;
3772 } else if (!Ty->isVariableArrayType()) {
3773 return false;
3774 }
3775 return true;
3776}
3777
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003778// Warn if the user has made the 'size' argument to strlcpy or strlcat
3779// be the size of the source, instead of the destination.
3780void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3781 IdentifierInfo *FnName) {
3782
3783 // Don't crash if the user has the wrong number of arguments
3784 if (Call->getNumArgs() != 3)
3785 return;
3786
3787 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3788 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3789 const Expr *CompareWithSrc = NULL;
3790
3791 // Look for 'strlcpy(dst, x, sizeof(x))'
3792 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3793 CompareWithSrc = Ex;
3794 else {
3795 // Look for 'strlcpy(dst, x, strlen(x))'
3796 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003797 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003798 && SizeCall->getNumArgs() == 1)
3799 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3800 }
3801 }
3802
3803 if (!CompareWithSrc)
3804 return;
3805
3806 // Determine if the argument to sizeof/strlen is equal to the source
3807 // argument. In principle there's all kinds of things you could do
3808 // here, for instance creating an == expression and evaluating it with
3809 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3810 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3811 if (!SrcArgDRE)
3812 return;
3813
3814 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3815 if (!CompareWithSrcDRE ||
3816 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3817 return;
3818
3819 const Expr *OriginalSizeArg = Call->getArg(2);
3820 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3821 << OriginalSizeArg->getSourceRange() << FnName;
3822
3823 // Output a FIXIT hint if the destination is an array (rather than a
3824 // pointer to an array). This could be enhanced to handle some
3825 // pointers if we know the actual size, like if DstArg is 'array+2'
3826 // we could say 'sizeof(array)-2'.
3827 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00003828 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00003829 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00003830
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003831 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003832 llvm::raw_svector_ostream OS(sizeString);
3833 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003834 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003835 OS << ")";
3836
3837 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3838 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3839 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003840}
3841
Anna Zaksc36bedc2012-02-01 19:08:57 +00003842/// Check if two expressions refer to the same declaration.
3843static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3844 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3845 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3846 return D1->getDecl() == D2->getDecl();
3847 return false;
3848}
3849
3850static const Expr *getStrlenExprArg(const Expr *E) {
3851 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3852 const FunctionDecl *FD = CE->getDirectCallee();
3853 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3854 return 0;
3855 return CE->getArg(0)->IgnoreParenCasts();
3856 }
3857 return 0;
3858}
3859
3860// Warn on anti-patterns as the 'size' argument to strncat.
3861// The correct size argument should look like following:
3862// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3863void Sema::CheckStrncatArguments(const CallExpr *CE,
3864 IdentifierInfo *FnName) {
3865 // Don't crash if the user has the wrong number of arguments.
3866 if (CE->getNumArgs() < 3)
3867 return;
3868 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3869 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3870 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3871
3872 // Identify common expressions, which are wrongly used as the size argument
3873 // to strncat and may lead to buffer overflows.
3874 unsigned PatternType = 0;
3875 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3876 // - sizeof(dst)
3877 if (referToTheSameDecl(SizeOfArg, DstArg))
3878 PatternType = 1;
3879 // - sizeof(src)
3880 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3881 PatternType = 2;
3882 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3883 if (BE->getOpcode() == BO_Sub) {
3884 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3885 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3886 // - sizeof(dst) - strlen(dst)
3887 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3888 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3889 PatternType = 1;
3890 // - sizeof(src) - (anything)
3891 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3892 PatternType = 2;
3893 }
3894 }
3895
3896 if (PatternType == 0)
3897 return;
3898
Anna Zaksafdb0412012-02-03 01:27:37 +00003899 // Generate the diagnostic.
3900 SourceLocation SL = LenArg->getLocStart();
3901 SourceRange SR = LenArg->getSourceRange();
3902 SourceManager &SM = PP.getSourceManager();
3903
3904 // If the function is defined as a builtin macro, do not show macro expansion.
3905 if (SM.isMacroArgExpansion(SL)) {
3906 SL = SM.getSpellingLoc(SL);
3907 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3908 SM.getSpellingLoc(SR.getEnd()));
3909 }
3910
Anna Zaks0f38ace2012-08-08 21:42:23 +00003911 // Check if the destination is an array (rather than a pointer to an array).
3912 QualType DstTy = DstArg->getType();
3913 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3914 Context);
3915 if (!isKnownSizeArray) {
3916 if (PatternType == 1)
3917 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3918 else
3919 Diag(SL, diag::warn_strncat_src_size) << SR;
3920 return;
3921 }
3922
Anna Zaksc36bedc2012-02-01 19:08:57 +00003923 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003924 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003925 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003926 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003927
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003928 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003929 llvm::raw_svector_ostream OS(sizeString);
3930 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003931 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003932 OS << ") - ";
3933 OS << "strlen(";
Richard Smithd1420c62012-08-16 03:56:14 +00003934 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003935 OS << ") - 1";
3936
Anna Zaksafdb0412012-02-03 01:27:37 +00003937 Diag(SL, diag::note_strncat_wrong_size)
3938 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003939}
3940
Ted Kremenek06de2762007-08-17 16:46:58 +00003941//===--- CHECK: Return Address of Stack Variable --------------------------===//
3942
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003943static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3944 Decl *ParentDecl);
3945static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3946 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003947
3948/// CheckReturnStackAddr - Check if a return statement returns the address
3949/// of a stack variable.
3950void
3951Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3952 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003953
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003954 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003955 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003956
3957 // Perform checking for returned stack addresses, local blocks,
3958 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003959 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003960 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003961 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003962 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003963 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003964 }
3965
3966 if (stackE == 0)
3967 return; // Nothing suspicious was found.
3968
3969 SourceLocation diagLoc;
3970 SourceRange diagRange;
3971 if (refVars.empty()) {
3972 diagLoc = stackE->getLocStart();
3973 diagRange = stackE->getSourceRange();
3974 } else {
3975 // We followed through a reference variable. 'stackE' contains the
3976 // problematic expression but we will warn at the return statement pointing
3977 // at the reference variable. We will later display the "trail" of
3978 // reference variables using notes.
3979 diagLoc = refVars[0]->getLocStart();
3980 diagRange = refVars[0]->getSourceRange();
3981 }
3982
3983 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3984 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3985 : diag::warn_ret_stack_addr)
3986 << DR->getDecl()->getDeclName() << diagRange;
3987 } else if (isa<BlockExpr>(stackE)) { // local block.
3988 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3989 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3990 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3991 } else { // local temporary.
3992 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3993 : diag::warn_ret_local_temp_addr)
3994 << diagRange;
3995 }
3996
3997 // Display the "trail" of reference variables that we followed until we
3998 // found the problematic expression using notes.
3999 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4000 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4001 // If this var binds to another reference var, show the range of the next
4002 // var, otherwise the var binds to the problematic expression, in which case
4003 // show the range of the expression.
4004 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4005 : stackE->getSourceRange();
4006 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4007 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00004008 }
4009}
4010
4011/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4012/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004013/// to a location on the stack, a local block, an address of a label, or a
4014/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00004015/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004016/// encounter a subexpression that (1) clearly does not lead to one of the
4017/// above problematic expressions (2) is something we cannot determine leads to
4018/// a problematic expression based on such local checking.
4019///
4020/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4021/// the expression that they point to. Such variables are added to the
4022/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00004023///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00004024/// EvalAddr processes expressions that are pointers that are used as
4025/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004026/// At the base case of the recursion is a check for the above problematic
4027/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00004028///
4029/// This implementation handles:
4030///
4031/// * pointer-to-pointer casts
4032/// * implicit conversions from array references to pointers
4033/// * taking the address of fields
4034/// * arbitrary interplay between "&" and "*" operators
4035/// * pointer arithmetic from an address of a stack variable
4036/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004037static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4038 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004039 if (E->isTypeDependent())
Craig Topperb61c2942013-08-02 05:10:31 +00004040 return NULL;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004041
Ted Kremenek06de2762007-08-17 16:46:58 +00004042 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00004043 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00004044 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004045 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004046 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00004047
Peter Collingbournef111d932011-04-15 00:35:48 +00004048 E = E->IgnoreParens();
4049
Ted Kremenek06de2762007-08-17 16:46:58 +00004050 // Our "symbolic interpreter" is just a dispatch off the currently
4051 // viewed AST node. We then recursively traverse the AST by calling
4052 // EvalAddr and EvalVal appropriately.
4053 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004054 case Stmt::DeclRefExprClass: {
4055 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4056
4057 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4058 // If this is a reference variable, follow through to the expression that
4059 // it points to.
4060 if (V->hasLocalStorage() &&
4061 V->getType()->isReferenceType() && V->hasInit()) {
4062 // Add the reference variable to the "trail".
4063 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004064 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004065 }
4066
4067 return NULL;
4068 }
Ted Kremenek06de2762007-08-17 16:46:58 +00004069
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004070 case Stmt::UnaryOperatorClass: {
4071 // The only unary operator that make sense to handle here
4072 // is AddrOf. All others don't make sense as pointers.
4073 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004074
John McCall2de56d12010-08-25 11:45:40 +00004075 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004076 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004077 else
Ted Kremenek06de2762007-08-17 16:46:58 +00004078 return NULL;
4079 }
Mike Stump1eb44332009-09-09 15:08:12 +00004080
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004081 case Stmt::BinaryOperatorClass: {
4082 // Handle pointer arithmetic. All other binary operators are not valid
4083 // in this context.
4084 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00004085 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00004086
John McCall2de56d12010-08-25 11:45:40 +00004087 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004088 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00004089
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004090 Expr *Base = B->getLHS();
4091
4092 // Determine which argument is the real pointer base. It could be
4093 // the RHS argument instead of the LHS.
4094 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00004095
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004096 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004097 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004098 }
Steve Naroff61f40a22008-09-10 19:17:48 +00004099
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004100 // For conditional operators we need to see if either the LHS or RHS are
4101 // valid DeclRefExpr*s. If one of them is valid, we return it.
4102 case Stmt::ConditionalOperatorClass: {
4103 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004104
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004105 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004106 if (Expr *lhsExpr = C->getLHS()) {
4107 // In C++, we can have a throw-expression, which has 'void' type.
4108 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004109 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004110 return LHS;
4111 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004112
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004113 // In C++, we can have a throw-expression, which has 'void' type.
4114 if (C->getRHS()->getType()->isVoidType())
4115 return NULL;
4116
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004117 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004118 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004119
4120 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00004121 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004122 return E; // local block.
4123 return NULL;
4124
4125 case Stmt::AddrLabelExprClass:
4126 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00004127
John McCall80ee6e82011-11-10 05:35:25 +00004128 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004129 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4130 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00004131
Ted Kremenek54b52742008-08-07 00:49:01 +00004132 // For casts, we need to handle conversions from arrays to
4133 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00004134 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00004135 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00004136 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00004137 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00004138 case Stmt::CXXStaticCastExprClass:
4139 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00004140 case Stmt::CXXConstCastExprClass:
4141 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00004142 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4143 switch (cast<CastExpr>(E)->getCastKind()) {
4144 case CK_BitCast:
4145 case CK_LValueToRValue:
4146 case CK_NoOp:
4147 case CK_BaseToDerived:
4148 case CK_DerivedToBase:
4149 case CK_UncheckedDerivedToBase:
4150 case CK_Dynamic:
4151 case CK_CPointerToObjCPointerCast:
4152 case CK_BlockPointerToObjCPointerCast:
4153 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004154 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00004155
4156 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004157 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00004158
4159 default:
4160 return 0;
4161 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004162 }
Mike Stump1eb44332009-09-09 15:08:12 +00004163
Douglas Gregor03e80032011-06-21 17:03:29 +00004164 case Stmt::MaterializeTemporaryExprClass:
4165 if (Expr *Result = EvalAddr(
4166 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004167 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00004168 return Result;
4169
4170 return E;
4171
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004172 // Everything else: we simply don't reason about them.
4173 default:
4174 return NULL;
4175 }
Ted Kremenek06de2762007-08-17 16:46:58 +00004176}
Mike Stump1eb44332009-09-09 15:08:12 +00004177
Ted Kremenek06de2762007-08-17 16:46:58 +00004178
4179/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4180/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004181static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4182 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004183do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00004184 // We should only be called for evaluating non-pointer expressions, or
4185 // expressions with a pointer type that are not used as references but instead
4186 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00004187
Ted Kremenek06de2762007-08-17 16:46:58 +00004188 // Our "symbolic interpreter" is just a dispatch off the currently
4189 // viewed AST node. We then recursively traverse the AST by calling
4190 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00004191
4192 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00004193 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004194 case Stmt::ImplicitCastExprClass: {
4195 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00004196 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004197 E = IE->getSubExpr();
4198 continue;
4199 }
4200 return NULL;
4201 }
4202
John McCall80ee6e82011-11-10 05:35:25 +00004203 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004204 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00004205
Douglas Gregora2813ce2009-10-23 18:54:35 +00004206 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004207 // When we hit a DeclRefExpr we are looking at code that refers to a
4208 // variable's name. If it's not a reference variable we check if it has
4209 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00004210 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004211
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004212 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4213 // Check if it refers to itself, e.g. "int& i = i;".
4214 if (V == ParentDecl)
4215 return DR;
4216
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004217 if (V->hasLocalStorage()) {
4218 if (!V->getType()->isReferenceType())
4219 return DR;
4220
4221 // Reference variable, follow through to the expression that
4222 // it points to.
4223 if (V->hasInit()) {
4224 // Add the reference variable to the "trail".
4225 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004226 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004227 }
4228 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004229 }
Mike Stump1eb44332009-09-09 15:08:12 +00004230
Ted Kremenek06de2762007-08-17 16:46:58 +00004231 return NULL;
4232 }
Mike Stump1eb44332009-09-09 15:08:12 +00004233
Ted Kremenek06de2762007-08-17 16:46:58 +00004234 case Stmt::UnaryOperatorClass: {
4235 // The only unary operator that make sense to handle here
4236 // is Deref. All others don't resolve to a "name." This includes
4237 // handling all sorts of rvalues passed to a unary operator.
4238 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004239
John McCall2de56d12010-08-25 11:45:40 +00004240 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004241 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004242
4243 return NULL;
4244 }
Mike Stump1eb44332009-09-09 15:08:12 +00004245
Ted Kremenek06de2762007-08-17 16:46:58 +00004246 case Stmt::ArraySubscriptExprClass: {
4247 // Array subscripts are potential references to data on the stack. We
4248 // retrieve the DeclRefExpr* for the array variable if it indeed
4249 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004250 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004251 }
Mike Stump1eb44332009-09-09 15:08:12 +00004252
Ted Kremenek06de2762007-08-17 16:46:58 +00004253 case Stmt::ConditionalOperatorClass: {
4254 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004255 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00004256 ConditionalOperator *C = cast<ConditionalOperator>(E);
4257
Anders Carlsson39073232007-11-30 19:04:31 +00004258 // Handle the GNU extension for missing LHS.
4259 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004260 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00004261 return LHS;
4262
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004263 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004264 }
Mike Stump1eb44332009-09-09 15:08:12 +00004265
Ted Kremenek06de2762007-08-17 16:46:58 +00004266 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00004267 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00004268 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004269
Ted Kremenek06de2762007-08-17 16:46:58 +00004270 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00004271 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00004272 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00004273
4274 // Check whether the member type is itself a reference, in which case
4275 // we're not going to refer to the member, but to what the member refers to.
4276 if (M->getMemberDecl()->getType()->isReferenceType())
4277 return NULL;
4278
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004279 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004280 }
Mike Stump1eb44332009-09-09 15:08:12 +00004281
Douglas Gregor03e80032011-06-21 17:03:29 +00004282 case Stmt::MaterializeTemporaryExprClass:
4283 if (Expr *Result = EvalVal(
4284 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004285 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00004286 return Result;
4287
4288 return E;
4289
Ted Kremenek06de2762007-08-17 16:46:58 +00004290 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004291 // Check that we don't return or take the address of a reference to a
4292 // temporary. This is only useful in C++.
4293 if (!E->isTypeDependent() && E->isRValue())
4294 return E;
4295
4296 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00004297 return NULL;
4298 }
Ted Kremenek68957a92010-08-04 20:01:07 +00004299} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00004300}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004301
4302//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4303
4304/// Check for comparisons of floating point operands using != and ==.
4305/// Issue a warning if these are no self-comparisons, as they are not likely
4306/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00004307void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00004308 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4309 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004310
4311 // Special case: check for x == x (which is OK).
4312 // Do not emit warnings for such cases.
4313 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4314 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4315 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00004316 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004317
4318
Ted Kremenek1b500bb2007-11-29 00:59:04 +00004319 // Special case: check for comparisons against literals that can be exactly
4320 // represented by APFloat. In such cases, do not emit a warning. This
4321 // is a heuristic: often comparison against such literals are used to
4322 // detect if a value in a variable has not changed. This clearly can
4323 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00004324 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4325 if (FLL->isExact())
4326 return;
4327 } else
4328 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4329 if (FLR->isExact())
4330 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004331
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004332 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00004333 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
4334 if (CL->isBuiltinCall())
4335 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004336
David Blaikie980343b2012-07-16 20:47:22 +00004337 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
4338 if (CR->isBuiltinCall())
4339 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004340
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004341 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00004342 Diag(Loc, diag::warn_floatingpoint_eq)
4343 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004344}
John McCallba26e582010-01-04 23:21:16 +00004345
John McCallf2370c92010-01-06 05:24:50 +00004346//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4347//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00004348
John McCallf2370c92010-01-06 05:24:50 +00004349namespace {
John McCallba26e582010-01-04 23:21:16 +00004350
John McCallf2370c92010-01-06 05:24:50 +00004351/// Structure recording the 'active' range of an integer-valued
4352/// expression.
4353struct IntRange {
4354 /// The number of bits active in the int.
4355 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00004356
John McCallf2370c92010-01-06 05:24:50 +00004357 /// True if the int is known not to have negative values.
4358 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00004359
John McCallf2370c92010-01-06 05:24:50 +00004360 IntRange(unsigned Width, bool NonNegative)
4361 : Width(Width), NonNegative(NonNegative)
4362 {}
John McCallba26e582010-01-04 23:21:16 +00004363
John McCall1844a6e2010-11-10 23:38:19 +00004364 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00004365 static IntRange forBoolType() {
4366 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00004367 }
4368
John McCall1844a6e2010-11-10 23:38:19 +00004369 /// Returns the range of an opaque value of the given integral type.
4370 static IntRange forValueOfType(ASTContext &C, QualType T) {
4371 return forValueOfCanonicalType(C,
4372 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00004373 }
4374
John McCall1844a6e2010-11-10 23:38:19 +00004375 /// Returns the range of an opaque value of a canonical integral type.
4376 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00004377 assert(T->isCanonicalUnqualified());
4378
4379 if (const VectorType *VT = dyn_cast<VectorType>(T))
4380 T = VT->getElementType().getTypePtr();
4381 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4382 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00004383
David Majnemerf9eaf982013-06-07 22:07:20 +00004384 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00004385 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemerf9eaf982013-06-07 22:07:20 +00004386 EnumDecl *Enum = ET->getDecl();
4387 if (!Enum->isCompleteDefinition())
4388 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall091f23f2010-11-09 22:22:12 +00004389
David Majnemerf9eaf982013-06-07 22:07:20 +00004390 unsigned NumPositive = Enum->getNumPositiveBits();
4391 unsigned NumNegative = Enum->getNumNegativeBits();
John McCall323ed742010-05-06 08:58:33 +00004392
David Majnemerf9eaf982013-06-07 22:07:20 +00004393 if (NumNegative == 0)
4394 return IntRange(NumPositive, true/*NonNegative*/);
4395 else
4396 return IntRange(std::max(NumPositive + 1, NumNegative),
4397 false/*NonNegative*/);
John McCall323ed742010-05-06 08:58:33 +00004398 }
John McCallf2370c92010-01-06 05:24:50 +00004399
4400 const BuiltinType *BT = cast<BuiltinType>(T);
4401 assert(BT->isInteger());
4402
4403 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4404 }
4405
John McCall1844a6e2010-11-10 23:38:19 +00004406 /// Returns the "target" range of a canonical integral type, i.e.
4407 /// the range of values expressible in the type.
4408 ///
4409 /// This matches forValueOfCanonicalType except that enums have the
4410 /// full range of their type, not the range of their enumerators.
4411 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4412 assert(T->isCanonicalUnqualified());
4413
4414 if (const VectorType *VT = dyn_cast<VectorType>(T))
4415 T = VT->getElementType().getTypePtr();
4416 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4417 T = CT->getElementType().getTypePtr();
4418 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00004419 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00004420
4421 const BuiltinType *BT = cast<BuiltinType>(T);
4422 assert(BT->isInteger());
4423
4424 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4425 }
4426
4427 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004428 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00004429 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00004430 L.NonNegative && R.NonNegative);
4431 }
4432
John McCall1844a6e2010-11-10 23:38:19 +00004433 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004434 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00004435 return IntRange(std::min(L.Width, R.Width),
4436 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00004437 }
4438};
4439
Ted Kremenek0692a192012-01-31 05:37:37 +00004440static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4441 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004442 if (value.isSigned() && value.isNegative())
4443 return IntRange(value.getMinSignedBits(), false);
4444
4445 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00004446 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004447
4448 // isNonNegative() just checks the sign bit without considering
4449 // signedness.
4450 return IntRange(value.getActiveBits(), true);
4451}
4452
Ted Kremenek0692a192012-01-31 05:37:37 +00004453static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4454 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004455 if (result.isInt())
4456 return GetValueRange(C, result.getInt(), MaxWidth);
4457
4458 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00004459 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4460 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4461 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4462 R = IntRange::join(R, El);
4463 }
John McCallf2370c92010-01-06 05:24:50 +00004464 return R;
4465 }
4466
4467 if (result.isComplexInt()) {
4468 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4469 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4470 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00004471 }
4472
4473 // This can happen with lossless casts to intptr_t of "based" lvalues.
4474 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00004475 // FIXME: The only reason we need to pass the type in here is to get
4476 // the sign right on this one case. It would be nice if APValue
4477 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00004478 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004479 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00004480}
John McCallf2370c92010-01-06 05:24:50 +00004481
Eli Friedman09bddcf2013-07-08 20:20:06 +00004482static QualType GetExprType(Expr *E) {
4483 QualType Ty = E->getType();
4484 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4485 Ty = AtomicRHS->getValueType();
4486 return Ty;
4487}
4488
John McCallf2370c92010-01-06 05:24:50 +00004489/// Pseudo-evaluate the given integer expression, estimating the
4490/// range of values it might take.
4491///
4492/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00004493static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004494 E = E->IgnoreParens();
4495
4496 // Try a full evaluation first.
4497 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004498 if (E->EvaluateAsRValue(result, C))
Eli Friedman09bddcf2013-07-08 20:20:06 +00004499 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004500
4501 // I think we only want to look through implicit casts here; if the
4502 // user has an explicit widening cast, we should treat the value as
4503 // being of the new, wider type.
4504 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00004505 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00004506 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4507
Eli Friedman09bddcf2013-07-08 20:20:06 +00004508 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCallf2370c92010-01-06 05:24:50 +00004509
John McCall2de56d12010-08-25 11:45:40 +00004510 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00004511
John McCallf2370c92010-01-06 05:24:50 +00004512 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00004513 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00004514 return OutputTypeRange;
4515
4516 IntRange SubRange
4517 = GetExprRange(C, CE->getSubExpr(),
4518 std::min(MaxWidth, OutputTypeRange.Width));
4519
4520 // Bail out if the subexpr's range is as wide as the cast type.
4521 if (SubRange.Width >= OutputTypeRange.Width)
4522 return OutputTypeRange;
4523
4524 // Otherwise, we take the smaller width, and we're non-negative if
4525 // either the output type or the subexpr is.
4526 return IntRange(SubRange.Width,
4527 SubRange.NonNegative || OutputTypeRange.NonNegative);
4528 }
4529
4530 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4531 // If we can fold the condition, just take that operand.
4532 bool CondResult;
4533 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4534 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4535 : CO->getFalseExpr(),
4536 MaxWidth);
4537
4538 // Otherwise, conservatively merge.
4539 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4540 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4541 return IntRange::join(L, R);
4542 }
4543
4544 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4545 switch (BO->getOpcode()) {
4546
4547 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00004548 case BO_LAnd:
4549 case BO_LOr:
4550 case BO_LT:
4551 case BO_GT:
4552 case BO_LE:
4553 case BO_GE:
4554 case BO_EQ:
4555 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00004556 return IntRange::forBoolType();
4557
John McCall862ff872011-07-13 06:35:24 +00004558 // The type of the assignments is the type of the LHS, so the RHS
4559 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00004560 case BO_MulAssign:
4561 case BO_DivAssign:
4562 case BO_RemAssign:
4563 case BO_AddAssign:
4564 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00004565 case BO_XorAssign:
4566 case BO_OrAssign:
4567 // TODO: bitfields?
Eli Friedman09bddcf2013-07-08 20:20:06 +00004568 return IntRange::forValueOfType(C, GetExprType(E));
John McCallc0cd21d2010-02-23 19:22:29 +00004569
John McCall862ff872011-07-13 06:35:24 +00004570 // Simple assignments just pass through the RHS, which will have
4571 // been coerced to the LHS type.
4572 case BO_Assign:
4573 // TODO: bitfields?
4574 return GetExprRange(C, BO->getRHS(), MaxWidth);
4575
John McCallf2370c92010-01-06 05:24:50 +00004576 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004577 case BO_PtrMemD:
4578 case BO_PtrMemI:
Eli Friedman09bddcf2013-07-08 20:20:06 +00004579 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004580
John McCall60fad452010-01-06 22:07:33 +00004581 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00004582 case BO_And:
4583 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00004584 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4585 GetExprRange(C, BO->getRHS(), MaxWidth));
4586
John McCallf2370c92010-01-06 05:24:50 +00004587 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00004588 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00004589 // ...except that we want to treat '1 << (blah)' as logically
4590 // positive. It's an important idiom.
4591 if (IntegerLiteral *I
4592 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4593 if (I->getValue() == 1) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00004594 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall3aae6092010-04-07 01:14:35 +00004595 return IntRange(R.Width, /*NonNegative*/ true);
4596 }
4597 }
4598 // fallthrough
4599
John McCall2de56d12010-08-25 11:45:40 +00004600 case BO_ShlAssign:
Eli Friedman09bddcf2013-07-08 20:20:06 +00004601 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004602
John McCall60fad452010-01-06 22:07:33 +00004603 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00004604 case BO_Shr:
4605 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00004606 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4607
4608 // If the shift amount is a positive constant, drop the width by
4609 // that much.
4610 llvm::APSInt shift;
4611 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4612 shift.isNonNegative()) {
4613 unsigned zext = shift.getZExtValue();
4614 if (zext >= L.Width)
4615 L.Width = (L.NonNegative ? 0 : 1);
4616 else
4617 L.Width -= zext;
4618 }
4619
4620 return L;
4621 }
4622
4623 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00004624 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00004625 return GetExprRange(C, BO->getRHS(), MaxWidth);
4626
John McCall60fad452010-01-06 22:07:33 +00004627 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00004628 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00004629 if (BO->getLHS()->getType()->isPointerType())
Eli Friedman09bddcf2013-07-08 20:20:06 +00004630 return IntRange::forValueOfType(C, GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004631 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00004632
John McCall00fe7612011-07-14 22:39:48 +00004633 // The width of a division result is mostly determined by the size
4634 // of the LHS.
4635 case BO_Div: {
4636 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00004637 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004638 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4639
4640 // If the divisor is constant, use that.
4641 llvm::APSInt divisor;
4642 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4643 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4644 if (log2 >= L.Width)
4645 L.Width = (L.NonNegative ? 0 : 1);
4646 else
4647 L.Width = std::min(L.Width - log2, MaxWidth);
4648 return L;
4649 }
4650
4651 // Otherwise, just use the LHS's width.
4652 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4653 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4654 }
4655
4656 // The result of a remainder can't be larger than the result of
4657 // either side.
4658 case BO_Rem: {
4659 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00004660 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004661 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4662 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4663
4664 IntRange meet = IntRange::meet(L, R);
4665 meet.Width = std::min(meet.Width, MaxWidth);
4666 return meet;
4667 }
4668
4669 // The default behavior is okay for these.
4670 case BO_Mul:
4671 case BO_Add:
4672 case BO_Xor:
4673 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00004674 break;
4675 }
4676
John McCall00fe7612011-07-14 22:39:48 +00004677 // The default case is to treat the operation as if it were closed
4678 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004679 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4680 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4681 return IntRange::join(L, R);
4682 }
4683
4684 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4685 switch (UO->getOpcode()) {
4686 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004687 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004688 return IntRange::forBoolType();
4689
4690 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004691 case UO_Deref:
4692 case UO_AddrOf: // should be impossible
Eli Friedman09bddcf2013-07-08 20:20:06 +00004693 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004694
4695 default:
4696 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4697 }
4698 }
4699
Ted Kremenek728a1fb2013-10-14 18:55:27 +00004700 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
4701 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
4702
John McCall993f43f2013-05-06 21:39:12 +00004703 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004704 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004705 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004706
Eli Friedman09bddcf2013-07-08 20:20:06 +00004707 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004708}
John McCall51313c32010-01-04 23:31:57 +00004709
Ted Kremenek0692a192012-01-31 05:37:37 +00004710static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00004711 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCall323ed742010-05-06 08:58:33 +00004712}
4713
John McCall51313c32010-01-04 23:31:57 +00004714/// Checks whether the given value, which currently has the given
4715/// source semantics, has the same value when coerced through the
4716/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004717static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4718 const llvm::fltSemantics &Src,
4719 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004720 llvm::APFloat truncated = value;
4721
4722 bool ignored;
4723 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4724 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4725
4726 return truncated.bitwiseIsEqual(value);
4727}
4728
4729/// Checks whether the given value, which currently has the given
4730/// source semantics, has the same value when coerced through the
4731/// target semantics.
4732///
4733/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004734static bool IsSameFloatAfterCast(const APValue &value,
4735 const llvm::fltSemantics &Src,
4736 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004737 if (value.isFloat())
4738 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4739
4740 if (value.isVector()) {
4741 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4742 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4743 return false;
4744 return true;
4745 }
4746
4747 assert(value.isComplexFloat());
4748 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4749 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4750}
4751
Ted Kremenek0692a192012-01-31 05:37:37 +00004752static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004753
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004754static bool IsZero(Sema &S, Expr *E) {
4755 // Suppress cases where we are comparing against an enum constant.
4756 if (const DeclRefExpr *DR =
4757 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4758 if (isa<EnumConstantDecl>(DR->getDecl()))
4759 return false;
4760
4761 // Suppress cases where the '0' value is expanded from a macro.
4762 if (E->getLocStart().isMacroID())
4763 return false;
4764
John McCall323ed742010-05-06 08:58:33 +00004765 llvm::APSInt Value;
4766 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4767}
4768
John McCall372e1032010-10-06 00:25:24 +00004769static bool HasEnumType(Expr *E) {
4770 // Strip off implicit integral promotions.
4771 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004772 if (ICE->getCastKind() != CK_IntegralCast &&
4773 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004774 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004775 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004776 }
4777
4778 return E->getType()->isEnumeralType();
4779}
4780
Ted Kremenek0692a192012-01-31 05:37:37 +00004781static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004782 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004783 if (E->isValueDependent())
4784 return;
4785
John McCall2de56d12010-08-25 11:45:40 +00004786 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004787 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004788 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004789 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004790 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004791 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004792 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004793 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004794 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004795 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004796 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004797 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004798 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004799 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004800 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004801 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4802 }
4803}
4804
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004805static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004806 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004807 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004808 bool RhsConstant) {
Richard Trieu526e6272012-11-14 22:50:24 +00004809 // 0 values are handled later by CheckTrivialUnsignedComparison().
4810 if (Value == 0)
4811 return;
4812
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004813 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004814 QualType OtherT = Other->getType();
4815 QualType ConstantT = Constant->getType();
Richard Trieu526e6272012-11-14 22:50:24 +00004816 QualType CommonT = E->getLHS()->getType();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004817 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004818 return;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004819 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004820 && "comparison with non-integer type");
Richard Trieu526e6272012-11-14 22:50:24 +00004821
4822 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu526e6272012-11-14 22:50:24 +00004823 bool CommonSigned = CommonT->isSignedIntegerType();
4824
4825 bool EqualityOnly = false;
4826
4827 // TODO: Investigate using GetExprRange() to get tighter bounds on
4828 // on the bit ranges.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004829 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu526e6272012-11-14 22:50:24 +00004830 unsigned OtherWidth = OtherRange.Width;
4831
4832 if (CommonSigned) {
4833 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedmand87de7b2012-11-30 23:09:29 +00004834 if (!OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004835 // Check that the constant is representable in type OtherT.
4836 if (ConstantSigned) {
4837 if (OtherWidth >= Value.getMinSignedBits())
4838 return;
4839 } else { // !ConstantSigned
4840 if (OtherWidth >= Value.getActiveBits() + 1)
4841 return;
4842 }
4843 } else { // !OtherSigned
4844 // Check that the constant is representable in type OtherT.
4845 // Negative values are out of range.
4846 if (ConstantSigned) {
4847 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4848 return;
4849 } else { // !ConstantSigned
4850 if (OtherWidth >= Value.getActiveBits())
4851 return;
4852 }
4853 }
4854 } else { // !CommonSigned
Eli Friedmand87de7b2012-11-30 23:09:29 +00004855 if (OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004856 if (OtherWidth >= Value.getActiveBits())
4857 return;
Eli Friedmand87de7b2012-11-30 23:09:29 +00004858 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu526e6272012-11-14 22:50:24 +00004859 // Check to see if the constant is representable in OtherT.
4860 if (OtherWidth > Value.getActiveBits())
4861 return;
4862 // Check to see if the constant is equivalent to a negative value
4863 // cast to CommonT.
4864 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu5d1cf4f2012-11-15 03:43:50 +00004865 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu526e6272012-11-14 22:50:24 +00004866 return;
4867 // The constant value rests between values that OtherT can represent after
4868 // conversion. Relational comparison still works, but equality
4869 // comparisons will be tautological.
4870 EqualityOnly = true;
4871 } else { // OtherSigned && ConstantSigned
4872 assert(0 && "Two signed types converted to unsigned types.");
4873 }
4874 }
4875
4876 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4877
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004878 bool IsTrue = true;
Richard Trieu526e6272012-11-14 22:50:24 +00004879 if (op == BO_EQ || op == BO_NE) {
4880 IsTrue = op == BO_NE;
4881 } else if (EqualityOnly) {
4882 return;
4883 } else if (RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004884 if (op == BO_GT || op == BO_GE)
Richard Trieu526e6272012-11-14 22:50:24 +00004885 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004886 else // op == BO_LT || op == BO_LE
Richard Trieu526e6272012-11-14 22:50:24 +00004887 IsTrue = PositiveConstant;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004888 } else {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004889 if (op == BO_LT || op == BO_LE)
Richard Trieu526e6272012-11-14 22:50:24 +00004890 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004891 else // op == BO_GT || op == BO_GE
Richard Trieu526e6272012-11-14 22:50:24 +00004892 IsTrue = PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004893 }
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004894
4895 // If this is a comparison to an enum constant, include that
4896 // constant in the diagnostic.
4897 const EnumConstantDecl *ED = 0;
4898 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
4899 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
4900
4901 SmallString<64> PrettySourceValue;
4902 llvm::raw_svector_ostream OS(PrettySourceValue);
4903 if (ED)
Ted Kremenek9de50942013-03-15 22:02:46 +00004904 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004905 else
4906 OS << Value;
4907
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004908 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004909 << OS.str() << OtherT << IsTrue
Richard Trieu526e6272012-11-14 22:50:24 +00004910 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004911}
4912
John McCall323ed742010-05-06 08:58:33 +00004913/// Analyze the operands of the given comparison. Implements the
4914/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004915static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004916 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4917 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004918}
John McCall51313c32010-01-04 23:31:57 +00004919
John McCallba26e582010-01-04 23:21:16 +00004920/// \brief Implements -Wsign-compare.
4921///
Richard Trieudd225092011-09-15 21:56:47 +00004922/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004923static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004924 // The type the comparison is being performed in.
4925 QualType T = E->getLHS()->getType();
4926 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4927 && "comparison with mismatched types");
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00004928 if (E->isValueDependent())
4929 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004930
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004931 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4932 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004933
4934 bool IsComparisonConstant = false;
4935
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004936 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004937 // of 'true' or 'false'.
4938 if (T->isIntegralType(S.Context)) {
4939 llvm::APSInt RHSValue;
4940 bool IsRHSIntegralLiteral =
4941 RHS->isIntegerConstantExpr(RHSValue, S.Context);
4942 llvm::APSInt LHSValue;
4943 bool IsLHSIntegralLiteral =
4944 LHS->isIntegerConstantExpr(LHSValue, S.Context);
4945 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4946 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4947 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4948 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4949 else
4950 IsComparisonConstant =
4951 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004952 } else if (!T->hasUnsignedIntegerRepresentation())
4953 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004954
John McCall323ed742010-05-06 08:58:33 +00004955 // We don't do anything special if this isn't an unsigned integral
4956 // comparison: we're only interested in integral comparisons, and
4957 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004958 //
4959 // We also don't care about value-dependent expressions or expressions
4960 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004961 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00004962 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004963
John McCall323ed742010-05-06 08:58:33 +00004964 // Check to see if one of the (unmodified) operands is of different
4965 // signedness.
4966 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004967 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4968 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004969 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004970 signedOperand = LHS;
4971 unsignedOperand = RHS;
4972 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4973 signedOperand = RHS;
4974 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004975 } else {
John McCall323ed742010-05-06 08:58:33 +00004976 CheckTrivialUnsignedComparison(S, E);
4977 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004978 }
4979
John McCall323ed742010-05-06 08:58:33 +00004980 // Otherwise, calculate the effective range of the signed operand.
4981 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004982
John McCall323ed742010-05-06 08:58:33 +00004983 // Go ahead and analyze implicit conversions in the operands. Note
4984 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004985 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4986 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004987
John McCall323ed742010-05-06 08:58:33 +00004988 // If the signed range is non-negative, -Wsign-compare won't fire,
4989 // but we should still check for comparisons which are always true
4990 // or false.
4991 if (signedRange.NonNegative)
4992 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004993
4994 // For (in)equality comparisons, if the unsigned operand is a
4995 // constant which cannot collide with a overflowed signed operand,
4996 // then reinterpreting the signed operand as unsigned will not
4997 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00004998 if (E->isEqualityOp()) {
4999 unsigned comparisonWidth = S.Context.getIntWidth(T);
5000 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00005001
John McCall323ed742010-05-06 08:58:33 +00005002 // We should never be unable to prove that the unsigned operand is
5003 // non-negative.
5004 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5005
5006 if (unsignedRange.Width < comparisonWidth)
5007 return;
5008 }
5009
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00005010 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5011 S.PDiag(diag::warn_mixed_sign_comparison)
5012 << LHS->getType() << RHS->getType()
5013 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00005014}
5015
John McCall15d7d122010-11-11 03:21:53 +00005016/// Analyzes an attempt to assign the given value to a bitfield.
5017///
5018/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00005019static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5020 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00005021 assert(Bitfield->isBitField());
5022 if (Bitfield->isInvalidDecl())
5023 return false;
5024
John McCall91b60142010-11-11 05:33:51 +00005025 // White-list bool bitfields.
5026 if (Bitfield->getType()->isBooleanType())
5027 return false;
5028
Douglas Gregor46ff3032011-02-04 13:09:01 +00005029 // Ignore value- or type-dependent expressions.
5030 if (Bitfield->getBitWidth()->isValueDependent() ||
5031 Bitfield->getBitWidth()->isTypeDependent() ||
5032 Init->isValueDependent() ||
5033 Init->isTypeDependent())
5034 return false;
5035
John McCall15d7d122010-11-11 03:21:53 +00005036 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5037
Richard Smith80d4b552011-12-28 19:48:30 +00005038 llvm::APSInt Value;
5039 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00005040 return false;
5041
John McCall15d7d122010-11-11 03:21:53 +00005042 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005043 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00005044
5045 if (OriginalWidth <= FieldWidth)
5046 return false;
5047
Eli Friedman3a643af2012-01-26 23:11:39 +00005048 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00005049 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00005050 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00005051
Eli Friedman3a643af2012-01-26 23:11:39 +00005052 // Check whether the stored value is equal to the original value.
5053 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00005054 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00005055 return false;
5056
Eli Friedman3a643af2012-01-26 23:11:39 +00005057 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00005058 // therefore don't strictly fit into a signed bitfield of width 1.
5059 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00005060 return false;
5061
John McCall15d7d122010-11-11 03:21:53 +00005062 std::string PrettyValue = Value.toString(10);
5063 std::string PrettyTrunc = TruncatedValue.toString(10);
5064
5065 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5066 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5067 << Init->getSourceRange();
5068
5069 return true;
5070}
5071
John McCallbeb22aa2010-11-09 23:24:47 +00005072/// Analyze the given simple or compound assignment for warning-worthy
5073/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00005074static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00005075 // Just recurse on the LHS.
5076 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5077
5078 // We want to recurse on the RHS as normal unless we're assigning to
5079 // a bitfield.
John McCall993f43f2013-05-06 21:39:12 +00005080 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005081 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall15d7d122010-11-11 03:21:53 +00005082 E->getOperatorLoc())) {
5083 // Recurse, ignoring any implicit conversions on the RHS.
5084 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5085 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00005086 }
5087 }
5088
5089 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5090}
5091
John McCall51313c32010-01-04 23:31:57 +00005092/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00005093static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00005094 SourceLocation CContext, unsigned diag,
5095 bool pruneControlFlow = false) {
5096 if (pruneControlFlow) {
5097 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5098 S.PDiag(diag)
5099 << SourceType << T << E->getSourceRange()
5100 << SourceRange(CContext));
5101 return;
5102 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005103 S.Diag(E->getExprLoc(), diag)
5104 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5105}
5106
Chandler Carruthe1b02e02011-04-05 06:47:57 +00005107/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00005108static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00005109 SourceLocation CContext, unsigned diag,
5110 bool pruneControlFlow = false) {
5111 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00005112}
5113
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005114/// Diagnose an implicit cast from a literal expression. Does not warn when the
5115/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00005116void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5117 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005118 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00005119 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005120 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00005121 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5122 T->hasUnsignedIntegerRepresentation());
5123 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00005124 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005125 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00005126 return;
5127
Eli Friedman4e1a82c2013-08-29 23:44:43 +00005128 // FIXME: Force the precision of the source value down so we don't print
5129 // digits which are usually useless (we don't really care here if we
5130 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5131 // would automatically print the shortest representation, but it's a bit
5132 // tricky to implement.
David Blaikiebe0ee872012-05-15 16:56:36 +00005133 SmallString<16> PrettySourceValue;
Eli Friedman4e1a82c2013-08-29 23:44:43 +00005134 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5135 precision = (precision * 59 + 195) / 196;
5136 Value.toString(PrettySourceValue, precision);
5137
David Blaikiede7e7b82012-05-15 17:18:27 +00005138 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00005139 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5140 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5141 else
David Blaikiede7e7b82012-05-15 17:18:27 +00005142 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00005143
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005144 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00005145 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5146 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00005147}
5148
John McCall091f23f2010-11-09 22:22:12 +00005149std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5150 if (!Range.Width) return "0";
5151
5152 llvm::APSInt ValueInRange = Value;
5153 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00005154 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00005155 return ValueInRange.toString(10);
5156}
5157
Hans Wennborg88617a22012-08-28 15:44:30 +00005158static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5159 if (!isa<ImplicitCastExpr>(Ex))
5160 return false;
5161
5162 Expr *InnerE = Ex->IgnoreParenImpCasts();
5163 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5164 const Type *Source =
5165 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5166 if (Target->isDependentType())
5167 return false;
5168
5169 const BuiltinType *FloatCandidateBT =
5170 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5171 const Type *BoolCandidateType = ToBool ? Target : Source;
5172
5173 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5174 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5175}
5176
5177void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5178 SourceLocation CC) {
5179 unsigned NumArgs = TheCall->getNumArgs();
5180 for (unsigned i = 0; i < NumArgs; ++i) {
5181 Expr *CurrA = TheCall->getArg(i);
5182 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5183 continue;
5184
5185 bool IsSwapped = ((i > 0) &&
5186 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5187 IsSwapped |= ((i < (NumArgs - 1)) &&
5188 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5189 if (IsSwapped) {
5190 // Warn on this floating-point to bool conversion.
5191 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5192 CurrA->getType(), CC,
5193 diag::warn_impcast_floating_point_to_bool);
5194 }
5195 }
5196}
5197
John McCall323ed742010-05-06 08:58:33 +00005198void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005199 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00005200 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00005201
John McCall323ed742010-05-06 08:58:33 +00005202 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5203 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5204 if (Source == Target) return;
5205 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00005206
Chandler Carruth108f7562011-07-26 05:40:03 +00005207 // If the conversion context location is invalid don't complain. We also
5208 // don't want to emit a warning if the issue occurs from the expansion of
5209 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5210 // delay this check as long as possible. Once we detect we are in that
5211 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00005212 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00005213 return;
5214
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005215 // Diagnose implicit casts to bool.
5216 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5217 if (isa<StringLiteral>(E))
5218 // Warn on string literal to bool. Checks for string literals in logical
5219 // expressions, for instances, assert(0 && "error here"), is prevented
5220 // by a check in AnalyzeImplicitConversions().
5221 return DiagnoseImpCast(S, E, T, CC,
5222 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00005223 if (Source->isFunctionType()) {
5224 // Warn on function to bool. Checks free functions and static member
5225 // functions. Weakly imported functions are excluded from the check,
5226 // since it's common to test their value to check whether the linker
5227 // found a definition for them.
5228 ValueDecl *D = 0;
5229 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
5230 D = R->getDecl();
5231 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
5232 D = M->getMemberDecl();
5233 }
5234
5235 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00005236 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
5237 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
5238 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00005239 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
5240 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
5241 QualType ReturnType;
5242 UnresolvedSet<4> NonTemplateOverloads;
David Blaikiec8fa5252013-06-21 23:54:45 +00005243 S.tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
David Blaikie2def7732011-12-09 21:42:37 +00005244 if (!ReturnType.isNull()
5245 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
5246 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
5247 << FixItHint::CreateInsertion(
5248 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00005249 return;
5250 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00005251 }
5252 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005253 }
John McCall51313c32010-01-04 23:31:57 +00005254
5255 // Strip vector types.
5256 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005257 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005258 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005259 return;
John McCallb4eb64d2010-10-08 02:01:28 +00005260 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005261 }
Chris Lattnerb792b302011-06-14 04:51:15 +00005262
5263 // If the vector cast is cast between two vectors of the same size, it is
5264 // a bitcast, not a conversion.
5265 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5266 return;
John McCall51313c32010-01-04 23:31:57 +00005267
5268 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5269 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5270 }
5271
5272 // Strip complex types.
5273 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005274 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005275 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005276 return;
5277
John McCallb4eb64d2010-10-08 02:01:28 +00005278 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005279 }
John McCall51313c32010-01-04 23:31:57 +00005280
5281 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5282 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5283 }
5284
5285 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5286 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5287
5288 // If the source is floating point...
5289 if (SourceBT && SourceBT->isFloatingPoint()) {
5290 // ...and the target is floating point...
5291 if (TargetBT && TargetBT->isFloatingPoint()) {
5292 // ...then warn if we're dropping FP rank.
5293
5294 // Builtin FP kinds are ordered by increasing FP rank.
5295 if (SourceBT->getKind() > TargetBT->getKind()) {
5296 // Don't warn about float constants that are precisely
5297 // representable in the target type.
5298 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00005299 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00005300 // Value might be a float, a float vector, or a float complex.
5301 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00005302 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5303 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00005304 return;
5305 }
5306
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005307 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005308 return;
5309
John McCallb4eb64d2010-10-08 02:01:28 +00005310 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00005311 }
5312 return;
5313 }
5314
Ted Kremenekef9ff882011-03-10 20:03:42 +00005315 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00005316 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005317 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005318 return;
5319
Chandler Carrutha5b93322011-02-17 11:05:49 +00005320 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00005321 // We also want to warn on, e.g., "int i = -1.234"
5322 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5323 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5324 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5325
Chandler Carruthf65076e2011-04-10 08:36:24 +00005326 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5327 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00005328 } else {
5329 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5330 }
5331 }
John McCall51313c32010-01-04 23:31:57 +00005332
Hans Wennborg88617a22012-08-28 15:44:30 +00005333 // If the target is bool, warn if expr is a function or method call.
5334 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5335 isa<CallExpr>(E)) {
5336 // Check last argument of function call to see if it is an
5337 // implicit cast from a type matching the type the result
5338 // is being cast to.
5339 CallExpr *CEx = cast<CallExpr>(E);
5340 unsigned NumArgs = CEx->getNumArgs();
5341 if (NumArgs > 0) {
5342 Expr *LastA = CEx->getArg(NumArgs - 1);
5343 Expr *InnerE = LastA->IgnoreParenImpCasts();
5344 const Type *InnerType =
5345 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5346 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5347 // Warn on this floating-point to bool conversion
5348 DiagnoseImpCast(S, E, T, CC,
5349 diag::warn_impcast_floating_point_to_bool);
5350 }
5351 }
5352 }
John McCall51313c32010-01-04 23:31:57 +00005353 return;
5354 }
5355
Richard Trieu1838ca52011-05-29 19:59:02 +00005356 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00005357 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiee81b43b2012-11-08 00:41:20 +00005358 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikie896c7dd2013-02-16 00:56:22 +00005359 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieb1360492012-03-16 20:30:12 +00005360 SourceLocation Loc = E->getSourceRange().getBegin();
5361 if (Loc.isMacroID())
5362 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00005363 if (!Loc.isMacroID() || CC.isMacroID())
5364 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5365 << T << clang::SourceRange(CC)
Richard Smith8adf8372013-09-20 00:27:40 +00005366 << FixItHint::CreateReplacement(Loc,
5367 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieu1838ca52011-05-29 19:59:02 +00005368 }
5369
David Blaikieb26331b2012-06-19 21:19:06 +00005370 if (!Source->isIntegerType() || !Target->isIntegerType())
5371 return;
5372
David Blaikiebe0ee872012-05-15 16:56:36 +00005373 // TODO: remove this early return once the false positives for constant->bool
5374 // in templates, macros, etc, are reduced or removed.
5375 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5376 return;
5377
John McCall323ed742010-05-06 08:58:33 +00005378 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00005379 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00005380
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005381 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer25ffbef2013-03-28 19:07:11 +00005382 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005383 // TODO: this should happen for bitfield stores, too.
5384 llvm::APSInt Value(32);
5385 if (E->isIntegerConstantExpr(Value, S.Context)) {
5386 if (S.SourceMgr.isInSystemMacro(CC))
5387 return;
5388
John McCall091f23f2010-11-09 22:22:12 +00005389 std::string PrettySourceValue = Value.toString(10);
5390 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005391
Ted Kremenek5e745da2011-10-22 02:37:33 +00005392 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5393 S.PDiag(diag::warn_impcast_integer_precision_constant)
5394 << PrettySourceValue << PrettyTargetValue
5395 << E->getType() << T << E->getSourceRange()
5396 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00005397 return;
5398 }
5399
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005400 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5401 if (S.SourceMgr.isInSystemMacro(CC))
5402 return;
5403
David Blaikie37050842012-04-12 22:40:54 +00005404 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00005405 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5406 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00005407 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00005408 }
5409
5410 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5411 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5412 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005413
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005414 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005415 return;
5416
John McCall323ed742010-05-06 08:58:33 +00005417 unsigned DiagID = diag::warn_impcast_integer_sign;
5418
5419 // Traditionally, gcc has warned about this under -Wsign-compare.
5420 // We also want to warn about it in -Wconversion.
5421 // So if -Wconversion is off, use a completely identical diagnostic
5422 // in the sign-compare group.
5423 // The conditional-checking code will
5424 if (ICContext) {
5425 DiagID = diag::warn_impcast_integer_sign_conditional;
5426 *ICContext = true;
5427 }
5428
John McCallb4eb64d2010-10-08 02:01:28 +00005429 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00005430 }
5431
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005432 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005433 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5434 // type, to give us better diagnostics.
5435 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00005436 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005437 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5438 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5439 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5440 SourceType = S.Context.getTypeDeclType(Enum);
5441 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5442 }
5443 }
5444
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005445 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5446 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall83972f12013-03-09 00:54:27 +00005447 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5448 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00005449 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005450 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005451 return;
5452
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005453 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005454 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005455 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005456
John McCall51313c32010-01-04 23:31:57 +00005457 return;
5458}
5459
David Blaikie9fb1ac52012-05-15 21:57:38 +00005460void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5461 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00005462
5463void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00005464 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00005465 E = E->IgnoreParenImpCasts();
5466
5467 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00005468 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00005469
John McCallb4eb64d2010-10-08 02:01:28 +00005470 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005471 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005472 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00005473 return;
5474}
5475
David Blaikie9fb1ac52012-05-15 21:57:38 +00005476void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5477 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00005478 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00005479
5480 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00005481 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5482 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005483
5484 // If -Wconversion would have warned about either of the candidates
5485 // for a signedness conversion to the context type...
5486 if (!Suspicious) return;
5487
5488 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005489 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5490 CC))
John McCall323ed742010-05-06 08:58:33 +00005491 return;
5492
John McCall323ed742010-05-06 08:58:33 +00005493 // ...then check whether it would have warned about either of the
5494 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00005495 if (E->getType() == T) return;
5496
5497 Suspicious = false;
5498 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5499 E->getType(), CC, &Suspicious);
5500 if (!Suspicious)
5501 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00005502 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005503}
5504
5505/// AnalyzeImplicitConversions - Find and report any interesting
5506/// implicit conversions in the given expression. There are a couple
5507/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005508void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005509 QualType T = OrigE->getType();
5510 Expr *E = OrigE->IgnoreParenImpCasts();
5511
Douglas Gregorf8b6e152011-10-10 17:38:18 +00005512 if (E->isTypeDependent() || E->isValueDependent())
5513 return;
5514
John McCall323ed742010-05-06 08:58:33 +00005515 // For conditional operators, we analyze the arguments as if they
5516 // were being fed directly into the output.
5517 if (isa<ConditionalOperator>(E)) {
5518 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00005519 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00005520 return;
5521 }
5522
Hans Wennborg88617a22012-08-28 15:44:30 +00005523 // Check implicit argument conversions for function calls.
5524 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5525 CheckImplicitArgumentConversions(S, Call, CC);
5526
John McCall323ed742010-05-06 08:58:33 +00005527 // Go ahead and check any implicit conversions we might have skipped.
5528 // The non-canonical typecheck is just an optimization;
5529 // CheckImplicitConversion will filter out dead implicit conversions.
5530 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005531 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00005532
5533 // Now continue drilling into this expression.
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005534
5535 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005536 if (POE->getResultExpr())
5537 E = POE->getResultExpr();
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005538 }
5539
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005540 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5541 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5542
John McCall323ed742010-05-06 08:58:33 +00005543 // Skip past explicit casts.
5544 if (isa<ExplicitCastExpr>(E)) {
5545 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00005546 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005547 }
5548
John McCallbeb22aa2010-11-09 23:24:47 +00005549 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5550 // Do a somewhat different check with comparison operators.
5551 if (BO->isComparisonOp())
5552 return AnalyzeComparison(S, BO);
5553
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005554 // And with simple assignments.
5555 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00005556 return AnalyzeAssignment(S, BO);
5557 }
John McCall323ed742010-05-06 08:58:33 +00005558
5559 // These break the otherwise-useful invariant below. Fortunately,
5560 // we don't really need to recurse into them, because any internal
5561 // expressions should have been analyzed already when they were
5562 // built into statements.
5563 if (isa<StmtExpr>(E)) return;
5564
5565 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005566 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00005567
5568 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00005569 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005570 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5571 bool IsLogicalOperator = BO && BO->isLogicalOp();
5572 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00005573 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00005574 if (!ChildExpr)
5575 continue;
5576
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005577 if (IsLogicalOperator &&
5578 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5579 // Ignore checking string literals that are in logical operators.
5580 continue;
5581 AnalyzeImplicitConversions(S, ChildExpr, CC);
5582 }
John McCall323ed742010-05-06 08:58:33 +00005583}
5584
5585} // end anonymous namespace
5586
5587/// Diagnoses "dangerous" implicit conversions within the given
5588/// expression (which is a full expression). Implements -Wconversion
5589/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005590///
5591/// \param CC the "context" location of the implicit conversion, i.e.
5592/// the most location of the syntactic entity requiring the implicit
5593/// conversion
5594void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005595 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00005596 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00005597 return;
5598
5599 // Don't diagnose for value- or type-dependent expressions.
5600 if (E->isTypeDependent() || E->isValueDependent())
5601 return;
5602
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005603 // Check for array bounds violations in cases where the check isn't triggered
5604 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5605 // ArraySubscriptExpr is on the RHS of a variable initialization.
5606 CheckArrayAccess(E);
5607
John McCallb4eb64d2010-10-08 02:01:28 +00005608 // This is not the right CC for (e.g.) a variable initialization.
5609 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005610}
5611
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005612/// Diagnose when expression is an integer constant expression and its evaluation
5613/// results in integer overflow
5614void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanian1fd8d462013-03-15 20:47:07 +00005615 if (isa<BinaryOperator>(E->IgnoreParens())) {
Robert Wilhelme7205c02013-08-10 12:33:24 +00005616 SmallVector<PartialDiagnosticAt, 4> Diags;
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005617 E->EvaluateForOverflow(Context, &Diags);
5618 }
5619}
5620
Richard Smith6c3af3d2013-01-17 01:17:56 +00005621namespace {
5622/// \brief Visitor for expressions which looks for unsequenced operations on the
5623/// same object.
5624class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smith0c0b3902013-06-30 10:40:20 +00005625 typedef EvaluatedExprVisitor<SequenceChecker> Base;
5626
Richard Smith6c3af3d2013-01-17 01:17:56 +00005627 /// \brief A tree of sequenced regions within an expression. Two regions are
5628 /// unsequenced if one is an ancestor or a descendent of the other. When we
5629 /// finish processing an expression with sequencing, such as a comma
5630 /// expression, we fold its tree nodes into its parent, since they are
5631 /// unsequenced with respect to nodes we will visit later.
5632 class SequenceTree {
5633 struct Value {
5634 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5635 unsigned Parent : 31;
5636 bool Merged : 1;
5637 };
Robert Wilhelme7205c02013-08-10 12:33:24 +00005638 SmallVector<Value, 8> Values;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005639
5640 public:
5641 /// \brief A region within an expression which may be sequenced with respect
5642 /// to some other region.
5643 class Seq {
5644 explicit Seq(unsigned N) : Index(N) {}
5645 unsigned Index;
5646 friend class SequenceTree;
5647 public:
5648 Seq() : Index(0) {}
5649 };
5650
5651 SequenceTree() { Values.push_back(Value(0)); }
5652 Seq root() const { return Seq(0); }
5653
5654 /// \brief Create a new sequence of operations, which is an unsequenced
5655 /// subset of \p Parent. This sequence of operations is sequenced with
5656 /// respect to other children of \p Parent.
5657 Seq allocate(Seq Parent) {
5658 Values.push_back(Value(Parent.Index));
5659 return Seq(Values.size() - 1);
5660 }
5661
5662 /// \brief Merge a sequence of operations into its parent.
5663 void merge(Seq S) {
5664 Values[S.Index].Merged = true;
5665 }
5666
5667 /// \brief Determine whether two operations are unsequenced. This operation
5668 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5669 /// should have been merged into its parent as appropriate.
5670 bool isUnsequenced(Seq Cur, Seq Old) {
5671 unsigned C = representative(Cur.Index);
5672 unsigned Target = representative(Old.Index);
5673 while (C >= Target) {
5674 if (C == Target)
5675 return true;
5676 C = Values[C].Parent;
5677 }
5678 return false;
5679 }
5680
5681 private:
5682 /// \brief Pick a representative for a sequence.
5683 unsigned representative(unsigned K) {
5684 if (Values[K].Merged)
5685 // Perform path compression as we go.
5686 return Values[K].Parent = representative(Values[K].Parent);
5687 return K;
5688 }
5689 };
5690
5691 /// An object for which we can track unsequenced uses.
5692 typedef NamedDecl *Object;
5693
5694 /// Different flavors of object usage which we track. We only track the
5695 /// least-sequenced usage of each kind.
5696 enum UsageKind {
5697 /// A read of an object. Multiple unsequenced reads are OK.
5698 UK_Use,
5699 /// A modification of an object which is sequenced before the value
Richard Smith418dd3e2013-06-26 23:16:51 +00005700 /// computation of the expression, such as ++n in C++.
Richard Smith6c3af3d2013-01-17 01:17:56 +00005701 UK_ModAsValue,
5702 /// A modification of an object which is not sequenced before the value
5703 /// computation of the expression, such as n++.
5704 UK_ModAsSideEffect,
5705
5706 UK_Count = UK_ModAsSideEffect + 1
5707 };
5708
5709 struct Usage {
5710 Usage() : Use(0), Seq() {}
5711 Expr *Use;
5712 SequenceTree::Seq Seq;
5713 };
5714
5715 struct UsageInfo {
5716 UsageInfo() : Diagnosed(false) {}
5717 Usage Uses[UK_Count];
5718 /// Have we issued a diagnostic for this variable already?
5719 bool Diagnosed;
5720 };
5721 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5722
5723 Sema &SemaRef;
5724 /// Sequenced regions within the expression.
5725 SequenceTree Tree;
5726 /// Declaration modifications and references which we have seen.
5727 UsageInfoMap UsageMap;
5728 /// The region we are currently within.
5729 SequenceTree::Seq Region;
5730 /// Filled in with declarations which were modified as a side-effect
5731 /// (that is, post-increment operations).
Robert Wilhelme7205c02013-08-10 12:33:24 +00005732 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smith1a2dcd52013-01-17 23:18:09 +00005733 /// Expressions to check later. We defer checking these to reduce
5734 /// stack usage.
Robert Wilhelme7205c02013-08-10 12:33:24 +00005735 SmallVectorImpl<Expr *> &WorkList;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005736
5737 /// RAII object wrapping the visitation of a sequenced subexpression of an
5738 /// expression. At the end of this process, the side-effects of the evaluation
5739 /// become sequenced with respect to the value computation of the result, so
5740 /// we downgrade any UK_ModAsSideEffect within the evaluation to
5741 /// UK_ModAsValue.
5742 struct SequencedSubexpression {
5743 SequencedSubexpression(SequenceChecker &Self)
5744 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5745 Self.ModAsSideEffect = &ModAsSideEffect;
5746 }
5747 ~SequencedSubexpression() {
5748 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5749 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5750 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5751 Self.addUsage(U, ModAsSideEffect[I].first,
5752 ModAsSideEffect[I].second.Use, UK_ModAsValue);
5753 }
5754 Self.ModAsSideEffect = OldModAsSideEffect;
5755 }
5756
5757 SequenceChecker &Self;
Robert Wilhelme7205c02013-08-10 12:33:24 +00005758 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5759 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005760 };
5761
Richard Smith67470052013-06-20 22:21:56 +00005762 /// RAII object wrapping the visitation of a subexpression which we might
5763 /// choose to evaluate as a constant. If any subexpression is evaluated and
5764 /// found to be non-constant, this allows us to suppress the evaluation of
5765 /// the outer expression.
5766 class EvaluationTracker {
5767 public:
5768 EvaluationTracker(SequenceChecker &Self)
5769 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
5770 Self.EvalTracker = this;
5771 }
5772 ~EvaluationTracker() {
5773 Self.EvalTracker = Prev;
5774 if (Prev)
5775 Prev->EvalOK &= EvalOK;
5776 }
5777
5778 bool evaluate(const Expr *E, bool &Result) {
5779 if (!EvalOK || E->isValueDependent())
5780 return false;
5781 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
5782 return EvalOK;
5783 }
5784
5785 private:
5786 SequenceChecker &Self;
5787 EvaluationTracker *Prev;
5788 bool EvalOK;
5789 } *EvalTracker;
5790
Richard Smith6c3af3d2013-01-17 01:17:56 +00005791 /// \brief Find the object which is produced by the specified expression,
5792 /// if any.
5793 Object getObject(Expr *E, bool Mod) const {
5794 E = E->IgnoreParenCasts();
5795 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5796 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5797 return getObject(UO->getSubExpr(), Mod);
5798 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5799 if (BO->getOpcode() == BO_Comma)
5800 return getObject(BO->getRHS(), Mod);
5801 if (Mod && BO->isAssignmentOp())
5802 return getObject(BO->getLHS(), Mod);
5803 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5804 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5805 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5806 return ME->getMemberDecl();
5807 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5808 // FIXME: If this is a reference, map through to its value.
5809 return DRE->getDecl();
5810 return 0;
5811 }
5812
5813 /// \brief Note that an object was modified or used by an expression.
5814 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5815 Usage &U = UI.Uses[UK];
5816 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5817 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5818 ModAsSideEffect->push_back(std::make_pair(O, U));
5819 U.Use = Ref;
5820 U.Seq = Region;
5821 }
5822 }
5823 /// \brief Check whether a modification or use conflicts with a prior usage.
5824 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5825 bool IsModMod) {
5826 if (UI.Diagnosed)
5827 return;
5828
5829 const Usage &U = UI.Uses[OtherKind];
5830 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5831 return;
5832
5833 Expr *Mod = U.Use;
5834 Expr *ModOrUse = Ref;
5835 if (OtherKind == UK_Use)
5836 std::swap(Mod, ModOrUse);
5837
5838 SemaRef.Diag(Mod->getExprLoc(),
5839 IsModMod ? diag::warn_unsequenced_mod_mod
5840 : diag::warn_unsequenced_mod_use)
5841 << O << SourceRange(ModOrUse->getExprLoc());
5842 UI.Diagnosed = true;
5843 }
5844
5845 void notePreUse(Object O, Expr *Use) {
5846 UsageInfo &U = UsageMap[O];
5847 // Uses conflict with other modifications.
5848 checkUsage(O, U, Use, UK_ModAsValue, false);
5849 }
5850 void notePostUse(Object O, Expr *Use) {
5851 UsageInfo &U = UsageMap[O];
5852 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5853 addUsage(U, O, Use, UK_Use);
5854 }
5855
5856 void notePreMod(Object O, Expr *Mod) {
5857 UsageInfo &U = UsageMap[O];
5858 // Modifications conflict with other modifications and with uses.
5859 checkUsage(O, U, Mod, UK_ModAsValue, true);
5860 checkUsage(O, U, Mod, UK_Use, false);
5861 }
5862 void notePostMod(Object O, Expr *Use, UsageKind UK) {
5863 UsageInfo &U = UsageMap[O];
5864 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5865 addUsage(U, O, Use, UK);
5866 }
5867
5868public:
Robert Wilhelme7205c02013-08-10 12:33:24 +00005869 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
5870 : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
5871 WorkList(WorkList), EvalTracker(0) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005872 Visit(E);
5873 }
5874
5875 void VisitStmt(Stmt *S) {
5876 // Skip all statements which aren't expressions for now.
5877 }
5878
5879 void VisitExpr(Expr *E) {
5880 // By default, just recurse to evaluated subexpressions.
Richard Smith0c0b3902013-06-30 10:40:20 +00005881 Base::VisitStmt(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005882 }
5883
5884 void VisitCastExpr(CastExpr *E) {
5885 Object O = Object();
5886 if (E->getCastKind() == CK_LValueToRValue)
5887 O = getObject(E->getSubExpr(), false);
5888
5889 if (O)
5890 notePreUse(O, E);
5891 VisitExpr(E);
5892 if (O)
5893 notePostUse(O, E);
5894 }
5895
5896 void VisitBinComma(BinaryOperator *BO) {
5897 // C++11 [expr.comma]p1:
5898 // Every value computation and side effect associated with the left
5899 // expression is sequenced before every value computation and side
5900 // effect associated with the right expression.
5901 SequenceTree::Seq LHS = Tree.allocate(Region);
5902 SequenceTree::Seq RHS = Tree.allocate(Region);
5903 SequenceTree::Seq OldRegion = Region;
5904
5905 {
5906 SequencedSubexpression SeqLHS(*this);
5907 Region = LHS;
5908 Visit(BO->getLHS());
5909 }
5910
5911 Region = RHS;
5912 Visit(BO->getRHS());
5913
5914 Region = OldRegion;
5915
5916 // Forget that LHS and RHS are sequenced. They are both unsequenced
5917 // with respect to other stuff.
5918 Tree.merge(LHS);
5919 Tree.merge(RHS);
5920 }
5921
5922 void VisitBinAssign(BinaryOperator *BO) {
5923 // The modification is sequenced after the value computation of the LHS
5924 // and RHS, so check it before inspecting the operands and update the
5925 // map afterwards.
5926 Object O = getObject(BO->getLHS(), true);
5927 if (!O)
5928 return VisitExpr(BO);
5929
5930 notePreMod(O, BO);
5931
5932 // C++11 [expr.ass]p7:
5933 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
5934 // only once.
5935 //
5936 // Therefore, for a compound assignment operator, O is considered used
5937 // everywhere except within the evaluation of E1 itself.
5938 if (isa<CompoundAssignOperator>(BO))
5939 notePreUse(O, BO);
5940
5941 Visit(BO->getLHS());
5942
5943 if (isa<CompoundAssignOperator>(BO))
5944 notePostUse(O, BO);
5945
5946 Visit(BO->getRHS());
5947
Richard Smith418dd3e2013-06-26 23:16:51 +00005948 // C++11 [expr.ass]p1:
5949 // the assignment is sequenced [...] before the value computation of the
5950 // assignment expression.
5951 // C11 6.5.16/3 has no such rule.
5952 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5953 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005954 }
5955 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
5956 VisitBinAssign(CAO);
5957 }
5958
5959 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5960 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5961 void VisitUnaryPreIncDec(UnaryOperator *UO) {
5962 Object O = getObject(UO->getSubExpr(), true);
5963 if (!O)
5964 return VisitExpr(UO);
5965
5966 notePreMod(O, UO);
5967 Visit(UO->getSubExpr());
Richard Smith418dd3e2013-06-26 23:16:51 +00005968 // C++11 [expr.pre.incr]p1:
5969 // the expression ++x is equivalent to x+=1
5970 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5971 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005972 }
5973
5974 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5975 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5976 void VisitUnaryPostIncDec(UnaryOperator *UO) {
5977 Object O = getObject(UO->getSubExpr(), true);
5978 if (!O)
5979 return VisitExpr(UO);
5980
5981 notePreMod(O, UO);
5982 Visit(UO->getSubExpr());
5983 notePostMod(O, UO, UK_ModAsSideEffect);
5984 }
5985
5986 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
5987 void VisitBinLOr(BinaryOperator *BO) {
5988 // The side-effects of the LHS of an '&&' are sequenced before the
5989 // value computation of the RHS, and hence before the value computation
5990 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
5991 // as if they were unconditionally sequenced.
Richard Smith67470052013-06-20 22:21:56 +00005992 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005993 {
5994 SequencedSubexpression Sequenced(*this);
5995 Visit(BO->getLHS());
5996 }
5997
5998 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00005999 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00006000 if (!Result)
6001 Visit(BO->getRHS());
6002 } else {
6003 // Check for unsequenced operations in the RHS, treating it as an
6004 // entirely separate evaluation.
6005 //
6006 // FIXME: If there are operations in the RHS which are unsequenced
6007 // with respect to operations outside the RHS, and those operations
6008 // are unconditionally evaluated, diagnose them.
Richard Smith1a2dcd52013-01-17 23:18:09 +00006009 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00006010 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006011 }
6012 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith67470052013-06-20 22:21:56 +00006013 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006014 {
6015 SequencedSubexpression Sequenced(*this);
6016 Visit(BO->getLHS());
6017 }
6018
6019 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00006020 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00006021 if (Result)
6022 Visit(BO->getRHS());
6023 } else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00006024 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00006025 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006026 }
6027
6028 // Only visit the condition, unless we can be sure which subexpression will
6029 // be chosen.
6030 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith67470052013-06-20 22:21:56 +00006031 EvaluationTracker Eval(*this);
Richard Smith418dd3e2013-06-26 23:16:51 +00006032 {
6033 SequencedSubexpression Sequenced(*this);
6034 Visit(CO->getCond());
6035 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006036
6037 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00006038 if (Eval.evaluate(CO->getCond(), Result))
Richard Smith6c3af3d2013-01-17 01:17:56 +00006039 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00006040 else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00006041 WorkList.push_back(CO->getTrueExpr());
6042 WorkList.push_back(CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00006043 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006044 }
6045
Richard Smith0c0b3902013-06-30 10:40:20 +00006046 void VisitCallExpr(CallExpr *CE) {
6047 // C++11 [intro.execution]p15:
6048 // When calling a function [...], every value computation and side effect
6049 // associated with any argument expression, or with the postfix expression
6050 // designating the called function, is sequenced before execution of every
6051 // expression or statement in the body of the function [and thus before
6052 // the value computation of its result].
6053 SequencedSubexpression Sequenced(*this);
6054 Base::VisitCallExpr(CE);
6055
6056 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6057 }
6058
Richard Smith6c3af3d2013-01-17 01:17:56 +00006059 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smith0c0b3902013-06-30 10:40:20 +00006060 // This is a call, so all subexpressions are sequenced before the result.
6061 SequencedSubexpression Sequenced(*this);
6062
Richard Smith6c3af3d2013-01-17 01:17:56 +00006063 if (!CCE->isListInitialization())
6064 return VisitExpr(CCE);
6065
6066 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00006067 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00006068 SequenceTree::Seq Parent = Region;
6069 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6070 E = CCE->arg_end();
6071 I != E; ++I) {
6072 Region = Tree.allocate(Parent);
6073 Elts.push_back(Region);
6074 Visit(*I);
6075 }
6076
6077 // Forget that the initializers are sequenced.
6078 Region = Parent;
6079 for (unsigned I = 0; I < Elts.size(); ++I)
6080 Tree.merge(Elts[I]);
6081 }
6082
6083 void VisitInitListExpr(InitListExpr *ILE) {
6084 if (!SemaRef.getLangOpts().CPlusPlus11)
6085 return VisitExpr(ILE);
6086
6087 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00006088 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00006089 SequenceTree::Seq Parent = Region;
6090 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6091 Expr *E = ILE->getInit(I);
6092 if (!E) continue;
6093 Region = Tree.allocate(Parent);
6094 Elts.push_back(Region);
6095 Visit(E);
6096 }
6097
6098 // Forget that the initializers are sequenced.
6099 Region = Parent;
6100 for (unsigned I = 0; I < Elts.size(); ++I)
6101 Tree.merge(Elts[I]);
6102 }
6103};
6104}
6105
6106void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelme7205c02013-08-10 12:33:24 +00006107 SmallVector<Expr *, 8> WorkList;
Richard Smith1a2dcd52013-01-17 23:18:09 +00006108 WorkList.push_back(E);
6109 while (!WorkList.empty()) {
Robert Wilhelm344472e2013-08-23 16:11:15 +00006110 Expr *Item = WorkList.pop_back_val();
Richard Smith1a2dcd52013-01-17 23:18:09 +00006111 SequenceChecker(*this, Item, WorkList);
6112 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006113}
6114
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006115void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6116 bool IsConstexpr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00006117 CheckImplicitConversions(E, CheckLoc);
6118 CheckUnsequencedOperations(E);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006119 if (!IsConstexpr && !E->isValueDependent())
6120 CheckForIntOverflow(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006121}
6122
John McCall15d7d122010-11-11 03:21:53 +00006123void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6124 FieldDecl *BitField,
6125 Expr *Init) {
6126 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6127}
6128
Mike Stumpf8c49212010-01-21 03:59:47 +00006129/// CheckParmsForFunctionDef - Check that the parameters of the given
6130/// function are appropriate for the definition of a function. This
6131/// takes care of any checks that cannot be performed on the
6132/// declaration itself, e.g., that the types of each of the function
6133/// parameters are complete.
Reid Kleckner8c0501c2013-06-24 14:38:26 +00006134bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6135 ParmVarDecl *const *PEnd,
Douglas Gregor82aa7132010-11-01 18:37:59 +00006136 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00006137 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00006138 for (; P != PEnd; ++P) {
6139 ParmVarDecl *Param = *P;
6140
Mike Stumpf8c49212010-01-21 03:59:47 +00006141 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6142 // function declarator that is part of a function definition of
6143 // that function shall not have incomplete type.
6144 //
6145 // This is also C++ [dcl.fct]p6.
6146 if (!Param->isInvalidDecl() &&
6147 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00006148 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00006149 Param->setInvalidDecl();
6150 HasInvalidParm = true;
6151 }
6152
6153 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6154 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00006155 if (CheckParameterNames &&
6156 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00006157 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006158 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00006159 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00006160
6161 // C99 6.7.5.3p12:
6162 // If the function declarator is not part of a definition of that
6163 // function, parameters may have incomplete type and may use the [*]
6164 // notation in their sequences of declarator specifiers to specify
6165 // variable length array types.
6166 QualType PType = Param->getOriginalType();
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006167 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigd17e3402010-02-01 05:02:49 +00006168 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitfc093362013-03-01 21:41:22 +00006169 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00006170 // information is added for it.
6171 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006172 break;
Sam Weinigd17e3402010-02-01 05:02:49 +00006173 }
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006174 PType= AT->getElementType();
Sam Weinigd17e3402010-02-01 05:02:49 +00006175 }
Reid Kleckner9b601952013-06-21 12:45:15 +00006176
6177 // MSVC destroys objects passed by value in the callee. Therefore a
6178 // function definition which takes such a parameter must be able to call the
6179 // object's destructor.
6180 if (getLangOpts().CPlusPlus &&
6181 Context.getTargetInfo().getCXXABI().isArgumentDestroyedByCallee()) {
6182 if (const RecordType *RT = Param->getType()->getAs<RecordType>())
6183 FinalizeVarWithDestructor(Param, RT);
6184 }
Mike Stumpf8c49212010-01-21 03:59:47 +00006185 }
6186
6187 return HasInvalidParm;
6188}
John McCallb7f4ffe2010-08-12 21:44:57 +00006189
6190/// CheckCastAlign - Implements -Wcast-align, which warns when a
6191/// pointer cast increases the alignment requirements.
6192void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6193 // This is actually a lot of work to potentially be doing on every
6194 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00006195 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6196 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00006197 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00006198 return;
6199
6200 // Ignore dependent types.
6201 if (T->isDependentType() || Op->getType()->isDependentType())
6202 return;
6203
6204 // Require that the destination be a pointer type.
6205 const PointerType *DestPtr = T->getAs<PointerType>();
6206 if (!DestPtr) return;
6207
6208 // If the destination has alignment 1, we're done.
6209 QualType DestPointee = DestPtr->getPointeeType();
6210 if (DestPointee->isIncompleteType()) return;
6211 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6212 if (DestAlign.isOne()) return;
6213
6214 // Require that the source be a pointer type.
6215 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6216 if (!SrcPtr) return;
6217 QualType SrcPointee = SrcPtr->getPointeeType();
6218
6219 // Whitelist casts from cv void*. We already implicitly
6220 // whitelisted casts to cv void*, since they have alignment 1.
6221 // Also whitelist casts involving incomplete types, which implicitly
6222 // includes 'void'.
6223 if (SrcPointee->isIncompleteType()) return;
6224
6225 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6226 if (SrcAlign >= DestAlign) return;
6227
6228 Diag(TRange.getBegin(), diag::warn_cast_align)
6229 << Op->getType() << T
6230 << static_cast<unsigned>(SrcAlign.getQuantity())
6231 << static_cast<unsigned>(DestAlign.getQuantity())
6232 << TRange << Op->getSourceRange();
6233}
6234
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006235static const Type* getElementType(const Expr *BaseExpr) {
6236 const Type* EltType = BaseExpr->getType().getTypePtr();
6237 if (EltType->isAnyPointerType())
6238 return EltType->getPointeeType().getTypePtr();
6239 else if (EltType->isArrayType())
6240 return EltType->getBaseElementTypeUnsafe();
6241 return EltType;
6242}
6243
Chandler Carruthc2684342011-08-05 09:10:50 +00006244/// \brief Check whether this array fits the idiom of a size-one tail padded
6245/// array member of a struct.
6246///
6247/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6248/// commonly used to emulate flexible arrays in C89 code.
6249static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6250 const NamedDecl *ND) {
6251 if (Size != 1 || !ND) return false;
6252
6253 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6254 if (!FD) return false;
6255
6256 // Don't consider sizes resulting from macro expansions or template argument
6257 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00006258
6259 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006260 while (TInfo) {
6261 TypeLoc TL = TInfo->getTypeLoc();
6262 // Look through typedefs.
David Blaikie39e6ab42013-02-18 22:06:02 +00006263 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6264 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006265 TInfo = TDL->getTypeSourceInfo();
6266 continue;
6267 }
David Blaikie39e6ab42013-02-18 22:06:02 +00006268 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6269 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier5e253012013-02-06 00:58:34 +00006270 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6271 return false;
6272 }
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006273 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00006274 }
Chandler Carruthc2684342011-08-05 09:10:50 +00006275
6276 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00006277 if (!RD) return false;
6278 if (RD->isUnion()) return false;
6279 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6280 if (!CRD->isStandardLayout()) return false;
6281 }
Chandler Carruthc2684342011-08-05 09:10:50 +00006282
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00006283 // See if this is the last field decl in the record.
6284 const Decl *D = FD;
6285 while ((D = D->getNextDeclInContext()))
6286 if (isa<FieldDecl>(D))
6287 return false;
6288 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00006289}
6290
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006291void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006292 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00006293 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00006294 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006295 if (IndexExpr->isValueDependent())
6296 return;
6297
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00006298 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006299 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00006300 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006301 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00006302 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00006303 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00006304
Chandler Carruth34064582011-02-17 20:55:08 +00006305 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006306 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00006307 return;
Richard Smith25b009a2011-12-16 19:31:14 +00006308 if (IndexNegated)
6309 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00006310
Chandler Carruthba447122011-08-05 08:07:29 +00006311 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00006312 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6313 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00006314 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00006315 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00006316
Ted Kremenek9e060ca2011-02-23 23:06:04 +00006317 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00006318 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00006319 if (!size.isStrictlyPositive())
6320 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006321
6322 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00006323 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006324 // Make sure we're comparing apples to apples when comparing index to size
6325 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6326 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00006327 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00006328 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006329 if (ptrarith_typesize != array_typesize) {
6330 // There's a cast to a different size type involved
6331 uint64_t ratio = array_typesize / ptrarith_typesize;
6332 // TODO: Be smarter about handling cases where array_typesize is not a
6333 // multiple of ptrarith_typesize
6334 if (ptrarith_typesize * ratio == array_typesize)
6335 size *= llvm::APInt(size.getBitWidth(), ratio);
6336 }
6337 }
6338
Chandler Carruth34064582011-02-17 20:55:08 +00006339 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00006340 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00006341 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00006342 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00006343
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006344 // For array subscripting the index must be less than size, but for pointer
6345 // arithmetic also allow the index (offset) to be equal to size since
6346 // computing the next address after the end of the array is legal and
6347 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00006348 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00006349 return;
6350
6351 // Also don't warn for arrays of size 1 which are members of some
6352 // structure. These are often used to approximate flexible arrays in C89
6353 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006354 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00006355 return;
Chandler Carruth34064582011-02-17 20:55:08 +00006356
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006357 // Suppress the warning if the subscript expression (as identified by the
6358 // ']' location) and the index expression are both from macro expansions
6359 // within a system header.
6360 if (ASE) {
6361 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6362 ASE->getRBracketLoc());
6363 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6364 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6365 IndexExpr->getLocStart());
Eli Friedman24146972013-08-22 00:27:10 +00006366 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006367 return;
6368 }
6369 }
6370
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006371 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006372 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006373 DiagID = diag::warn_array_index_exceeds_bounds;
6374
6375 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6376 PDiag(DiagID) << index.toString(10, true)
6377 << size.toString(10, true)
6378 << (unsigned)size.getLimitedValue(~0U)
6379 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00006380 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006381 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006382 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006383 DiagID = diag::warn_ptr_arith_precedes_bounds;
6384 if (index.isNegative()) index = -index;
6385 }
6386
6387 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6388 PDiag(DiagID) << index.toString(10, true)
6389 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006390 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00006391
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00006392 if (!ND) {
6393 // Try harder to find a NamedDecl to point at in the note.
6394 while (const ArraySubscriptExpr *ASE =
6395 dyn_cast<ArraySubscriptExpr>(BaseExpr))
6396 BaseExpr = ASE->getBase()->IgnoreParenCasts();
6397 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6398 ND = dyn_cast<NamedDecl>(DRE->getDecl());
6399 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6400 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6401 }
6402
Chandler Carruth35001ca2011-02-17 21:10:52 +00006403 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006404 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6405 PDiag(diag::note_array_index_out_of_bounds)
6406 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006407}
6408
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006409void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006410 int AllowOnePastEnd = 0;
6411 while (expr) {
6412 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006413 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006414 case Stmt::ArraySubscriptExprClass: {
6415 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006416 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006417 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006418 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006419 }
6420 case Stmt::UnaryOperatorClass: {
6421 // Only unwrap the * and & unary operators
6422 const UnaryOperator *UO = cast<UnaryOperator>(expr);
6423 expr = UO->getSubExpr();
6424 switch (UO->getOpcode()) {
6425 case UO_AddrOf:
6426 AllowOnePastEnd++;
6427 break;
6428 case UO_Deref:
6429 AllowOnePastEnd--;
6430 break;
6431 default:
6432 return;
6433 }
6434 break;
6435 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006436 case Stmt::ConditionalOperatorClass: {
6437 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
6438 if (const Expr *lhs = cond->getLHS())
6439 CheckArrayAccess(lhs);
6440 if (const Expr *rhs = cond->getRHS())
6441 CheckArrayAccess(rhs);
6442 return;
6443 }
6444 default:
6445 return;
6446 }
Peter Collingbournef111d932011-04-15 00:35:48 +00006447 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006448}
John McCallf85e1932011-06-15 23:02:42 +00006449
6450//===--- CHECK: Objective-C retain cycles ----------------------------------//
6451
6452namespace {
6453 struct RetainCycleOwner {
6454 RetainCycleOwner() : Variable(0), Indirect(false) {}
6455 VarDecl *Variable;
6456 SourceRange Range;
6457 SourceLocation Loc;
6458 bool Indirect;
6459
6460 void setLocsFrom(Expr *e) {
6461 Loc = e->getExprLoc();
6462 Range = e->getSourceRange();
6463 }
6464 };
6465}
6466
6467/// Consider whether capturing the given variable can possibly lead to
6468/// a retain cycle.
6469static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00006470 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00006471 // lifetime. In MRR, it's captured strongly if the variable is
6472 // __block and has an appropriate type.
6473 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6474 return false;
6475
6476 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00006477 if (ref)
6478 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00006479 return true;
6480}
6481
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006482static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00006483 while (true) {
6484 e = e->IgnoreParens();
6485 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6486 switch (cast->getCastKind()) {
6487 case CK_BitCast:
6488 case CK_LValueBitCast:
6489 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00006490 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00006491 e = cast->getSubExpr();
6492 continue;
6493
John McCallf85e1932011-06-15 23:02:42 +00006494 default:
6495 return false;
6496 }
6497 }
6498
6499 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6500 ObjCIvarDecl *ivar = ref->getDecl();
6501 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6502 return false;
6503
6504 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006505 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006506 return false;
6507
6508 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6509 owner.Indirect = true;
6510 return true;
6511 }
6512
6513 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6514 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6515 if (!var) return false;
6516 return considerVariable(var, ref, owner);
6517 }
6518
John McCallf85e1932011-06-15 23:02:42 +00006519 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6520 if (member->isArrow()) return false;
6521
6522 // Don't count this as an indirect ownership.
6523 e = member->getBase();
6524 continue;
6525 }
6526
John McCall4b9c2d22011-11-06 09:01:30 +00006527 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6528 // Only pay attention to pseudo-objects on property references.
6529 ObjCPropertyRefExpr *pre
6530 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6531 ->IgnoreParens());
6532 if (!pre) return false;
6533 if (pre->isImplicitProperty()) return false;
6534 ObjCPropertyDecl *property = pre->getExplicitProperty();
6535 if (!property->isRetaining() &&
6536 !(property->getPropertyIvarDecl() &&
6537 property->getPropertyIvarDecl()->getType()
6538 .getObjCLifetime() == Qualifiers::OCL_Strong))
6539 return false;
6540
6541 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006542 if (pre->isSuperReceiver()) {
6543 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6544 if (!owner.Variable)
6545 return false;
6546 owner.Loc = pre->getLocation();
6547 owner.Range = pre->getSourceRange();
6548 return true;
6549 }
John McCall4b9c2d22011-11-06 09:01:30 +00006550 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6551 ->getSourceExpr());
6552 continue;
6553 }
6554
John McCallf85e1932011-06-15 23:02:42 +00006555 // Array ivars?
6556
6557 return false;
6558 }
6559}
6560
6561namespace {
6562 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6563 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6564 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6565 Variable(variable), Capturer(0) {}
6566
6567 VarDecl *Variable;
6568 Expr *Capturer;
6569
6570 void VisitDeclRefExpr(DeclRefExpr *ref) {
6571 if (ref->getDecl() == Variable && !Capturer)
6572 Capturer = ref;
6573 }
6574
John McCallf85e1932011-06-15 23:02:42 +00006575 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6576 if (Capturer) return;
6577 Visit(ref->getBase());
6578 if (Capturer && ref->isFreeIvar())
6579 Capturer = ref;
6580 }
6581
6582 void VisitBlockExpr(BlockExpr *block) {
6583 // Look inside nested blocks
6584 if (block->getBlockDecl()->capturesVariable(Variable))
6585 Visit(block->getBlockDecl()->getBody());
6586 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00006587
6588 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6589 if (Capturer) return;
6590 if (OVE->getSourceExpr())
6591 Visit(OVE->getSourceExpr());
6592 }
John McCallf85e1932011-06-15 23:02:42 +00006593 };
6594}
6595
6596/// Check whether the given argument is a block which captures a
6597/// variable.
6598static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6599 assert(owner.Variable && owner.Loc.isValid());
6600
6601 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00006602
6603 // Look through [^{...} copy] and Block_copy(^{...}).
6604 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6605 Selector Cmd = ME->getSelector();
6606 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6607 e = ME->getInstanceReceiver();
6608 if (!e)
6609 return 0;
6610 e = e->IgnoreParenCasts();
6611 }
6612 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6613 if (CE->getNumArgs() == 1) {
6614 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00006615 if (Fn) {
6616 const IdentifierInfo *FnI = Fn->getIdentifier();
6617 if (FnI && FnI->isStr("_Block_copy")) {
6618 e = CE->getArg(0)->IgnoreParenCasts();
6619 }
6620 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00006621 }
6622 }
6623
John McCallf85e1932011-06-15 23:02:42 +00006624 BlockExpr *block = dyn_cast<BlockExpr>(e);
6625 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6626 return 0;
6627
6628 FindCaptureVisitor visitor(S.Context, owner.Variable);
6629 visitor.Visit(block->getBlockDecl()->getBody());
6630 return visitor.Capturer;
6631}
6632
6633static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6634 RetainCycleOwner &owner) {
6635 assert(capturer);
6636 assert(owner.Variable && owner.Loc.isValid());
6637
6638 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6639 << owner.Variable << capturer->getSourceRange();
6640 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6641 << owner.Indirect << owner.Range;
6642}
6643
6644/// Check for a keyword selector that starts with the word 'add' or
6645/// 'set'.
6646static bool isSetterLikeSelector(Selector sel) {
6647 if (sel.isUnarySelector()) return false;
6648
Chris Lattner5f9e2722011-07-23 10:55:15 +00006649 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00006650 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006651 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00006652 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006653 else if (str.startswith("add")) {
6654 // Specially whitelist 'addOperationWithBlock:'.
6655 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6656 return false;
6657 str = str.substr(3);
6658 }
John McCallf85e1932011-06-15 23:02:42 +00006659 else
6660 return false;
6661
6662 if (str.empty()) return true;
Jordan Rose3f6f51e2013-02-08 22:30:41 +00006663 return !isLowercase(str.front());
John McCallf85e1932011-06-15 23:02:42 +00006664}
6665
6666/// Check a message send to see if it's likely to cause a retain cycle.
6667void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6668 // Only check instance methods whose selector looks like a setter.
6669 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6670 return;
6671
6672 // Try to find a variable that the receiver is strongly owned by.
6673 RetainCycleOwner owner;
6674 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006675 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006676 return;
6677 } else {
6678 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6679 owner.Variable = getCurMethodDecl()->getSelfDecl();
6680 owner.Loc = msg->getSuperLoc();
6681 owner.Range = msg->getSuperLoc();
6682 }
6683
6684 // Check whether the receiver is captured by any of the arguments.
6685 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6686 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6687 return diagnoseRetainCycle(*this, capturer, owner);
6688}
6689
6690/// Check a property assign to see if it's likely to cause a retain cycle.
6691void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6692 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006693 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00006694 return;
6695
6696 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6697 diagnoseRetainCycle(*this, capturer, owner);
6698}
6699
Jordan Rosee10f4d32012-09-15 02:48:31 +00006700void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6701 RetainCycleOwner Owner;
6702 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6703 return;
6704
6705 // Because we don't have an expression for the variable, we have to set the
6706 // location explicitly here.
6707 Owner.Loc = Var->getLocation();
6708 Owner.Range = Var->getSourceRange();
6709
6710 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6711 diagnoseRetainCycle(*this, Capturer, Owner);
6712}
6713
Ted Kremenek9d084012012-12-21 08:04:28 +00006714static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6715 Expr *RHS, bool isProperty) {
6716 // Check if RHS is an Objective-C object literal, which also can get
6717 // immediately zapped in a weak reference. Note that we explicitly
6718 // allow ObjCStringLiterals, since those are designed to never really die.
6719 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006720
Ted Kremenekd3292c82012-12-21 22:46:35 +00006721 // This enum needs to match with the 'select' in
6722 // warn_objc_arc_literal_assign (off-by-1).
6723 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6724 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6725 return false;
Ted Kremenekf530ff72012-12-21 21:59:39 +00006726
6727 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenekd3292c82012-12-21 22:46:35 +00006728 << (unsigned) Kind
Ted Kremenek9d084012012-12-21 08:04:28 +00006729 << (isProperty ? 0 : 1)
6730 << RHS->getSourceRange();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006731
6732 return true;
Ted Kremenek9d084012012-12-21 08:04:28 +00006733}
6734
Ted Kremenekb29b30f2012-12-21 19:45:30 +00006735static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6736 Qualifiers::ObjCLifetime LT,
6737 Expr *RHS, bool isProperty) {
6738 // Strip off any implicit cast added to get to the one ARC-specific.
6739 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6740 if (cast->getCastKind() == CK_ARCConsumeObject) {
6741 S.Diag(Loc, diag::warn_arc_retained_assign)
6742 << (LT == Qualifiers::OCL_ExplicitNone)
6743 << (isProperty ? 0 : 1)
6744 << RHS->getSourceRange();
6745 return true;
6746 }
6747 RHS = cast->getSubExpr();
6748 }
6749
6750 if (LT == Qualifiers::OCL_Weak &&
6751 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6752 return true;
6753
6754 return false;
6755}
6756
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006757bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6758 QualType LHS, Expr *RHS) {
6759 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6760
6761 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6762 return false;
6763
6764 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6765 return true;
6766
6767 return false;
6768}
6769
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006770void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6771 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006772 QualType LHSType;
6773 // PropertyRef on LHS type need be directly obtained from
6774 // its declaration as it has a PsuedoType.
6775 ObjCPropertyRefExpr *PRE
6776 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6777 if (PRE && !PRE->isImplicitProperty()) {
6778 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6779 if (PD)
6780 LHSType = PD->getType();
6781 }
6782
6783 if (LHSType.isNull())
6784 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00006785
6786 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6787
6788 if (LT == Qualifiers::OCL_Weak) {
6789 DiagnosticsEngine::Level Level =
6790 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6791 if (Level != DiagnosticsEngine::Ignored)
6792 getCurFunction()->markSafeWeakUse(LHS);
6793 }
6794
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006795 if (checkUnsafeAssigns(Loc, LHSType, RHS))
6796 return;
Jordan Rose7a270482012-09-28 22:21:35 +00006797
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006798 // FIXME. Check for other life times.
6799 if (LT != Qualifiers::OCL_None)
6800 return;
6801
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006802 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006803 if (PRE->isImplicitProperty())
6804 return;
6805 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6806 if (!PD)
6807 return;
6808
Bill Wendlingad017fa2012-12-20 19:22:21 +00006809 unsigned Attributes = PD->getPropertyAttributes();
6810 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006811 // when 'assign' attribute was not explicitly specified
6812 // by user, ignore it and rely on property type itself
6813 // for lifetime info.
6814 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6815 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6816 LHSType->isObjCRetainableType())
6817 return;
6818
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006819 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00006820 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006821 Diag(Loc, diag::warn_arc_retained_property_assign)
6822 << RHS->getSourceRange();
6823 return;
6824 }
6825 RHS = cast->getSubExpr();
6826 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006827 }
Bill Wendlingad017fa2012-12-20 19:22:21 +00006828 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006829 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6830 return;
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00006831 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006832 }
6833}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00006834
6835//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6836
6837namespace {
6838bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6839 SourceLocation StmtLoc,
6840 const NullStmt *Body) {
6841 // Do not warn if the body is a macro that expands to nothing, e.g:
6842 //
6843 // #define CALL(x)
6844 // if (condition)
6845 // CALL(0);
6846 //
6847 if (Body->hasLeadingEmptyMacro())
6848 return false;
6849
6850 // Get line numbers of statement and body.
6851 bool StmtLineInvalid;
6852 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6853 &StmtLineInvalid);
6854 if (StmtLineInvalid)
6855 return false;
6856
6857 bool BodyLineInvalid;
6858 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
6859 &BodyLineInvalid);
6860 if (BodyLineInvalid)
6861 return false;
6862
6863 // Warn if null statement and body are on the same line.
6864 if (StmtLine != BodyLine)
6865 return false;
6866
6867 return true;
6868}
6869} // Unnamed namespace
6870
6871void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
6872 const Stmt *Body,
6873 unsigned DiagID) {
6874 // Since this is a syntactic check, don't emit diagnostic for template
6875 // instantiations, this just adds noise.
6876 if (CurrentInstantiationScope)
6877 return;
6878
6879 // The body should be a null statement.
6880 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6881 if (!NBody)
6882 return;
6883
6884 // Do the usual checks.
6885 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6886 return;
6887
6888 Diag(NBody->getSemiLoc(), DiagID);
6889 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6890}
6891
6892void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
6893 const Stmt *PossibleBody) {
6894 assert(!CurrentInstantiationScope); // Ensured by caller
6895
6896 SourceLocation StmtLoc;
6897 const Stmt *Body;
6898 unsigned DiagID;
6899 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
6900 StmtLoc = FS->getRParenLoc();
6901 Body = FS->getBody();
6902 DiagID = diag::warn_empty_for_body;
6903 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
6904 StmtLoc = WS->getCond()->getSourceRange().getEnd();
6905 Body = WS->getBody();
6906 DiagID = diag::warn_empty_while_body;
6907 } else
6908 return; // Neither `for' nor `while'.
6909
6910 // The body should be a null statement.
6911 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6912 if (!NBody)
6913 return;
6914
6915 // Skip expensive checks if diagnostic is disabled.
6916 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
6917 DiagnosticsEngine::Ignored)
6918 return;
6919
6920 // Do the usual checks.
6921 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6922 return;
6923
6924 // `for(...);' and `while(...);' are popular idioms, so in order to keep
6925 // noise level low, emit diagnostics only if for/while is followed by a
6926 // CompoundStmt, e.g.:
6927 // for (int i = 0; i < n; i++);
6928 // {
6929 // a(i);
6930 // }
6931 // or if for/while is followed by a statement with more indentation
6932 // than for/while itself:
6933 // for (int i = 0; i < n; i++);
6934 // a(i);
6935 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
6936 if (!ProbableTypo) {
6937 bool BodyColInvalid;
6938 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
6939 PossibleBody->getLocStart(),
6940 &BodyColInvalid);
6941 if (BodyColInvalid)
6942 return;
6943
6944 bool StmtColInvalid;
6945 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
6946 S->getLocStart(),
6947 &StmtColInvalid);
6948 if (StmtColInvalid)
6949 return;
6950
6951 if (BodyCol > StmtCol)
6952 ProbableTypo = true;
6953 }
6954
6955 if (ProbableTypo) {
6956 Diag(NBody->getSemiLoc(), DiagID);
6957 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6958 }
6959}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006960
6961//===--- Layout compatibility ----------------------------------------------//
6962
6963namespace {
6964
6965bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
6966
6967/// \brief Check if two enumeration types are layout-compatible.
6968bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
6969 // C++11 [dcl.enum] p8:
6970 // Two enumeration types are layout-compatible if they have the same
6971 // underlying type.
6972 return ED1->isComplete() && ED2->isComplete() &&
6973 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
6974}
6975
6976/// \brief Check if two fields are layout-compatible.
6977bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
6978 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
6979 return false;
6980
6981 if (Field1->isBitField() != Field2->isBitField())
6982 return false;
6983
6984 if (Field1->isBitField()) {
6985 // Make sure that the bit-fields are the same length.
6986 unsigned Bits1 = Field1->getBitWidthValue(C);
6987 unsigned Bits2 = Field2->getBitWidthValue(C);
6988
6989 if (Bits1 != Bits2)
6990 return false;
6991 }
6992
6993 return true;
6994}
6995
6996/// \brief Check if two standard-layout structs are layout-compatible.
6997/// (C++11 [class.mem] p17)
6998bool isLayoutCompatibleStruct(ASTContext &C,
6999 RecordDecl *RD1,
7000 RecordDecl *RD2) {
7001 // If both records are C++ classes, check that base classes match.
7002 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7003 // If one of records is a CXXRecordDecl we are in C++ mode,
7004 // thus the other one is a CXXRecordDecl, too.
7005 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7006 // Check number of base classes.
7007 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7008 return false;
7009
7010 // Check the base classes.
7011 for (CXXRecordDecl::base_class_const_iterator
7012 Base1 = D1CXX->bases_begin(),
7013 BaseEnd1 = D1CXX->bases_end(),
7014 Base2 = D2CXX->bases_begin();
7015 Base1 != BaseEnd1;
7016 ++Base1, ++Base2) {
7017 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7018 return false;
7019 }
7020 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7021 // If only RD2 is a C++ class, it should have zero base classes.
7022 if (D2CXX->getNumBases() > 0)
7023 return false;
7024 }
7025
7026 // Check the fields.
7027 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7028 Field2End = RD2->field_end(),
7029 Field1 = RD1->field_begin(),
7030 Field1End = RD1->field_end();
7031 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7032 if (!isLayoutCompatible(C, *Field1, *Field2))
7033 return false;
7034 }
7035 if (Field1 != Field1End || Field2 != Field2End)
7036 return false;
7037
7038 return true;
7039}
7040
7041/// \brief Check if two standard-layout unions are layout-compatible.
7042/// (C++11 [class.mem] p18)
7043bool isLayoutCompatibleUnion(ASTContext &C,
7044 RecordDecl *RD1,
7045 RecordDecl *RD2) {
7046 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
7047 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
7048 Field2End = RD2->field_end();
7049 Field2 != Field2End; ++Field2) {
7050 UnmatchedFields.insert(*Field2);
7051 }
7052
7053 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
7054 Field1End = RD1->field_end();
7055 Field1 != Field1End; ++Field1) {
7056 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7057 I = UnmatchedFields.begin(),
7058 E = UnmatchedFields.end();
7059
7060 for ( ; I != E; ++I) {
7061 if (isLayoutCompatible(C, *Field1, *I)) {
7062 bool Result = UnmatchedFields.erase(*I);
7063 (void) Result;
7064 assert(Result);
7065 break;
7066 }
7067 }
7068 if (I == E)
7069 return false;
7070 }
7071
7072 return UnmatchedFields.empty();
7073}
7074
7075bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7076 if (RD1->isUnion() != RD2->isUnion())
7077 return false;
7078
7079 if (RD1->isUnion())
7080 return isLayoutCompatibleUnion(C, RD1, RD2);
7081 else
7082 return isLayoutCompatibleStruct(C, RD1, RD2);
7083}
7084
7085/// \brief Check if two types are layout-compatible in C++11 sense.
7086bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7087 if (T1.isNull() || T2.isNull())
7088 return false;
7089
7090 // C++11 [basic.types] p11:
7091 // If two types T1 and T2 are the same type, then T1 and T2 are
7092 // layout-compatible types.
7093 if (C.hasSameType(T1, T2))
7094 return true;
7095
7096 T1 = T1.getCanonicalType().getUnqualifiedType();
7097 T2 = T2.getCanonicalType().getUnqualifiedType();
7098
7099 const Type::TypeClass TC1 = T1->getTypeClass();
7100 const Type::TypeClass TC2 = T2->getTypeClass();
7101
7102 if (TC1 != TC2)
7103 return false;
7104
7105 if (TC1 == Type::Enum) {
7106 return isLayoutCompatible(C,
7107 cast<EnumType>(T1)->getDecl(),
7108 cast<EnumType>(T2)->getDecl());
7109 } else if (TC1 == Type::Record) {
7110 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7111 return false;
7112
7113 return isLayoutCompatible(C,
7114 cast<RecordType>(T1)->getDecl(),
7115 cast<RecordType>(T2)->getDecl());
7116 }
7117
7118 return false;
7119}
7120}
7121
7122//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7123
7124namespace {
7125/// \brief Given a type tag expression find the type tag itself.
7126///
7127/// \param TypeExpr Type tag expression, as it appears in user's code.
7128///
7129/// \param VD Declaration of an identifier that appears in a type tag.
7130///
7131/// \param MagicValue Type tag magic value.
7132bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7133 const ValueDecl **VD, uint64_t *MagicValue) {
7134 while(true) {
7135 if (!TypeExpr)
7136 return false;
7137
7138 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7139
7140 switch (TypeExpr->getStmtClass()) {
7141 case Stmt::UnaryOperatorClass: {
7142 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7143 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7144 TypeExpr = UO->getSubExpr();
7145 continue;
7146 }
7147 return false;
7148 }
7149
7150 case Stmt::DeclRefExprClass: {
7151 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7152 *VD = DRE->getDecl();
7153 return true;
7154 }
7155
7156 case Stmt::IntegerLiteralClass: {
7157 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7158 llvm::APInt MagicValueAPInt = IL->getValue();
7159 if (MagicValueAPInt.getActiveBits() <= 64) {
7160 *MagicValue = MagicValueAPInt.getZExtValue();
7161 return true;
7162 } else
7163 return false;
7164 }
7165
7166 case Stmt::BinaryConditionalOperatorClass:
7167 case Stmt::ConditionalOperatorClass: {
7168 const AbstractConditionalOperator *ACO =
7169 cast<AbstractConditionalOperator>(TypeExpr);
7170 bool Result;
7171 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7172 if (Result)
7173 TypeExpr = ACO->getTrueExpr();
7174 else
7175 TypeExpr = ACO->getFalseExpr();
7176 continue;
7177 }
7178 return false;
7179 }
7180
7181 case Stmt::BinaryOperatorClass: {
7182 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7183 if (BO->getOpcode() == BO_Comma) {
7184 TypeExpr = BO->getRHS();
7185 continue;
7186 }
7187 return false;
7188 }
7189
7190 default:
7191 return false;
7192 }
7193 }
7194}
7195
7196/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7197///
7198/// \param TypeExpr Expression that specifies a type tag.
7199///
7200/// \param MagicValues Registered magic values.
7201///
7202/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7203/// kind.
7204///
7205/// \param TypeInfo Information about the corresponding C type.
7206///
7207/// \returns true if the corresponding C type was found.
7208bool GetMatchingCType(
7209 const IdentifierInfo *ArgumentKind,
7210 const Expr *TypeExpr, const ASTContext &Ctx,
7211 const llvm::DenseMap<Sema::TypeTagMagicValue,
7212 Sema::TypeTagData> *MagicValues,
7213 bool &FoundWrongKind,
7214 Sema::TypeTagData &TypeInfo) {
7215 FoundWrongKind = false;
7216
7217 // Variable declaration that has type_tag_for_datatype attribute.
7218 const ValueDecl *VD = NULL;
7219
7220 uint64_t MagicValue;
7221
7222 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7223 return false;
7224
7225 if (VD) {
7226 for (specific_attr_iterator<TypeTagForDatatypeAttr>
7227 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
7228 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
7229 I != E; ++I) {
7230 if (I->getArgumentKind() != ArgumentKind) {
7231 FoundWrongKind = true;
7232 return false;
7233 }
7234 TypeInfo.Type = I->getMatchingCType();
7235 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7236 TypeInfo.MustBeNull = I->getMustBeNull();
7237 return true;
7238 }
7239 return false;
7240 }
7241
7242 if (!MagicValues)
7243 return false;
7244
7245 llvm::DenseMap<Sema::TypeTagMagicValue,
7246 Sema::TypeTagData>::const_iterator I =
7247 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7248 if (I == MagicValues->end())
7249 return false;
7250
7251 TypeInfo = I->second;
7252 return true;
7253}
7254} // unnamed namespace
7255
7256void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7257 uint64_t MagicValue, QualType Type,
7258 bool LayoutCompatible,
7259 bool MustBeNull) {
7260 if (!TypeTagForDatatypeMagicValues)
7261 TypeTagForDatatypeMagicValues.reset(
7262 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7263
7264 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7265 (*TypeTagForDatatypeMagicValues)[Magic] =
7266 TypeTagData(Type, LayoutCompatible, MustBeNull);
7267}
7268
7269namespace {
7270bool IsSameCharType(QualType T1, QualType T2) {
7271 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7272 if (!BT1)
7273 return false;
7274
7275 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7276 if (!BT2)
7277 return false;
7278
7279 BuiltinType::Kind T1Kind = BT1->getKind();
7280 BuiltinType::Kind T2Kind = BT2->getKind();
7281
7282 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
7283 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
7284 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7285 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7286}
7287} // unnamed namespace
7288
7289void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7290 const Expr * const *ExprArgs) {
7291 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7292 bool IsPointerAttr = Attr->getIsPointer();
7293
7294 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7295 bool FoundWrongKind;
7296 TypeTagData TypeInfo;
7297 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7298 TypeTagForDatatypeMagicValues.get(),
7299 FoundWrongKind, TypeInfo)) {
7300 if (FoundWrongKind)
7301 Diag(TypeTagExpr->getExprLoc(),
7302 diag::warn_type_tag_for_datatype_wrong_kind)
7303 << TypeTagExpr->getSourceRange();
7304 return;
7305 }
7306
7307 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7308 if (IsPointerAttr) {
7309 // Skip implicit cast of pointer to `void *' (as a function argument).
7310 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5a249802012-11-03 16:07:49 +00007311 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkob57ce4e2012-11-03 22:10:18 +00007312 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00007313 ArgumentExpr = ICE->getSubExpr();
7314 }
7315 QualType ArgumentType = ArgumentExpr->getType();
7316
7317 // Passing a `void*' pointer shouldn't trigger a warning.
7318 if (IsPointerAttr && ArgumentType->isVoidPointerType())
7319 return;
7320
7321 if (TypeInfo.MustBeNull) {
7322 // Type tag with matching void type requires a null pointer.
7323 if (!ArgumentExpr->isNullPointerConstant(Context,
7324 Expr::NPC_ValueDependentIsNotNull)) {
7325 Diag(ArgumentExpr->getExprLoc(),
7326 diag::warn_type_safety_null_pointer_required)
7327 << ArgumentKind->getName()
7328 << ArgumentExpr->getSourceRange()
7329 << TypeTagExpr->getSourceRange();
7330 }
7331 return;
7332 }
7333
7334 QualType RequiredType = TypeInfo.Type;
7335 if (IsPointerAttr)
7336 RequiredType = Context.getPointerType(RequiredType);
7337
7338 bool mismatch = false;
7339 if (!TypeInfo.LayoutCompatible) {
7340 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7341
7342 // C++11 [basic.fundamental] p1:
7343 // Plain char, signed char, and unsigned char are three distinct types.
7344 //
7345 // But we treat plain `char' as equivalent to `signed char' or `unsigned
7346 // char' depending on the current char signedness mode.
7347 if (mismatch)
7348 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7349 RequiredType->getPointeeType())) ||
7350 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7351 mismatch = false;
7352 } else
7353 if (IsPointerAttr)
7354 mismatch = !isLayoutCompatible(Context,
7355 ArgumentType->getPointeeType(),
7356 RequiredType->getPointeeType());
7357 else
7358 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7359
7360 if (mismatch)
7361 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
7362 << ArgumentType << ArgumentKind->getName()
7363 << TypeInfo.LayoutCompatible << RequiredType
7364 << ArgumentExpr->getSourceRange()
7365 << TypeTagExpr->getSourceRange();
7366}