blob: 0b95c48d4f8e7afa9d9ce571a4ad2ca77a39af05 [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:
Kevin Qin624bb5e2013-11-14 03:29:16 +0000342 case NeonTypeFlags::Poly64:
Bob Wilsonda95f732011-11-08 01:16:11 +0000343 return shift ? 63 : (1 << IsQuad) - 1;
344 case NeonTypeFlags::Float16:
345 assert(!shift && "cannot shift float types!");
346 return (4 << IsQuad) - 1;
347 case NeonTypeFlags::Float32:
348 assert(!shift && "cannot shift float types!");
349 return (2 << IsQuad) - 1;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000350 case NeonTypeFlags::Float64:
351 assert(!shift && "cannot shift float types!");
352 return (1 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000353 }
David Blaikie7530c032012-01-17 06:56:22 +0000354 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000355}
356
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000357/// getNeonEltType - Return the QualType corresponding to the elements of
358/// the vector type specified by the NeonTypeFlags. This is used to check
359/// the pointer arguments for Neon load/store intrinsics.
Kevin Qin624bb5e2013-11-14 03:29:16 +0000360static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
361 bool IsAArch64) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000362 switch (Flags.getEltType()) {
363 case NeonTypeFlags::Int8:
364 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
365 case NeonTypeFlags::Int16:
366 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
367 case NeonTypeFlags::Int32:
368 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
369 case NeonTypeFlags::Int64:
370 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
371 case NeonTypeFlags::Poly8:
Kevin Qin624bb5e2013-11-14 03:29:16 +0000372 return IsAArch64 ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000373 case NeonTypeFlags::Poly16:
Kevin Qin624bb5e2013-11-14 03:29:16 +0000374 return IsAArch64 ? Context.UnsignedShortTy : Context.ShortTy;
375 case NeonTypeFlags::Poly64:
376 return Context.UnsignedLongLongTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000377 case NeonTypeFlags::Float16:
Kevin Qin624bb5e2013-11-14 03:29:16 +0000378 return Context.HalfTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000379 case NeonTypeFlags::Float32:
380 return Context.FloatTy;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000381 case NeonTypeFlags::Float64:
382 return Context.DoubleTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000383 }
David Blaikie7530c032012-01-17 06:56:22 +0000384 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000385}
386
Tim Northoverb793f0d2013-08-01 09:23:19 +0000387bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
388 CallExpr *TheCall) {
389
390 llvm::APSInt Result;
391
392 uint64_t mask = 0;
393 unsigned TV = 0;
394 int PtrArgNum = -1;
395 bool HasConstPtr = false;
396 switch (BuiltinID) {
397#define GET_NEON_AARCH64_OVERLOAD_CHECK
398#include "clang/Basic/arm_neon.inc"
399#undef GET_NEON_AARCH64_OVERLOAD_CHECK
400 }
401
402 // For NEON intrinsics which are overloaded on vector element type, validate
403 // the immediate which specifies which variant to emit.
404 unsigned ImmArg = TheCall->getNumArgs() - 1;
405 if (mask) {
406 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
407 return true;
408
409 TV = Result.getLimitedValue(64);
410 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
411 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
412 << TheCall->getArg(ImmArg)->getSourceRange();
413 }
414
415 if (PtrArgNum >= 0) {
416 // Check that pointer arguments have the specified type.
417 Expr *Arg = TheCall->getArg(PtrArgNum);
418 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
419 Arg = ICE->getSubExpr();
420 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
421 QualType RHSTy = RHS.get()->getType();
Kevin Qin624bb5e2013-11-14 03:29:16 +0000422 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context, true);
Tim Northoverb793f0d2013-08-01 09:23:19 +0000423 if (HasConstPtr)
424 EltTy = EltTy.withConst();
425 QualType LHSTy = Context.getPointerType(EltTy);
426 AssignConvertType ConvTy;
427 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
428 if (RHS.isInvalid())
429 return true;
430 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
431 RHS.get(), AA_Assigning))
432 return true;
433 }
434
435 // For NEON intrinsics which take an immediate value as part of the
436 // instruction, range check them here.
437 unsigned i = 0, l = 0, u = 0;
438 switch (BuiltinID) {
439 default:
440 return false;
441#define GET_NEON_AARCH64_IMMEDIATE_CHECK
442#include "clang/Basic/arm_neon.inc"
443#undef GET_NEON_AARCH64_IMMEDIATE_CHECK
444 }
445 ;
446
447 // We can't check the value of a dependent argument.
448 if (TheCall->getArg(i)->isTypeDependent() ||
449 TheCall->getArg(i)->isValueDependent())
450 return false;
451
452 // Check that the immediate argument is actually a constant.
453 if (SemaBuiltinConstantArg(TheCall, i, Result))
454 return true;
455
456 // Range check against the upper/lower values for this isntruction.
457 unsigned Val = Result.getZExtValue();
458 if (Val < l || Val > (u + l))
459 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
460 << l << u + l << TheCall->getArg(i)->getSourceRange();
461
462 return false;
463}
464
Tim Northover09df2b02013-07-16 09:47:53 +0000465bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall) {
466 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
467 BuiltinID == ARM::BI__builtin_arm_strex) &&
468 "unexpected ARM builtin");
469 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex;
470
471 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
472
473 // Ensure that we have the proper number of arguments.
474 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
475 return true;
476
477 // Inspect the pointer argument of the atomic builtin. This should always be
478 // a pointer type, whose element is an integral scalar or pointer type.
479 // Because it is a pointer type, we don't have to worry about any implicit
480 // casts here.
481 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
482 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
483 if (PointerArgRes.isInvalid())
484 return true;
485 PointerArg = PointerArgRes.take();
486
487 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
488 if (!pointerType) {
489 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
490 << PointerArg->getType() << PointerArg->getSourceRange();
491 return true;
492 }
493
494 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
495 // task is to insert the appropriate casts into the AST. First work out just
496 // what the appropriate type is.
497 QualType ValType = pointerType->getPointeeType();
498 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
499 if (IsLdrex)
500 AddrType.addConst();
501
502 // Issue a warning if the cast is dodgy.
503 CastKind CastNeeded = CK_NoOp;
504 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
505 CastNeeded = CK_BitCast;
506 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
507 << PointerArg->getType()
508 << Context.getPointerType(AddrType)
509 << AA_Passing << PointerArg->getSourceRange();
510 }
511
512 // Finally, do the cast and replace the argument with the corrected version.
513 AddrType = Context.getPointerType(AddrType);
514 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
515 if (PointerArgRes.isInvalid())
516 return true;
517 PointerArg = PointerArgRes.take();
518
519 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
520
521 // In general, we allow ints, floats and pointers to be loaded and stored.
522 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
523 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
524 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
525 << PointerArg->getType() << PointerArg->getSourceRange();
526 return true;
527 }
528
529 // But ARM doesn't have instructions to deal with 128-bit versions.
530 if (Context.getTypeSize(ValType) > 64) {
531 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
532 << PointerArg->getType() << PointerArg->getSourceRange();
533 return true;
534 }
535
536 switch (ValType.getObjCLifetime()) {
537 case Qualifiers::OCL_None:
538 case Qualifiers::OCL_ExplicitNone:
539 // okay
540 break;
541
542 case Qualifiers::OCL_Weak:
543 case Qualifiers::OCL_Strong:
544 case Qualifiers::OCL_Autoreleasing:
545 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
546 << ValType << PointerArg->getSourceRange();
547 return true;
548 }
549
550
551 if (IsLdrex) {
552 TheCall->setType(ValType);
553 return false;
554 }
555
556 // Initialize the argument to be stored.
557 ExprResult ValArg = TheCall->getArg(0);
558 InitializedEntity Entity = InitializedEntity::InitializeParameter(
559 Context, ValType, /*consume*/ false);
560 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
561 if (ValArg.isInvalid())
562 return true;
Tim Northover09df2b02013-07-16 09:47:53 +0000563 TheCall->setArg(0, ValArg.get());
Tim Northovera6306fc2013-10-29 12:32:58 +0000564
565 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
566 // but the custom checker bypasses all default analysis.
567 TheCall->setType(Context.IntTy);
Tim Northover09df2b02013-07-16 09:47:53 +0000568 return false;
569}
570
Nate Begeman26a31422010-06-08 02:47:44 +0000571bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000572 llvm::APSInt Result;
573
Tim Northover09df2b02013-07-16 09:47:53 +0000574 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
575 BuiltinID == ARM::BI__builtin_arm_strex) {
576 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall);
577 }
578
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000579 uint64_t mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000580 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000581 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000582 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000583 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000584#define GET_NEON_OVERLOAD_CHECK
585#include "clang/Basic/arm_neon.inc"
586#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000587 }
588
Nate Begeman0d15c532010-06-13 04:47:52 +0000589 // For NEON intrinsics which are overloaded on vector element type, validate
590 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000591 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000592 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000593 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000594 return true;
595
Bob Wilsonda95f732011-11-08 01:16:11 +0000596 TV = Result.getLimitedValue(64);
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000597 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000598 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000599 << TheCall->getArg(ImmArg)->getSourceRange();
600 }
601
Bob Wilson46482552011-11-16 21:32:23 +0000602 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000603 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000604 Expr *Arg = TheCall->getArg(PtrArgNum);
605 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
606 Arg = ICE->getSubExpr();
607 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
608 QualType RHSTy = RHS.get()->getType();
Kevin Qin624bb5e2013-11-14 03:29:16 +0000609 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context, false);
Bob Wilson46482552011-11-16 21:32:23 +0000610 if (HasConstPtr)
611 EltTy = EltTy.withConst();
612 QualType LHSTy = Context.getPointerType(EltTy);
613 AssignConvertType ConvTy;
614 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
615 if (RHS.isInvalid())
616 return true;
617 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
618 RHS.get(), AA_Assigning))
619 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000620 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000621
Nate Begeman0d15c532010-06-13 04:47:52 +0000622 // For NEON intrinsics which take an immediate value as part of the
623 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000624 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000625 switch (BuiltinID) {
626 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000627 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
628 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000629 case ARM::BI__builtin_arm_vcvtr_f:
630 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao186b26d2013-11-12 21:42:50 +0000631 case ARM::BI__builtin_arm_dmb:
632 case ARM::BI__builtin_arm_dsb: l = 0; u = 15; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000633#define GET_NEON_IMMEDIATE_CHECK
634#include "clang/Basic/arm_neon.inc"
635#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000636 };
637
Douglas Gregor592a4232012-06-29 01:05:22 +0000638 // We can't check the value of a dependent argument.
639 if (TheCall->getArg(i)->isTypeDependent() ||
640 TheCall->getArg(i)->isValueDependent())
641 return false;
642
Nate Begeman61eecf52010-06-14 05:21:25 +0000643 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000644 if (SemaBuiltinConstantArg(TheCall, i, Result))
645 return true;
646
Nate Begeman61eecf52010-06-14 05:21:25 +0000647 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000648 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000649 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000650 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000651 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000652
Nate Begeman99c40bb2010-08-03 21:32:34 +0000653 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000654 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000655}
Daniel Dunbarde454282008-10-02 18:44:07 +0000656
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000657bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
658 unsigned i = 0, l = 0, u = 0;
659 switch (BuiltinID) {
660 default: return false;
661 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
662 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyanbe22cb82012-08-27 12:29:20 +0000663 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
664 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
665 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
666 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
667 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000668 };
669
670 // We can't check the value of a dependent argument.
671 if (TheCall->getArg(i)->isTypeDependent() ||
672 TheCall->getArg(i)->isValueDependent())
673 return false;
674
675 // Check that the immediate argument is actually a constant.
676 llvm::APSInt Result;
677 if (SemaBuiltinConstantArg(TheCall, i, Result))
678 return true;
679
680 // Range check against the upper/lower values for this instruction.
681 unsigned Val = Result.getZExtValue();
682 if (Val < l || Val > u)
683 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
684 << l << u << TheCall->getArg(i)->getSourceRange();
685
686 return false;
687}
688
Richard Smith831421f2012-06-25 20:30:08 +0000689/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
690/// parameter with the FormatAttr's correct format_idx and firstDataArg.
691/// Returns true when the format fits the function and the FormatStringInfo has
692/// been populated.
693bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
694 FormatStringInfo *FSI) {
695 FSI->HasVAListArg = Format->getFirstArg() == 0;
696 FSI->FormatIdx = Format->getFormatIdx() - 1;
697 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssond406bf02009-08-16 01:56:34 +0000698
Richard Smith831421f2012-06-25 20:30:08 +0000699 // The way the format attribute works in GCC, the implicit this argument
700 // of member functions is counted. However, it doesn't appear in our own
701 // lists, so decrement format_idx in that case.
702 if (IsCXXMember) {
703 if(FSI->FormatIdx == 0)
704 return false;
705 --FSI->FormatIdx;
706 if (FSI->FirstDataArg != 0)
707 --FSI->FirstDataArg;
708 }
709 return true;
710}
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Richard Smith831421f2012-06-25 20:30:08 +0000712/// Handles the checks for format strings, non-POD arguments to vararg
713/// functions, and NULL arguments passed to non-NULL parameters.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000714void Sema::checkCall(NamedDecl *FDecl,
715 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000716 unsigned NumProtoArgs,
717 bool IsMemberFunction,
718 SourceLocation Loc,
719 SourceRange Range,
720 VariadicCallType CallType) {
Richard Smith0e218972013-08-05 18:49:43 +0000721 // FIXME: We should check as much as we can in the template definition.
Jordan Rose66360e22012-10-02 01:49:54 +0000722 if (CurContext->isDependentContext())
723 return;
Daniel Dunbarde454282008-10-02 18:44:07 +0000724
Ted Kremenekc82faca2010-09-09 04:33:05 +0000725 // Printf and scanf checking.
Richard Smith0e218972013-08-05 18:49:43 +0000726 llvm::SmallBitVector CheckedVarArgs;
727 if (FDecl) {
Richard Trieu0538f0e2013-06-22 00:20:41 +0000728 for (specific_attr_iterator<FormatAttr>
Benjamin Kramer47abb252013-08-08 11:08:26 +0000729 I = FDecl->specific_attr_begin<FormatAttr>(),
730 E = FDecl->specific_attr_end<FormatAttr>();
Benjamin Kramer541a28f2013-08-09 09:39:17 +0000731 I != E; ++I) {
732 // Only create vector if there are format attributes.
733 CheckedVarArgs.resize(Args.size());
734
Benjamin Kramer47abb252013-08-08 11:08:26 +0000735 CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc, Range,
736 CheckedVarArgs);
Benjamin Kramer541a28f2013-08-09 09:39:17 +0000737 }
Richard Smith0e218972013-08-05 18:49:43 +0000738 }
Richard Smith831421f2012-06-25 20:30:08 +0000739
740 // Refuse POD arguments that weren't caught by the format string
741 // checks above.
Richard Smith0e218972013-08-05 18:49:43 +0000742 if (CallType != VariadicDoesNotApply) {
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000743 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000744 // Args[ArgIdx] can be null in malformed code.
Richard Smith0e218972013-08-05 18:49:43 +0000745 if (const Expr *Arg = Args[ArgIdx]) {
746 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
747 checkVariadicArgument(Arg, CallType);
748 }
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000749 }
Richard Smith0e218972013-08-05 18:49:43 +0000750 }
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Richard Trieu0538f0e2013-06-22 00:20:41 +0000752 if (FDecl) {
753 for (specific_attr_iterator<NonNullAttr>
754 I = FDecl->specific_attr_begin<NonNullAttr>(),
755 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
756 CheckNonNullArguments(*I, Args.data(), Loc);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000757
Richard Trieu0538f0e2013-06-22 00:20:41 +0000758 // Type safety checking.
759 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
760 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
761 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>();
762 i != e; ++i) {
763 CheckArgumentWithTypeTag(*i, Args.data());
764 }
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000765 }
Richard Smith831421f2012-06-25 20:30:08 +0000766}
767
768/// CheckConstructorCall - Check a constructor call for correctness and safety
769/// properties not enforced by the C type system.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000770void Sema::CheckConstructorCall(FunctionDecl *FDecl,
771 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000772 const FunctionProtoType *Proto,
773 SourceLocation Loc) {
774 VariadicCallType CallType =
775 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000776 checkCall(FDecl, Args, Proto->getNumArgs(),
Richard Smith831421f2012-06-25 20:30:08 +0000777 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
778}
779
780/// CheckFunctionCall - Check a direct function call for various correctness
781/// and safety properties not strictly enforced by the C type system.
782bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
783 const FunctionProtoType *Proto) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000784 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
785 isa<CXXMethodDecl>(FDecl);
786 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
787 IsMemberOperatorCall;
Richard Smith831421f2012-06-25 20:30:08 +0000788 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
789 TheCall->getCallee());
790 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Eli Friedman2edcde82012-10-11 00:30:58 +0000791 Expr** Args = TheCall->getArgs();
792 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmandf75b0c2012-10-11 00:34:15 +0000793 if (IsMemberOperatorCall) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000794 // If this is a call to a member operator, hide the first argument
795 // from checkCall.
796 // FIXME: Our choice of AST representation here is less than ideal.
797 ++Args;
798 --NumArgs;
799 }
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000800 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs),
801 NumProtoArgs,
Richard Smith831421f2012-06-25 20:30:08 +0000802 IsMemberFunction, TheCall->getRParenLoc(),
803 TheCall->getCallee()->getSourceRange(), CallType);
804
805 IdentifierInfo *FnInfo = FDecl->getIdentifier();
806 // None of the checks below are needed for functions that don't have
807 // simple names (e.g., C++ conversion functions).
808 if (!FnInfo)
809 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +0000810
Anna Zaks0a151a12012-01-17 00:37:07 +0000811 unsigned CMId = FDecl->getMemoryFunctionKind();
812 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000813 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000814
Anna Zaksd9b859a2012-01-13 21:52:01 +0000815 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000816 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000817 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000818 else if (CMId == Builtin::BIstrncat)
819 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000820 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000821 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000822
Anders Carlssond406bf02009-08-16 01:56:34 +0000823 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000824}
825
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000826bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000827 ArrayRef<const Expr *> Args) {
Richard Smith831421f2012-06-25 20:30:08 +0000828 VariadicCallType CallType =
829 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000830
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000831 checkCall(Method, Args, Method->param_size(),
Richard Smith831421f2012-06-25 20:30:08 +0000832 /*IsMemberFunction=*/false,
833 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000834
835 return false;
836}
837
Richard Trieuf462b012013-06-20 21:03:13 +0000838bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
839 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000840 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
841 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000842 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000843
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000844 QualType Ty = V->getType();
Richard Trieuf462b012013-06-20 21:03:13 +0000845 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000846 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000847
Richard Trieuf462b012013-06-20 21:03:13 +0000848 VariadicCallType CallType;
Richard Trieua4993772013-06-20 23:21:54 +0000849 if (!Proto || !Proto->isVariadic()) {
Richard Trieuf462b012013-06-20 21:03:13 +0000850 CallType = VariadicDoesNotApply;
851 } else if (Ty->isBlockPointerType()) {
852 CallType = VariadicBlock;
853 } else { // Ty->isFunctionPointerType()
854 CallType = VariadicFunction;
855 }
Richard Smith831421f2012-06-25 20:30:08 +0000856 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000857
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000858 checkCall(NDecl,
859 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
860 TheCall->getNumArgs()),
Richard Smith831421f2012-06-25 20:30:08 +0000861 NumProtoArgs, /*IsMemberFunction=*/false,
862 TheCall->getRParenLoc(),
863 TheCall->getCallee()->getSourceRange(), CallType);
864
Anders Carlssond406bf02009-08-16 01:56:34 +0000865 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000866}
867
Richard Trieu0538f0e2013-06-22 00:20:41 +0000868/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
869/// such as function pointers returned from functions.
870bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
871 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
872 TheCall->getCallee());
873 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
874
875 checkCall(/*FDecl=*/0,
876 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
877 TheCall->getNumArgs()),
878 NumProtoArgs, /*IsMemberFunction=*/false,
879 TheCall->getRParenLoc(),
880 TheCall->getCallee()->getSourceRange(), CallType);
881
882 return false;
883}
884
Richard Smithff34d402012-04-12 05:08:17 +0000885ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
886 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000887 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
888 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000889
Richard Smithff34d402012-04-12 05:08:17 +0000890 // All these operations take one of the following forms:
891 enum {
892 // C __c11_atomic_init(A *, C)
893 Init,
894 // C __c11_atomic_load(A *, int)
895 Load,
896 // void __atomic_load(A *, CP, int)
897 Copy,
898 // C __c11_atomic_add(A *, M, int)
899 Arithmetic,
900 // C __atomic_exchange_n(A *, CP, int)
901 Xchg,
902 // void __atomic_exchange(A *, C *, CP, int)
903 GNUXchg,
904 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
905 C11CmpXchg,
906 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
907 GNUCmpXchg
908 } Form = Init;
909 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
910 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
911 // where:
912 // C is an appropriate type,
913 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
914 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
915 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
916 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000917
Richard Smithff34d402012-04-12 05:08:17 +0000918 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
919 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
920 && "need to update code for modified C11 atomics");
921 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
922 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
923 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
924 Op == AtomicExpr::AO__atomic_store_n ||
925 Op == AtomicExpr::AO__atomic_exchange_n ||
926 Op == AtomicExpr::AO__atomic_compare_exchange_n;
927 bool IsAddSub = false;
928
929 switch (Op) {
930 case AtomicExpr::AO__c11_atomic_init:
931 Form = Init;
932 break;
933
934 case AtomicExpr::AO__c11_atomic_load:
935 case AtomicExpr::AO__atomic_load_n:
936 Form = Load;
937 break;
938
939 case AtomicExpr::AO__c11_atomic_store:
940 case AtomicExpr::AO__atomic_load:
941 case AtomicExpr::AO__atomic_store:
942 case AtomicExpr::AO__atomic_store_n:
943 Form = Copy;
944 break;
945
946 case AtomicExpr::AO__c11_atomic_fetch_add:
947 case AtomicExpr::AO__c11_atomic_fetch_sub:
948 case AtomicExpr::AO__atomic_fetch_add:
949 case AtomicExpr::AO__atomic_fetch_sub:
950 case AtomicExpr::AO__atomic_add_fetch:
951 case AtomicExpr::AO__atomic_sub_fetch:
952 IsAddSub = true;
953 // Fall through.
954 case AtomicExpr::AO__c11_atomic_fetch_and:
955 case AtomicExpr::AO__c11_atomic_fetch_or:
956 case AtomicExpr::AO__c11_atomic_fetch_xor:
957 case AtomicExpr::AO__atomic_fetch_and:
958 case AtomicExpr::AO__atomic_fetch_or:
959 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000960 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000961 case AtomicExpr::AO__atomic_and_fetch:
962 case AtomicExpr::AO__atomic_or_fetch:
963 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000964 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000965 Form = Arithmetic;
966 break;
967
968 case AtomicExpr::AO__c11_atomic_exchange:
969 case AtomicExpr::AO__atomic_exchange_n:
970 Form = Xchg;
971 break;
972
973 case AtomicExpr::AO__atomic_exchange:
974 Form = GNUXchg;
975 break;
976
977 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
978 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
979 Form = C11CmpXchg;
980 break;
981
982 case AtomicExpr::AO__atomic_compare_exchange:
983 case AtomicExpr::AO__atomic_compare_exchange_n:
984 Form = GNUCmpXchg;
985 break;
986 }
987
988 // Check we have the right number of arguments.
989 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000990 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_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();
Richard Smithff34d402012-04-12 05:08:17 +0000994 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
995 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000996 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000997 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000998 << TheCall->getCallee()->getSourceRange();
999 return ExprError();
1000 }
1001
Richard Smithff34d402012-04-12 05:08:17 +00001002 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001003 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +00001004 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1005 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1006 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +00001007 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +00001008 << Ptr->getType() << Ptr->getSourceRange();
1009 return ExprError();
1010 }
1011
Richard Smithff34d402012-04-12 05:08:17 +00001012 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1013 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1014 QualType ValType = AtomTy; // 'C'
1015 if (IsC11) {
1016 if (!AtomTy->isAtomicType()) {
1017 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1018 << Ptr->getType() << Ptr->getSourceRange();
1019 return ExprError();
1020 }
Richard Smithbc57b102012-09-15 06:09:58 +00001021 if (AtomTy.isConstQualified()) {
1022 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1023 << Ptr->getType() << Ptr->getSourceRange();
1024 return ExprError();
1025 }
Richard Smithff34d402012-04-12 05:08:17 +00001026 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +00001027 }
Eli Friedman276b0612011-10-11 02:20:01 +00001028
Richard Smithff34d402012-04-12 05:08:17 +00001029 // For an arithmetic operation, the implied arithmetic must be well-formed.
1030 if (Form == Arithmetic) {
1031 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1032 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1033 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1034 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1035 return ExprError();
1036 }
1037 if (!IsAddSub && !ValType->isIntegerType()) {
1038 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1039 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1040 return ExprError();
1041 }
1042 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1043 // For __atomic_*_n operations, the value type must be a scalar integral or
1044 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +00001045 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +00001046 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1047 return ExprError();
1048 }
1049
Eli Friedmana3d727b2013-09-11 03:49:34 +00001050 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1051 !AtomTy->isScalarType()) {
Richard Smithff34d402012-04-12 05:08:17 +00001052 // For GNU atomics, require a trivially-copyable type. This is not part of
1053 // the GNU atomics specification, but we enforce it for sanity.
1054 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +00001055 << Ptr->getType() << Ptr->getSourceRange();
1056 return ExprError();
1057 }
1058
Richard Smithff34d402012-04-12 05:08:17 +00001059 // FIXME: For any builtin other than a load, the ValType must not be
1060 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +00001061
1062 switch (ValType.getObjCLifetime()) {
1063 case Qualifiers::OCL_None:
1064 case Qualifiers::OCL_ExplicitNone:
1065 // okay
1066 break;
1067
1068 case Qualifiers::OCL_Weak:
1069 case Qualifiers::OCL_Strong:
1070 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +00001071 // FIXME: Can this happen? By this point, ValType should be known
1072 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +00001073 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1074 << ValType << Ptr->getSourceRange();
1075 return ExprError();
1076 }
1077
1078 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +00001079 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +00001080 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +00001081 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +00001082 ResultType = Context.BoolTy;
1083
Richard Smithff34d402012-04-12 05:08:17 +00001084 // The type of a parameter passed 'by value'. In the GNU atomics, such
1085 // arguments are actually passed as pointers.
1086 QualType ByValType = ValType; // 'CP'
1087 if (!IsC11 && !IsN)
1088 ByValType = Ptr->getType();
1089
Eli Friedman276b0612011-10-11 02:20:01 +00001090 // The first argument --- the pointer --- has a fixed type; we
1091 // deduce the types of the rest of the arguments accordingly. Walk
1092 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +00001093 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +00001094 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +00001095 if (i < NumVals[Form] + 1) {
1096 switch (i) {
1097 case 1:
1098 // The second argument is the non-atomic operand. For arithmetic, this
1099 // is always passed by value, and for a compare_exchange it is always
1100 // passed by address. For the rest, GNU uses by-address and C11 uses
1101 // by-value.
1102 assert(Form != Load);
1103 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1104 Ty = ValType;
1105 else if (Form == Copy || Form == Xchg)
1106 Ty = ByValType;
1107 else if (Form == Arithmetic)
1108 Ty = Context.getPointerDiffType();
1109 else
1110 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1111 break;
1112 case 2:
1113 // The third argument to compare_exchange / GNU exchange is a
1114 // (pointer to a) desired value.
1115 Ty = ByValType;
1116 break;
1117 case 3:
1118 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1119 Ty = Context.BoolTy;
1120 break;
1121 }
Eli Friedman276b0612011-10-11 02:20:01 +00001122 } else {
1123 // The order(s) are always converted to int.
1124 Ty = Context.IntTy;
1125 }
Richard Smithff34d402012-04-12 05:08:17 +00001126
Eli Friedman276b0612011-10-11 02:20:01 +00001127 InitializedEntity Entity =
1128 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +00001129 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +00001130 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1131 if (Arg.isInvalid())
1132 return true;
1133 TheCall->setArg(i, Arg.get());
1134 }
1135
Richard Smithff34d402012-04-12 05:08:17 +00001136 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001137 SmallVector<Expr*, 5> SubExprs;
1138 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +00001139 switch (Form) {
1140 case Init:
1141 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +00001142 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001143 break;
1144 case Load:
1145 SubExprs.push_back(TheCall->getArg(1)); // Order
1146 break;
1147 case Copy:
1148 case Arithmetic:
1149 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001150 SubExprs.push_back(TheCall->getArg(2)); // Order
1151 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001152 break;
1153 case GNUXchg:
1154 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1155 SubExprs.push_back(TheCall->getArg(3)); // Order
1156 SubExprs.push_back(TheCall->getArg(1)); // Val1
1157 SubExprs.push_back(TheCall->getArg(2)); // Val2
1158 break;
1159 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001160 SubExprs.push_back(TheCall->getArg(3)); // Order
1161 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001162 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +00001163 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +00001164 break;
1165 case GNUCmpXchg:
1166 SubExprs.push_back(TheCall->getArg(4)); // Order
1167 SubExprs.push_back(TheCall->getArg(1)); // Val1
1168 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1169 SubExprs.push_back(TheCall->getArg(2)); // Val2
1170 SubExprs.push_back(TheCall->getArg(3)); // Weak
1171 break;
Eli Friedman276b0612011-10-11 02:20:01 +00001172 }
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00001173
1174 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1175 SubExprs, ResultType, Op,
1176 TheCall->getRParenLoc());
1177
1178 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1179 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1180 Context.AtomicUsesUnsupportedLibcall(AE))
1181 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1182 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001183
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00001184 return Owned(AE);
Eli Friedman276b0612011-10-11 02:20:01 +00001185}
1186
1187
John McCall5f8d6042011-08-27 01:09:30 +00001188/// checkBuiltinArgument - Given a call to a builtin function, perform
1189/// normal type-checking on the given argument, updating the call in
1190/// place. This is useful when a builtin function requires custom
1191/// type-checking for some of its arguments but not necessarily all of
1192/// them.
1193///
1194/// Returns true on error.
1195static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1196 FunctionDecl *Fn = E->getDirectCallee();
1197 assert(Fn && "builtin call without direct callee!");
1198
1199 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1200 InitializedEntity Entity =
1201 InitializedEntity::InitializeParameter(S.Context, Param);
1202
1203 ExprResult Arg = E->getArg(0);
1204 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1205 if (Arg.isInvalid())
1206 return true;
1207
1208 E->setArg(ArgIndex, Arg.take());
1209 return false;
1210}
1211
Chris Lattner5caa3702009-05-08 06:58:22 +00001212/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1213/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1214/// type of its first argument. The main ActOnCallExpr routines have already
1215/// promoted the types of arguments because all of these calls are prototyped as
1216/// void(...).
1217///
1218/// This function goes through and does final semantic checking for these
1219/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +00001220ExprResult
1221Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001222 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +00001223 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1224 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1225
1226 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +00001227 if (TheCall->getNumArgs() < 1) {
1228 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1229 << 0 << 1 << TheCall->getNumArgs()
1230 << TheCall->getCallee()->getSourceRange();
1231 return ExprError();
1232 }
Mike Stump1eb44332009-09-09 15:08:12 +00001233
Chris Lattner5caa3702009-05-08 06:58:22 +00001234 // Inspect the first argument of the atomic builtin. This should always be
1235 // a pointer type, whose element is an integral scalar or pointer type.
1236 // Because it is a pointer type, we don't have to worry about any implicit
1237 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +00001238 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +00001239 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +00001240 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1241 if (FirstArgResult.isInvalid())
1242 return ExprError();
1243 FirstArg = FirstArgResult.take();
1244 TheCall->setArg(0, FirstArg);
1245
John McCallf85e1932011-06-15 23:02:42 +00001246 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1247 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001248 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1249 << FirstArg->getType() << FirstArg->getSourceRange();
1250 return ExprError();
1251 }
Mike Stump1eb44332009-09-09 15:08:12 +00001252
John McCallf85e1932011-06-15 23:02:42 +00001253 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +00001254 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +00001255 !ValType->isBlockPointerType()) {
1256 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1257 << FirstArg->getType() << FirstArg->getSourceRange();
1258 return ExprError();
1259 }
Chris Lattner5caa3702009-05-08 06:58:22 +00001260
John McCallf85e1932011-06-15 23:02:42 +00001261 switch (ValType.getObjCLifetime()) {
1262 case Qualifiers::OCL_None:
1263 case Qualifiers::OCL_ExplicitNone:
1264 // okay
1265 break;
1266
1267 case Qualifiers::OCL_Weak:
1268 case Qualifiers::OCL_Strong:
1269 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001270 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001271 << ValType << FirstArg->getSourceRange();
1272 return ExprError();
1273 }
1274
John McCallb45ae252011-10-05 07:41:44 +00001275 // Strip any qualifiers off ValType.
1276 ValType = ValType.getUnqualifiedType();
1277
Chandler Carruth8d13d222010-07-18 20:54:12 +00001278 // The majority of builtins return a value, but a few have special return
1279 // types, so allow them to override appropriately below.
1280 QualType ResultType = ValType;
1281
Chris Lattner5caa3702009-05-08 06:58:22 +00001282 // We need to figure out which concrete builtin this maps onto. For example,
1283 // __sync_fetch_and_add with a 2 byte object turns into
1284 // __sync_fetch_and_add_2.
1285#define BUILTIN_ROW(x) \
1286 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1287 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +00001288
Chris Lattner5caa3702009-05-08 06:58:22 +00001289 static const unsigned BuiltinIndices[][5] = {
1290 BUILTIN_ROW(__sync_fetch_and_add),
1291 BUILTIN_ROW(__sync_fetch_and_sub),
1292 BUILTIN_ROW(__sync_fetch_and_or),
1293 BUILTIN_ROW(__sync_fetch_and_and),
1294 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +00001295
Chris Lattner5caa3702009-05-08 06:58:22 +00001296 BUILTIN_ROW(__sync_add_and_fetch),
1297 BUILTIN_ROW(__sync_sub_and_fetch),
1298 BUILTIN_ROW(__sync_and_and_fetch),
1299 BUILTIN_ROW(__sync_or_and_fetch),
1300 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001301
Chris Lattner5caa3702009-05-08 06:58:22 +00001302 BUILTIN_ROW(__sync_val_compare_and_swap),
1303 BUILTIN_ROW(__sync_bool_compare_and_swap),
1304 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001305 BUILTIN_ROW(__sync_lock_release),
1306 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001307 };
Mike Stump1eb44332009-09-09 15:08:12 +00001308#undef BUILTIN_ROW
1309
Chris Lattner5caa3702009-05-08 06:58:22 +00001310 // Determine the index of the size.
1311 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001312 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001313 case 1: SizeIndex = 0; break;
1314 case 2: SizeIndex = 1; break;
1315 case 4: SizeIndex = 2; break;
1316 case 8: SizeIndex = 3; break;
1317 case 16: SizeIndex = 4; break;
1318 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001319 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1320 << FirstArg->getType() << FirstArg->getSourceRange();
1321 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001322 }
Mike Stump1eb44332009-09-09 15:08:12 +00001323
Chris Lattner5caa3702009-05-08 06:58:22 +00001324 // Each of these builtins has one pointer argument, followed by some number of
1325 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1326 // that we ignore. Find out which row of BuiltinIndices to read from as well
1327 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001328 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001329 unsigned BuiltinIndex, NumFixed = 1;
1330 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001331 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001332 case Builtin::BI__sync_fetch_and_add:
1333 case Builtin::BI__sync_fetch_and_add_1:
1334 case Builtin::BI__sync_fetch_and_add_2:
1335 case Builtin::BI__sync_fetch_and_add_4:
1336 case Builtin::BI__sync_fetch_and_add_8:
1337 case Builtin::BI__sync_fetch_and_add_16:
1338 BuiltinIndex = 0;
1339 break;
1340
1341 case Builtin::BI__sync_fetch_and_sub:
1342 case Builtin::BI__sync_fetch_and_sub_1:
1343 case Builtin::BI__sync_fetch_and_sub_2:
1344 case Builtin::BI__sync_fetch_and_sub_4:
1345 case Builtin::BI__sync_fetch_and_sub_8:
1346 case Builtin::BI__sync_fetch_and_sub_16:
1347 BuiltinIndex = 1;
1348 break;
1349
1350 case Builtin::BI__sync_fetch_and_or:
1351 case Builtin::BI__sync_fetch_and_or_1:
1352 case Builtin::BI__sync_fetch_and_or_2:
1353 case Builtin::BI__sync_fetch_and_or_4:
1354 case Builtin::BI__sync_fetch_and_or_8:
1355 case Builtin::BI__sync_fetch_and_or_16:
1356 BuiltinIndex = 2;
1357 break;
1358
1359 case Builtin::BI__sync_fetch_and_and:
1360 case Builtin::BI__sync_fetch_and_and_1:
1361 case Builtin::BI__sync_fetch_and_and_2:
1362 case Builtin::BI__sync_fetch_and_and_4:
1363 case Builtin::BI__sync_fetch_and_and_8:
1364 case Builtin::BI__sync_fetch_and_and_16:
1365 BuiltinIndex = 3;
1366 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001367
Douglas Gregora9766412011-11-28 16:30:08 +00001368 case Builtin::BI__sync_fetch_and_xor:
1369 case Builtin::BI__sync_fetch_and_xor_1:
1370 case Builtin::BI__sync_fetch_and_xor_2:
1371 case Builtin::BI__sync_fetch_and_xor_4:
1372 case Builtin::BI__sync_fetch_and_xor_8:
1373 case Builtin::BI__sync_fetch_and_xor_16:
1374 BuiltinIndex = 4;
1375 break;
1376
1377 case Builtin::BI__sync_add_and_fetch:
1378 case Builtin::BI__sync_add_and_fetch_1:
1379 case Builtin::BI__sync_add_and_fetch_2:
1380 case Builtin::BI__sync_add_and_fetch_4:
1381 case Builtin::BI__sync_add_and_fetch_8:
1382 case Builtin::BI__sync_add_and_fetch_16:
1383 BuiltinIndex = 5;
1384 break;
1385
1386 case Builtin::BI__sync_sub_and_fetch:
1387 case Builtin::BI__sync_sub_and_fetch_1:
1388 case Builtin::BI__sync_sub_and_fetch_2:
1389 case Builtin::BI__sync_sub_and_fetch_4:
1390 case Builtin::BI__sync_sub_and_fetch_8:
1391 case Builtin::BI__sync_sub_and_fetch_16:
1392 BuiltinIndex = 6;
1393 break;
1394
1395 case Builtin::BI__sync_and_and_fetch:
1396 case Builtin::BI__sync_and_and_fetch_1:
1397 case Builtin::BI__sync_and_and_fetch_2:
1398 case Builtin::BI__sync_and_and_fetch_4:
1399 case Builtin::BI__sync_and_and_fetch_8:
1400 case Builtin::BI__sync_and_and_fetch_16:
1401 BuiltinIndex = 7;
1402 break;
1403
1404 case Builtin::BI__sync_or_and_fetch:
1405 case Builtin::BI__sync_or_and_fetch_1:
1406 case Builtin::BI__sync_or_and_fetch_2:
1407 case Builtin::BI__sync_or_and_fetch_4:
1408 case Builtin::BI__sync_or_and_fetch_8:
1409 case Builtin::BI__sync_or_and_fetch_16:
1410 BuiltinIndex = 8;
1411 break;
1412
1413 case Builtin::BI__sync_xor_and_fetch:
1414 case Builtin::BI__sync_xor_and_fetch_1:
1415 case Builtin::BI__sync_xor_and_fetch_2:
1416 case Builtin::BI__sync_xor_and_fetch_4:
1417 case Builtin::BI__sync_xor_and_fetch_8:
1418 case Builtin::BI__sync_xor_and_fetch_16:
1419 BuiltinIndex = 9;
1420 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001421
Chris Lattner5caa3702009-05-08 06:58:22 +00001422 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001423 case Builtin::BI__sync_val_compare_and_swap_1:
1424 case Builtin::BI__sync_val_compare_and_swap_2:
1425 case Builtin::BI__sync_val_compare_and_swap_4:
1426 case Builtin::BI__sync_val_compare_and_swap_8:
1427 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001428 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001429 NumFixed = 2;
1430 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001431
Chris Lattner5caa3702009-05-08 06:58:22 +00001432 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001433 case Builtin::BI__sync_bool_compare_and_swap_1:
1434 case Builtin::BI__sync_bool_compare_and_swap_2:
1435 case Builtin::BI__sync_bool_compare_and_swap_4:
1436 case Builtin::BI__sync_bool_compare_and_swap_8:
1437 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001438 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001439 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001440 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001441 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001442
1443 case Builtin::BI__sync_lock_test_and_set:
1444 case Builtin::BI__sync_lock_test_and_set_1:
1445 case Builtin::BI__sync_lock_test_and_set_2:
1446 case Builtin::BI__sync_lock_test_and_set_4:
1447 case Builtin::BI__sync_lock_test_and_set_8:
1448 case Builtin::BI__sync_lock_test_and_set_16:
1449 BuiltinIndex = 12;
1450 break;
1451
Chris Lattner5caa3702009-05-08 06:58:22 +00001452 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001453 case Builtin::BI__sync_lock_release_1:
1454 case Builtin::BI__sync_lock_release_2:
1455 case Builtin::BI__sync_lock_release_4:
1456 case Builtin::BI__sync_lock_release_8:
1457 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001458 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001459 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001460 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001461 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001462
1463 case Builtin::BI__sync_swap:
1464 case Builtin::BI__sync_swap_1:
1465 case Builtin::BI__sync_swap_2:
1466 case Builtin::BI__sync_swap_4:
1467 case Builtin::BI__sync_swap_8:
1468 case Builtin::BI__sync_swap_16:
1469 BuiltinIndex = 14;
1470 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001471 }
Mike Stump1eb44332009-09-09 15:08:12 +00001472
Chris Lattner5caa3702009-05-08 06:58:22 +00001473 // Now that we know how many fixed arguments we expect, first check that we
1474 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001475 if (TheCall->getNumArgs() < 1+NumFixed) {
1476 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1477 << 0 << 1+NumFixed << TheCall->getNumArgs()
1478 << TheCall->getCallee()->getSourceRange();
1479 return ExprError();
1480 }
Mike Stump1eb44332009-09-09 15:08:12 +00001481
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001482 // Get the decl for the concrete builtin from this, we can tell what the
1483 // concrete integer type we should convert to is.
1484 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1485 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001486 FunctionDecl *NewBuiltinDecl;
1487 if (NewBuiltinID == BuiltinID)
1488 NewBuiltinDecl = FDecl;
1489 else {
1490 // Perform builtin lookup to avoid redeclaring it.
1491 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1492 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1493 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1494 assert(Res.getFoundDecl());
1495 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1496 if (NewBuiltinDecl == 0)
1497 return ExprError();
1498 }
Chandler Carruthd2014572010-07-09 18:59:35 +00001499
John McCallf871d0c2010-08-07 06:22:56 +00001500 // The first argument --- the pointer --- has a fixed type; we
1501 // deduce the types of the rest of the arguments accordingly. Walk
1502 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001503 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001504 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001505
Chris Lattner5caa3702009-05-08 06:58:22 +00001506 // GCC does an implicit conversion to the pointer or integer ValType. This
1507 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001508 // Initialize the argument.
1509 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1510 ValType, /*consume*/ false);
1511 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001512 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001513 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001514
Chris Lattner5caa3702009-05-08 06:58:22 +00001515 // Okay, we have something that *can* be converted to the right type. Check
1516 // to see if there is a potentially weird extension going on here. This can
1517 // happen when you do an atomic operation on something like an char* and
1518 // pass in 42. The 42 gets converted to char. This is even more strange
1519 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001520 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001521 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001522 }
Mike Stump1eb44332009-09-09 15:08:12 +00001523
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001524 ASTContext& Context = this->getASTContext();
1525
1526 // Create a new DeclRefExpr to refer to the new decl.
1527 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1528 Context,
1529 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001530 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001531 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001532 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001533 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001534 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001535 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001536
Chris Lattner5caa3702009-05-08 06:58:22 +00001537 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001538 // FIXME: This loses syntactic information.
1539 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1540 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1541 CK_BuiltinFnToFnPtr);
John Wiegley429bb272011-04-08 18:41:53 +00001542 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001543
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001544 // Change the result type of the call to match the original value type. This
1545 // is arbitrary, but the codegen for these builtins ins design to handle it
1546 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001547 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001548
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001549 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001550}
1551
Chris Lattner69039812009-02-18 06:01:06 +00001552/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001553/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001554/// Note: It might also make sense to do the UTF-16 conversion here (would
1555/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001556bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001557 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001558 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1559
Douglas Gregor5cee1192011-07-27 05:40:30 +00001560 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001561 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1562 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001563 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001564 }
Mike Stump1eb44332009-09-09 15:08:12 +00001565
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001566 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001567 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001568 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001569 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00001570 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001571 UTF16 *ToPtr = &ToBuf[0];
1572
1573 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1574 &ToPtr, ToPtr + NumBytes,
1575 strictConversion);
1576 // Check for conversion failure.
1577 if (Result != conversionOK)
1578 Diag(Arg->getLocStart(),
1579 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1580 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001581 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001582}
1583
Chris Lattnerc27c6652007-12-20 00:05:45 +00001584/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1585/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001586bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1587 Expr *Fn = TheCall->getCallee();
1588 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001589 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001590 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001591 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1592 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001593 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001594 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001595 return true;
1596 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001597
1598 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001599 return Diag(TheCall->getLocEnd(),
1600 diag::err_typecheck_call_too_few_args_at_least)
1601 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001602 }
1603
John McCall5f8d6042011-08-27 01:09:30 +00001604 // Type-check the first argument normally.
1605 if (checkBuiltinArgument(*this, TheCall, 0))
1606 return true;
1607
Chris Lattnerc27c6652007-12-20 00:05:45 +00001608 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001609 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001610 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001611 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001612 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001613 else if (FunctionDecl *FD = getCurFunctionDecl())
1614 isVariadic = FD->isVariadic();
1615 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001616 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001617
Chris Lattnerc27c6652007-12-20 00:05:45 +00001618 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001619 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1620 return true;
1621 }
Mike Stump1eb44332009-09-09 15:08:12 +00001622
Chris Lattner30ce3442007-12-19 23:59:04 +00001623 // Verify that the second argument to the builtin is the last argument of the
1624 // current function or method.
1625 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001626 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001627
Nico Weberb07d4482013-05-24 23:31:57 +00001628 // These are valid if SecondArgIsLastNamedArgument is false after the next
1629 // block.
1630 QualType Type;
1631 SourceLocation ParamLoc;
1632
Anders Carlsson88cf2262008-02-11 04:20:54 +00001633 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1634 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001635 // FIXME: This isn't correct for methods (results in bogus warning).
1636 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001637 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001638 if (CurBlock)
1639 LastArg = *(CurBlock->TheDecl->param_end()-1);
1640 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001641 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001642 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001643 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001644 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weberb07d4482013-05-24 23:31:57 +00001645
1646 Type = PV->getType();
1647 ParamLoc = PV->getLocation();
Chris Lattner30ce3442007-12-19 23:59:04 +00001648 }
1649 }
Mike Stump1eb44332009-09-09 15:08:12 +00001650
Chris Lattner30ce3442007-12-19 23:59:04 +00001651 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001652 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001653 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weberb07d4482013-05-24 23:31:57 +00001654 else if (Type->isReferenceType()) {
1655 Diag(Arg->getLocStart(),
1656 diag::warn_va_start_of_reference_type_is_undefined);
1657 Diag(ParamLoc, diag::note_parameter_type) << Type;
1658 }
1659
Enea Zaffanella54de9bb2013-11-07 08:14:26 +00001660 TheCall->setType(Context.VoidTy);
Chris Lattner30ce3442007-12-19 23:59:04 +00001661 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001662}
Chris Lattner30ce3442007-12-19 23:59:04 +00001663
Chris Lattner1b9a0792007-12-20 00:26:33 +00001664/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1665/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001666bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1667 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001668 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001669 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001670 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001671 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001672 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001673 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001674 << SourceRange(TheCall->getArg(2)->getLocStart(),
1675 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001676
John Wiegley429bb272011-04-08 18:41:53 +00001677 ExprResult OrigArg0 = TheCall->getArg(0);
1678 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001679
Chris Lattner1b9a0792007-12-20 00:26:33 +00001680 // Do standard promotions between the two arguments, returning their common
1681 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001682 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001683 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1684 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001685
1686 // Make sure any conversions are pushed back into the call; this is
1687 // type safe since unordered compare builtins are declared as "_Bool
1688 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001689 TheCall->setArg(0, OrigArg0.get());
1690 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001691
John Wiegley429bb272011-04-08 18:41:53 +00001692 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001693 return false;
1694
Chris Lattner1b9a0792007-12-20 00:26:33 +00001695 // If the common type isn't a real floating type, then the arguments were
1696 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001697 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001698 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001699 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001700 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1701 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Chris Lattner1b9a0792007-12-20 00:26:33 +00001703 return false;
1704}
1705
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001706/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1707/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001708/// to check everything. We expect the last argument to be a floating point
1709/// value.
1710bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1711 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001712 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001713 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001714 if (TheCall->getNumArgs() > NumArgs)
1715 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001716 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001717 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001718 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001719 (*(TheCall->arg_end()-1))->getLocEnd());
1720
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001721 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001722
Eli Friedman9ac6f622009-08-31 20:06:00 +00001723 if (OrigArg->isTypeDependent())
1724 return false;
1725
Chris Lattner81368fb2010-05-06 05:50:07 +00001726 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001727 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001728 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001729 diag::err_typecheck_call_invalid_unary_fp)
1730 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001731
Chris Lattner81368fb2010-05-06 05:50:07 +00001732 // If this is an implicit conversion from float -> double, remove it.
1733 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1734 Expr *CastArg = Cast->getSubExpr();
1735 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1736 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1737 "promotion from float to double is the only expected cast here");
1738 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001739 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001740 }
1741 }
1742
Eli Friedman9ac6f622009-08-31 20:06:00 +00001743 return false;
1744}
1745
Eli Friedmand38617c2008-05-14 19:38:39 +00001746/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1747// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001748ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001749 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001750 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001751 diag::err_typecheck_call_too_few_args_at_least)
Craig Topperb44545a2013-07-28 21:50:10 +00001752 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1753 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001754
Nate Begeman37b6a572010-06-08 00:16:34 +00001755 // Determine which of the following types of shufflevector we're checking:
1756 // 1) unary, vector mask: (lhs, mask)
1757 // 2) binary, vector mask: (lhs, rhs, mask)
1758 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1759 QualType resType = TheCall->getArg(0)->getType();
1760 unsigned numElements = 0;
Craig Toppere3fbbe92013-07-19 04:46:31 +00001761
Douglas Gregorcde01732009-05-19 22:10:17 +00001762 if (!TheCall->getArg(0)->isTypeDependent() &&
1763 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001764 QualType LHSType = TheCall->getArg(0)->getType();
1765 QualType RHSType = TheCall->getArg(1)->getType();
Craig Toppere3fbbe92013-07-19 04:46:31 +00001766
Craig Topperbbe759c2013-07-29 06:47:04 +00001767 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1768 return ExprError(Diag(TheCall->getLocStart(),
1769 diag::err_shufflevector_non_vector)
1770 << SourceRange(TheCall->getArg(0)->getLocStart(),
1771 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00001772
Nate Begeman37b6a572010-06-08 00:16:34 +00001773 numElements = LHSType->getAs<VectorType>()->getNumElements();
1774 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001775
Nate Begeman37b6a572010-06-08 00:16:34 +00001776 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1777 // with mask. If so, verify that RHS is an integer vector type with the
1778 // same number of elts as lhs.
1779 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru4cb3d902013-07-06 08:00:09 +00001780 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001781 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbbe759c2013-07-29 06:47:04 +00001782 return ExprError(Diag(TheCall->getLocStart(),
1783 diag::err_shufflevector_incompatible_vector)
1784 << SourceRange(TheCall->getArg(1)->getLocStart(),
1785 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00001786 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbbe759c2013-07-29 06:47:04 +00001787 return ExprError(Diag(TheCall->getLocStart(),
1788 diag::err_shufflevector_incompatible_vector)
1789 << SourceRange(TheCall->getArg(0)->getLocStart(),
1790 TheCall->getArg(1)->getLocEnd()));
Nate Begeman37b6a572010-06-08 00:16:34 +00001791 } else if (numElements != numResElements) {
1792 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001793 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001794 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001795 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001796 }
1797
1798 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001799 if (TheCall->getArg(i)->isTypeDependent() ||
1800 TheCall->getArg(i)->isValueDependent())
1801 continue;
1802
Nate Begeman37b6a572010-06-08 00:16:34 +00001803 llvm::APSInt Result(32);
1804 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1805 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00001806 diag::err_shufflevector_nonconstant_argument)
1807 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001808
Craig Topper6f4f8082013-08-03 17:40:38 +00001809 // Allow -1 which will be translated to undef in the IR.
1810 if (Result.isSigned() && Result.isAllOnesValue())
1811 continue;
1812
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001813 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001814 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00001815 diag::err_shufflevector_argument_too_large)
1816 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001817 }
1818
Chris Lattner5f9e2722011-07-23 10:55:15 +00001819 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001820
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001821 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001822 exprs.push_back(TheCall->getArg(i));
1823 TheCall->setArg(i, 0);
1824 }
1825
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001826 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001827 TheCall->getCallee()->getLocStart(),
1828 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001829}
Chris Lattner30ce3442007-12-19 23:59:04 +00001830
Hal Finkel414a1bd2013-09-18 03:29:45 +00001831/// SemaConvertVectorExpr - Handle __builtin_convertvector
1832ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1833 SourceLocation BuiltinLoc,
1834 SourceLocation RParenLoc) {
1835 ExprValueKind VK = VK_RValue;
1836 ExprObjectKind OK = OK_Ordinary;
1837 QualType DstTy = TInfo->getType();
1838 QualType SrcTy = E->getType();
1839
1840 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1841 return ExprError(Diag(BuiltinLoc,
1842 diag::err_convertvector_non_vector)
1843 << E->getSourceRange());
1844 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1845 return ExprError(Diag(BuiltinLoc,
1846 diag::err_convertvector_non_vector_type));
1847
1848 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1849 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1850 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1851 if (SrcElts != DstElts)
1852 return ExprError(Diag(BuiltinLoc,
1853 diag::err_convertvector_incompatible_vector)
1854 << E->getSourceRange());
1855 }
1856
1857 return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
1858 BuiltinLoc, RParenLoc));
1859
1860}
1861
Daniel Dunbar4493f792008-07-21 22:59:13 +00001862/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1863// This is declared to take (const void*, ...) and can take two
1864// optional constant int args.
1865bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001866 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001867
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001868 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001869 return Diag(TheCall->getLocEnd(),
1870 diag::err_typecheck_call_too_many_args_at_most)
1871 << 0 /*function call*/ << 3 << NumArgs
1872 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001873
1874 // Argument 0 is checked for us and the remaining arguments must be
1875 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001876 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001877 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001878
1879 // We can't check the value of a dependent argument.
1880 if (Arg->isTypeDependent() || Arg->isValueDependent())
1881 continue;
1882
Eli Friedman9aef7262009-12-04 00:30:06 +00001883 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001884 if (SemaBuiltinConstantArg(TheCall, i, Result))
1885 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001886
Daniel Dunbar4493f792008-07-21 22:59:13 +00001887 // FIXME: gcc issues a warning and rewrites these to 0. These
1888 // seems especially odd for the third argument since the default
1889 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001890 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001891 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001892 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001893 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001894 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001895 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001896 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001897 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001898 }
1899 }
1900
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001901 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001902}
1903
Eric Christopher691ebc32010-04-17 02:26:23 +00001904/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1905/// TheCall is a constant expression.
1906bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1907 llvm::APSInt &Result) {
1908 Expr *Arg = TheCall->getArg(ArgNum);
1909 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1910 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1911
1912 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1913
1914 if (!Arg->isIntegerConstantExpr(Result, Context))
1915 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001916 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001917
Chris Lattner21fb98e2009-09-23 06:06:36 +00001918 return false;
1919}
1920
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001921/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1922/// int type). This simply type checks that type is one of the defined
1923/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001924// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001925bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001926 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001927
1928 // We can't check the value of a dependent argument.
1929 if (TheCall->getArg(1)->isTypeDependent() ||
1930 TheCall->getArg(1)->isValueDependent())
1931 return false;
1932
Eric Christopher691ebc32010-04-17 02:26:23 +00001933 // Check constant-ness first.
1934 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1935 return true;
1936
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001937 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001938 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001939 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1940 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001941 }
1942
1943 return false;
1944}
1945
Eli Friedman586d6a82009-05-03 06:04:26 +00001946/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001947/// This checks that val is a constant 1.
1948bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1949 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001950 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001951
Eric Christopher691ebc32010-04-17 02:26:23 +00001952 // TODO: This is less than ideal. Overload this to take a value.
1953 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1954 return true;
1955
1956 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001957 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1958 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1959
1960 return false;
1961}
1962
Richard Smith0e218972013-08-05 18:49:43 +00001963namespace {
1964enum StringLiteralCheckType {
1965 SLCT_NotALiteral,
1966 SLCT_UncheckedLiteral,
1967 SLCT_CheckedLiteral
1968};
1969}
1970
Richard Smith831421f2012-06-25 20:30:08 +00001971// Determine if an expression is a string literal or constant string.
1972// If this function returns false on the arguments to a function expecting a
1973// format string, we will usually need to emit a warning.
1974// True string literals are then checked by CheckFormatString.
Richard Smith0e218972013-08-05 18:49:43 +00001975static StringLiteralCheckType
1976checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
1977 bool HasVAListArg, unsigned format_idx,
1978 unsigned firstDataArg, Sema::FormatStringType Type,
1979 Sema::VariadicCallType CallType, bool InFunctionCall,
1980 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001981 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001982 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001983 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001984
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001985 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001986
Richard Smith0e218972013-08-05 18:49:43 +00001987 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikiea73cdcb2012-02-10 21:07:25 +00001988 // Technically -Wformat-nonliteral does not warn about this case.
1989 // The behavior of printf and friends in this case is implementation
1990 // dependent. Ideally if the format string cannot be null then
1991 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith0e218972013-08-05 18:49:43 +00001992 return SLCT_UncheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001993
Ted Kremenekd30ef872009-01-12 23:09:09 +00001994 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001995 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001996 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001997 // The expression is a literal if both sub-expressions were, and it was
1998 // completely checked only if both sub-expressions were checked.
1999 const AbstractConditionalOperator *C =
2000 cast<AbstractConditionalOperator>(E);
2001 StringLiteralCheckType Left =
Richard Smith0e218972013-08-05 18:49:43 +00002002 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00002003 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002004 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002005 if (Left == SLCT_NotALiteral)
2006 return SLCT_NotALiteral;
2007 StringLiteralCheckType Right =
Richard Smith0e218972013-08-05 18:49:43 +00002008 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00002009 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002010 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002011 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002012 }
2013
2014 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00002015 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2016 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002017 }
2018
John McCall56ca35d2011-02-17 10:25:35 +00002019 case Stmt::OpaqueValueExprClass:
2020 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2021 E = src;
2022 goto tryAgain;
2023 }
Richard Smith831421f2012-06-25 20:30:08 +00002024 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00002025
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00002026 case Stmt::PredefinedExprClass:
2027 // While __func__, etc., are technically not string literals, they
2028 // cannot contain format specifiers and thus are not a security
2029 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00002030 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00002031
Ted Kremenek082d9362009-03-20 21:35:28 +00002032 case Stmt::DeclRefExprClass: {
2033 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002034
Ted Kremenek082d9362009-03-20 21:35:28 +00002035 // As an exception, do not flag errors for variables binding to
2036 // const string literals.
2037 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2038 bool isConstant = false;
2039 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00002040
Richard Smith0e218972013-08-05 18:49:43 +00002041 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2042 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002043 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smith0e218972013-08-05 18:49:43 +00002044 isConstant = T.isConstant(S.Context) &&
2045 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00002046 } else if (T->isObjCObjectPointerType()) {
2047 // In ObjC, there is usually no "const ObjectPointer" type,
2048 // so don't check if the pointee type is constant.
Richard Smith0e218972013-08-05 18:49:43 +00002049 isConstant = T.isConstant(S.Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00002050 }
Mike Stump1eb44332009-09-09 15:08:12 +00002051
Ted Kremenek082d9362009-03-20 21:35:28 +00002052 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002053 if (const Expr *Init = VD->getAnyInitializer()) {
2054 // Look through initializers like const char c[] = { "foo" }
2055 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2056 if (InitList->isStringLiteralInit())
2057 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2058 }
Richard Smith0e218972013-08-05 18:49:43 +00002059 return checkFormatStringExpr(S, Init, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002060 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002061 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002062 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002063 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002064 }
Mike Stump1eb44332009-09-09 15:08:12 +00002065
Anders Carlssond966a552009-06-28 19:55:58 +00002066 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2067 // special check to see if the format string is a function parameter
2068 // of the function calling the printf function. If the function
2069 // has an attribute indicating it is a printf-like function, then we
2070 // should suppress warnings concerning non-literals being used in a call
2071 // to a vprintf function. For example:
2072 //
2073 // void
2074 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2075 // va_list ap;
2076 // va_start(ap, fmt);
2077 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2078 // ...
Richard Smith0e218972013-08-05 18:49:43 +00002079 // }
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002080 if (HasVAListArg) {
2081 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2082 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2083 int PVIndex = PV->getFunctionScopeIndex() + 1;
2084 for (specific_attr_iterator<FormatAttr>
2085 i = ND->specific_attr_begin<FormatAttr>(),
2086 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
2087 FormatAttr *PVFormat = *i;
2088 // adjust for implicit parameter
2089 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2090 if (MD->isInstance())
2091 ++PVIndex;
2092 // We also check if the formats are compatible.
2093 // We can't pass a 'scanf' string to a 'printf' function.
2094 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smith0e218972013-08-05 18:49:43 +00002095 Type == S.GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00002096 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002097 }
2098 }
2099 }
2100 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002101 }
Mike Stump1eb44332009-09-09 15:08:12 +00002102
Richard Smith831421f2012-06-25 20:30:08 +00002103 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00002104 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00002105
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002106 case Stmt::CallExprClass:
2107 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00002108 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002109 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2110 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2111 unsigned ArgIndex = FA->getFormatIdx();
2112 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2113 if (MD->isInstance())
2114 --ArgIndex;
2115 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002116
Richard Smith0e218972013-08-05 18:49:43 +00002117 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002118 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002119 Type, CallType, InFunctionCall,
2120 CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002121 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2122 unsigned BuiltinID = FD->getBuiltinID();
2123 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2124 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2125 const Expr *Arg = CE->getArg(0);
Richard Smith0e218972013-08-05 18:49:43 +00002126 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002127 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002128 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002129 InFunctionCall, CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002130 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00002131 }
2132 }
Mike Stump1eb44332009-09-09 15:08:12 +00002133
Richard Smith831421f2012-06-25 20:30:08 +00002134 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00002135 }
Fariborz Jahanianc85832f2013-10-18 21:20:34 +00002136
2137 case Stmt::ObjCMessageExprClass: {
2138 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(E);
2139 if (const ObjCMethodDecl *MDecl = ME->getMethodDecl()) {
2140 if (const NamedDecl *ND = dyn_cast<NamedDecl>(MDecl)) {
2141 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2142 unsigned ArgIndex = FA->getFormatIdx();
2143 if (ArgIndex <= ME->getNumArgs()) {
2144 const Expr *Arg = ME->getArg(ArgIndex-1);
2145 return checkFormatStringExpr(S, Arg, Args,
2146 HasVAListArg, format_idx,
2147 firstDataArg, Type, CallType,
2148 InFunctionCall, CheckedVarArgs);
2149 }
2150 }
2151 }
2152 }
2153
2154 return SLCT_NotALiteral;
2155 }
2156
Ted Kremenek082d9362009-03-20 21:35:28 +00002157 case Stmt::ObjCStringLiteralClass:
2158 case Stmt::StringLiteralClass: {
2159 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002160
Ted Kremenek082d9362009-03-20 21:35:28 +00002161 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00002162 StrE = ObjCFExpr->getString();
2163 else
Ted Kremenek082d9362009-03-20 21:35:28 +00002164 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002165
Ted Kremenekd30ef872009-01-12 23:09:09 +00002166 if (StrE) {
Richard Smith0e218972013-08-05 18:49:43 +00002167 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2168 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002169 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002170 }
Mike Stump1eb44332009-09-09 15:08:12 +00002171
Richard Smith831421f2012-06-25 20:30:08 +00002172 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002173 }
Mike Stump1eb44332009-09-09 15:08:12 +00002174
Ted Kremenek082d9362009-03-20 21:35:28 +00002175 default:
Richard Smith831421f2012-06-25 20:30:08 +00002176 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002177 }
2178}
2179
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002180void
Mike Stump1eb44332009-09-09 15:08:12 +00002181Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00002182 const Expr * const *ExprArgs,
2183 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00002184 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
2185 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002186 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00002187 const Expr *ArgExpr = ExprArgs[*i];
Nick Lewycky3edf3872013-01-23 05:08:29 +00002188
2189 // As a special case, transparent unions initialized with zero are
2190 // considered null for the purposes of the nonnull attribute.
2191 if (const RecordType *UT = ArgExpr->getType()->getAsUnionType()) {
2192 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2193 if (const CompoundLiteralExpr *CLE =
2194 dyn_cast<CompoundLiteralExpr>(ArgExpr))
2195 if (const InitListExpr *ILE =
2196 dyn_cast<InitListExpr>(CLE->getInitializer()))
2197 ArgExpr = ILE->getInit(0);
2198 }
2199
2200 bool Result;
2201 if (ArgExpr->EvaluateAsBooleanCondition(Result, Context) && !Result)
Nick Lewycky909a70d2011-03-25 01:44:32 +00002202 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002203 }
2204}
Ted Kremenekd30ef872009-01-12 23:09:09 +00002205
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002206Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmancaa5ab22013-09-03 21:02:22 +00002207 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002208 .Case("scanf", FST_Scanf)
2209 .Cases("printf", "printf0", FST_Printf)
2210 .Cases("NSString", "CFString", FST_NSString)
2211 .Case("strftime", FST_Strftime)
2212 .Case("strfmon", FST_Strfmon)
2213 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2214 .Default(FST_Unknown);
2215}
2216
Jordan Roseddcfbc92012-07-19 18:10:23 +00002217/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00002218/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00002219/// Returns true if a format string has been fully checked.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002220bool Sema::CheckFormatArguments(const FormatAttr *Format,
2221 ArrayRef<const Expr *> Args,
2222 bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002223 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002224 SourceLocation Loc, SourceRange Range,
2225 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith831421f2012-06-25 20:30:08 +00002226 FormatStringInfo FSI;
2227 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002228 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith831421f2012-06-25 20:30:08 +00002229 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smith0e218972013-08-05 18:49:43 +00002230 CallType, Loc, Range, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002231 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002232}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00002233
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002234bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002235 bool HasVAListArg, unsigned format_idx,
2236 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002237 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002238 SourceLocation Loc, SourceRange Range,
2239 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002240 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002241 if (format_idx >= Args.size()) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002242 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00002243 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00002244 }
Mike Stump1eb44332009-09-09 15:08:12 +00002245
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002246 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00002247
Chris Lattner59907c42007-08-10 20:18:51 +00002248 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00002249 //
Ted Kremenek71895b92007-08-14 17:39:48 +00002250 // Dynamically generated format strings are difficult to
2251 // automatically vet at compile time. Requiring that format strings
2252 // are string literals: (1) permits the checking of format strings by
2253 // the compiler and thereby (2) can practically remove the source of
2254 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002255
Mike Stump1eb44332009-09-09 15:08:12 +00002256 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002257 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00002258 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002259 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00002260 StringLiteralCheckType CT =
Richard Smith0e218972013-08-05 18:49:43 +00002261 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2262 format_idx, firstDataArg, Type, CallType,
2263 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002264 if (CT != SLCT_NotALiteral)
2265 // Literal format string found, check done!
2266 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002267
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002268 // Strftime is particular as it always uses a single 'time' argument,
2269 // so it is safe to pass a non-literal string.
2270 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00002271 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002272
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002273 // Do not emit diag when the string param is a macro expansion and the
2274 // format is either NSString or CFString. This is a hack to prevent
2275 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2276 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00002277 if (Type == FST_NSString &&
2278 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00002279 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002280
Chris Lattner655f1412009-04-29 04:59:47 +00002281 // If there are no arguments specified, warn with -Wformat-security, otherwise
2282 // warn only with -Wformat-nonliteral.
Eli Friedman2243e782013-06-18 18:10:01 +00002283 if (Args.size() == firstDataArg)
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002284 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002285 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00002286 << OrigFormatExpr->getSourceRange();
2287 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002288 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002289 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00002290 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00002291 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002292}
Ted Kremenek71895b92007-08-14 17:39:48 +00002293
Ted Kremeneke0e53132010-01-28 23:39:18 +00002294namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00002295class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2296protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00002297 Sema &S;
2298 const StringLiteral *FExpr;
2299 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00002300 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002301 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002302 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00002303 const bool HasVAListArg;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002304 ArrayRef<const Expr *> Args;
Ted Kremenek0d277352010-01-29 01:06:55 +00002305 unsigned FormatIdx;
Richard Smith0e218972013-08-05 18:49:43 +00002306 llvm::SmallBitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00002307 bool usesPositionalArgs;
2308 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00002309 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00002310 Sema::VariadicCallType CallType;
Richard Smith0e218972013-08-05 18:49:43 +00002311 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002312public:
Ted Kremenek826a3452010-07-16 02:11:22 +00002313 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00002314 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002315 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002316 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002317 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00002318 Sema::VariadicCallType callType,
2319 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremeneke0e53132010-01-28 23:39:18 +00002320 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00002321 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2322 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002323 Args(Args), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00002324 usesPositionalArgs(false), atFirstArg(true),
Richard Smith0e218972013-08-05 18:49:43 +00002325 inFunctionCall(inFunctionCall), CallType(callType),
2326 CheckedVarArgs(CheckedVarArgs) {
2327 CoveredArgs.resize(numDataArgs);
2328 CoveredArgs.reset();
2329 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002330
Ted Kremenek07d161f2010-01-29 01:50:07 +00002331 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002332
Ted Kremenek826a3452010-07-16 02:11:22 +00002333 void HandleIncompleteSpecifier(const char *startSpecifier,
2334 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00002335
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002336 void HandleInvalidLengthModifier(
2337 const analyze_format_string::FormatSpecifier &FS,
2338 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002339 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002340
Hans Wennborg76517422012-02-22 10:17:01 +00002341 void HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002342 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002343 const char *startSpecifier, unsigned specifierLen);
2344
2345 void HandleNonStandardConversionSpecifier(
2346 const analyze_format_string::ConversionSpecifier &CS,
2347 const char *startSpecifier, unsigned specifierLen);
2348
Hans Wennborgf8562642012-03-09 10:10:54 +00002349 virtual void HandlePosition(const char *startPos, unsigned posLen);
2350
Ted Kremenekefaff192010-02-27 01:41:03 +00002351 virtual void HandleInvalidPosition(const char *startSpecifier,
2352 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00002353 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00002354
2355 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2356
Ted Kremeneke0e53132010-01-28 23:39:18 +00002357 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002358
Richard Trieu55733de2011-10-28 00:41:25 +00002359 template <typename Range>
2360 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2361 const Expr *ArgumentExpr,
2362 PartialDiagnostic PDiag,
2363 SourceLocation StringLoc,
2364 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002365 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002366
Ted Kremenek826a3452010-07-16 02:11:22 +00002367protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002368 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2369 const char *startSpec,
2370 unsigned specifierLen,
2371 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00002372
2373 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2374 const char *startSpec,
2375 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002376
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002377 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00002378 CharSourceRange getSpecifierRange(const char *startSpecifier,
2379 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002380 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002381
Ted Kremenek0d277352010-01-29 01:06:55 +00002382 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00002383
2384 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2385 const analyze_format_string::ConversionSpecifier &CS,
2386 const char *startSpecifier, unsigned specifierLen,
2387 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00002388
2389 template <typename Range>
2390 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2391 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002392 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002393
2394 void CheckPositionalAndNonpositionalArgs(
2395 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002396};
2397}
2398
Ted Kremenek826a3452010-07-16 02:11:22 +00002399SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002400 return OrigFormatExpr->getSourceRange();
2401}
2402
Ted Kremenek826a3452010-07-16 02:11:22 +00002403CharSourceRange CheckFormatHandler::
2404getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002405 SourceLocation Start = getLocationOfByte(startSpecifier);
2406 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2407
2408 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002409 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002410
2411 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002412}
2413
Ted Kremenek826a3452010-07-16 02:11:22 +00002414SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002415 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002416}
2417
Ted Kremenek826a3452010-07-16 02:11:22 +00002418void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2419 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002420 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2421 getLocationOfByte(startSpecifier),
2422 /*IsStringLocation*/true,
2423 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002424}
2425
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002426void CheckFormatHandler::HandleInvalidLengthModifier(
2427 const analyze_format_string::FormatSpecifier &FS,
2428 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002429 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002430 using namespace analyze_format_string;
2431
2432 const LengthModifier &LM = FS.getLengthModifier();
2433 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2434
2435 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002436 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002437 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002438 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002439 getLocationOfByte(LM.getStart()),
2440 /*IsStringLocation*/true,
2441 getSpecifierRange(startSpecifier, specifierLen));
2442
2443 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2444 << FixedLM->toString()
2445 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2446
2447 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00002448 FixItHint Hint;
2449 if (DiagID == diag::warn_format_nonsensical_length)
2450 Hint = FixItHint::CreateRemoval(LMRange);
2451
2452 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002453 getLocationOfByte(LM.getStart()),
2454 /*IsStringLocation*/true,
2455 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002456 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002457 }
2458}
2459
Hans Wennborg76517422012-02-22 10:17:01 +00002460void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002461 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002462 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002463 using namespace analyze_format_string;
2464
2465 const LengthModifier &LM = FS.getLengthModifier();
2466 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2467
2468 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002469 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose8be066e2012-09-08 04:00:12 +00002470 if (FixedLM) {
2471 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2472 << LM.toString() << 0,
2473 getLocationOfByte(LM.getStart()),
2474 /*IsStringLocation*/true,
2475 getSpecifierRange(startSpecifier, specifierLen));
2476
2477 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2478 << FixedLM->toString()
2479 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2480
2481 } else {
2482 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2483 << LM.toString() << 0,
2484 getLocationOfByte(LM.getStart()),
2485 /*IsStringLocation*/true,
2486 getSpecifierRange(startSpecifier, specifierLen));
2487 }
Hans Wennborg76517422012-02-22 10:17:01 +00002488}
2489
2490void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2491 const analyze_format_string::ConversionSpecifier &CS,
2492 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002493 using namespace analyze_format_string;
2494
2495 // See if we know how to fix this conversion specifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002496 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose670941c2012-09-13 02:11:15 +00002497 if (FixedCS) {
2498 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2499 << CS.toString() << /*conversion specifier*/1,
2500 getLocationOfByte(CS.getStart()),
2501 /*IsStringLocation*/true,
2502 getSpecifierRange(startSpecifier, specifierLen));
2503
2504 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2505 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2506 << FixedCS->toString()
2507 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2508 } else {
2509 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2510 << CS.toString() << /*conversion specifier*/1,
2511 getLocationOfByte(CS.getStart()),
2512 /*IsStringLocation*/true,
2513 getSpecifierRange(startSpecifier, specifierLen));
2514 }
Hans Wennborg76517422012-02-22 10:17:01 +00002515}
2516
Hans Wennborgf8562642012-03-09 10:10:54 +00002517void CheckFormatHandler::HandlePosition(const char *startPos,
2518 unsigned posLen) {
2519 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2520 getLocationOfByte(startPos),
2521 /*IsStringLocation*/true,
2522 getSpecifierRange(startPos, posLen));
2523}
2524
Ted Kremenekefaff192010-02-27 01:41:03 +00002525void
Ted Kremenek826a3452010-07-16 02:11:22 +00002526CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2527 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002528 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2529 << (unsigned) p,
2530 getLocationOfByte(startPos), /*IsStringLocation*/true,
2531 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002532}
2533
Ted Kremenek826a3452010-07-16 02:11:22 +00002534void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002535 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002536 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2537 getLocationOfByte(startPos),
2538 /*IsStringLocation*/true,
2539 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002540}
2541
Ted Kremenek826a3452010-07-16 02:11:22 +00002542void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002543 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002544 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002545 EmitFormatDiagnostic(
2546 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2547 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2548 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002549 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002550}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002551
Jordan Rose48716662012-07-19 18:10:08 +00002552// Note that this may return NULL if there was an error parsing or building
2553// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002554const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002555 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002556}
2557
2558void CheckFormatHandler::DoneProcessing() {
2559 // Does the number of data arguments exceed the number of
2560 // format conversions in the format string?
2561 if (!HasVAListArg) {
2562 // Find any arguments that weren't covered.
2563 CoveredArgs.flip();
2564 signed notCoveredArg = CoveredArgs.find_first();
2565 if (notCoveredArg >= 0) {
2566 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002567 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2568 SourceLocation Loc = E->getLocStart();
2569 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2570 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2571 Loc, /*IsStringLocation*/false,
2572 getFormatStringRange());
2573 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002574 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002575 }
2576 }
2577}
2578
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002579bool
2580CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2581 SourceLocation Loc,
2582 const char *startSpec,
2583 unsigned specifierLen,
2584 const char *csStart,
2585 unsigned csLen) {
2586
2587 bool keepGoing = true;
2588 if (argIndex < NumDataArgs) {
2589 // Consider the argument coverered, even though the specifier doesn't
2590 // make sense.
2591 CoveredArgs.set(argIndex);
2592 }
2593 else {
2594 // If argIndex exceeds the number of data arguments we
2595 // don't issue a warning because that is just a cascade of warnings (and
2596 // they may have intended '%%' anyway). We don't want to continue processing
2597 // the format string after this point, however, as we will like just get
2598 // gibberish when trying to match arguments.
2599 keepGoing = false;
2600 }
2601
Richard Trieu55733de2011-10-28 00:41:25 +00002602 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2603 << StringRef(csStart, csLen),
2604 Loc, /*IsStringLocation*/true,
2605 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002606
2607 return keepGoing;
2608}
2609
Richard Trieu55733de2011-10-28 00:41:25 +00002610void
2611CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2612 const char *startSpec,
2613 unsigned specifierLen) {
2614 EmitFormatDiagnostic(
2615 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2616 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2617}
2618
Ted Kremenek666a1972010-07-26 19:45:42 +00002619bool
2620CheckFormatHandler::CheckNumArgs(
2621 const analyze_format_string::FormatSpecifier &FS,
2622 const analyze_format_string::ConversionSpecifier &CS,
2623 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2624
2625 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002626 PartialDiagnostic PDiag = FS.usesPositionalArg()
2627 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2628 << (argIndex+1) << NumDataArgs)
2629 : S.PDiag(diag::warn_printf_insufficient_data_args);
2630 EmitFormatDiagnostic(
2631 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2632 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002633 return false;
2634 }
2635 return true;
2636}
2637
Richard Trieu55733de2011-10-28 00:41:25 +00002638template<typename Range>
2639void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2640 SourceLocation Loc,
2641 bool IsStringLocation,
2642 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002643 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002644 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002645 Loc, IsStringLocation, StringRange, FixIt);
2646}
2647
2648/// \brief If the format string is not within the funcion call, emit a note
2649/// so that the function call and string are in diagnostic messages.
2650///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002651/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002652/// call and only one diagnostic message will be produced. Otherwise, an
2653/// extra note will be emitted pointing to location of the format string.
2654///
2655/// \param ArgumentExpr the expression that is passed as the format string
2656/// argument in the function call. Used for getting locations when two
2657/// diagnostics are emitted.
2658///
2659/// \param PDiag the callee should already have provided any strings for the
2660/// diagnostic message. This function only adds locations and fixits
2661/// to diagnostics.
2662///
2663/// \param Loc primary location for diagnostic. If two diagnostics are
2664/// required, one will be at Loc and a new SourceLocation will be created for
2665/// the other one.
2666///
2667/// \param IsStringLocation if true, Loc points to the format string should be
2668/// used for the note. Otherwise, Loc points to the argument list and will
2669/// be used with PDiag.
2670///
2671/// \param StringRange some or all of the string to highlight. This is
2672/// templated so it can accept either a CharSourceRange or a SourceRange.
2673///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002674/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002675template<typename Range>
2676void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2677 const Expr *ArgumentExpr,
2678 PartialDiagnostic PDiag,
2679 SourceLocation Loc,
2680 bool IsStringLocation,
2681 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002682 ArrayRef<FixItHint> FixIt) {
2683 if (InFunctionCall) {
2684 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2685 D << StringRange;
2686 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2687 I != E; ++I) {
2688 D << *I;
2689 }
2690 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00002691 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2692 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00002693
2694 const Sema::SemaDiagnosticBuilder &Note =
2695 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2696 diag::note_format_string_defined);
2697
2698 Note << StringRange;
2699 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2700 I != E; ++I) {
2701 Note << *I;
2702 }
Richard Trieu55733de2011-10-28 00:41:25 +00002703 }
2704}
2705
Ted Kremenek826a3452010-07-16 02:11:22 +00002706//===--- CHECK: Printf format string checking ------------------------------===//
2707
2708namespace {
2709class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002710 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002711public:
2712 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2713 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002714 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002715 const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002716 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002717 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00002718 Sema::VariadicCallType CallType,
2719 llvm::SmallBitVector &CheckedVarArgs)
2720 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2721 numDataArgs, beg, hasVAListArg, Args,
2722 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2723 ObjCContext(isObjC)
Jordan Roseddcfbc92012-07-19 18:10:23 +00002724 {}
2725
Ted Kremenek826a3452010-07-16 02:11:22 +00002726
2727 bool HandleInvalidPrintfConversionSpecifier(
2728 const analyze_printf::PrintfSpecifier &FS,
2729 const char *startSpecifier,
2730 unsigned specifierLen);
2731
2732 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2733 const char *startSpecifier,
2734 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002735 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2736 const char *StartSpecifier,
2737 unsigned SpecifierLen,
2738 const Expr *E);
2739
Ted Kremenek826a3452010-07-16 02:11:22 +00002740 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2741 const char *startSpecifier, unsigned specifierLen);
2742 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2743 const analyze_printf::OptionalAmount &Amt,
2744 unsigned type,
2745 const char *startSpecifier, unsigned specifierLen);
2746 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2747 const analyze_printf::OptionalFlag &flag,
2748 const char *startSpecifier, unsigned specifierLen);
2749 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2750 const analyze_printf::OptionalFlag &ignoredFlag,
2751 const analyze_printf::OptionalFlag &flag,
2752 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002753 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith831421f2012-06-25 20:30:08 +00002754 const Expr *E, const CharSourceRange &CSR);
2755
Ted Kremenek826a3452010-07-16 02:11:22 +00002756};
2757}
2758
2759bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2760 const analyze_printf::PrintfSpecifier &FS,
2761 const char *startSpecifier,
2762 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002763 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002764 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002765
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002766 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2767 getLocationOfByte(CS.getStart()),
2768 startSpecifier, specifierLen,
2769 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002770}
2771
Ted Kremenek826a3452010-07-16 02:11:22 +00002772bool CheckPrintfHandler::HandleAmount(
2773 const analyze_format_string::OptionalAmount &Amt,
2774 unsigned k, const char *startSpecifier,
2775 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002776
2777 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002778 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002779 unsigned argIndex = Amt.getArgIndex();
2780 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002781 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2782 << k,
2783 getLocationOfByte(Amt.getStart()),
2784 /*IsStringLocation*/true,
2785 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002786 // Don't do any more checking. We will just emit
2787 // spurious errors.
2788 return false;
2789 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002790
Ted Kremenek0d277352010-01-29 01:06:55 +00002791 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002792 // Although not in conformance with C99, we also allow the argument to be
2793 // an 'unsigned int' as that is a reasonably safe case. GCC also
2794 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002795 CoveredArgs.set(argIndex);
2796 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002797 if (!Arg)
2798 return false;
2799
Ted Kremenek0d277352010-01-29 01:06:55 +00002800 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002801
Hans Wennborgf3749f42012-08-07 08:11:26 +00002802 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2803 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002804
Hans Wennborgf3749f42012-08-07 08:11:26 +00002805 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002806 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002807 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002808 << T << Arg->getSourceRange(),
2809 getLocationOfByte(Amt.getStart()),
2810 /*IsStringLocation*/true,
2811 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002812 // Don't do any more checking. We will just emit
2813 // spurious errors.
2814 return false;
2815 }
2816 }
2817 }
2818 return true;
2819}
Ted Kremenek0d277352010-01-29 01:06:55 +00002820
Tom Caree4ee9662010-06-17 19:00:27 +00002821void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002822 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002823 const analyze_printf::OptionalAmount &Amt,
2824 unsigned type,
2825 const char *startSpecifier,
2826 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002827 const analyze_printf::PrintfConversionSpecifier &CS =
2828 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002829
Richard Trieu55733de2011-10-28 00:41:25 +00002830 FixItHint fixit =
2831 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2832 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2833 Amt.getConstantLength()))
2834 : FixItHint();
2835
2836 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2837 << type << CS.toString(),
2838 getLocationOfByte(Amt.getStart()),
2839 /*IsStringLocation*/true,
2840 getSpecifierRange(startSpecifier, specifierLen),
2841 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002842}
2843
Ted Kremenek826a3452010-07-16 02:11:22 +00002844void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002845 const analyze_printf::OptionalFlag &flag,
2846 const char *startSpecifier,
2847 unsigned specifierLen) {
2848 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002849 const analyze_printf::PrintfConversionSpecifier &CS =
2850 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002851 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2852 << flag.toString() << CS.toString(),
2853 getLocationOfByte(flag.getPosition()),
2854 /*IsStringLocation*/true,
2855 getSpecifierRange(startSpecifier, specifierLen),
2856 FixItHint::CreateRemoval(
2857 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002858}
2859
2860void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002861 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002862 const analyze_printf::OptionalFlag &ignoredFlag,
2863 const analyze_printf::OptionalFlag &flag,
2864 const char *startSpecifier,
2865 unsigned specifierLen) {
2866 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002867 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2868 << ignoredFlag.toString() << flag.toString(),
2869 getLocationOfByte(ignoredFlag.getPosition()),
2870 /*IsStringLocation*/true,
2871 getSpecifierRange(startSpecifier, specifierLen),
2872 FixItHint::CreateRemoval(
2873 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002874}
2875
Richard Smith831421f2012-06-25 20:30:08 +00002876// Determines if the specified is a C++ class or struct containing
2877// a member with the specified name and kind (e.g. a CXXMethodDecl named
2878// "c_str()").
2879template<typename MemberKind>
2880static llvm::SmallPtrSet<MemberKind*, 1>
2881CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2882 const RecordType *RT = Ty->getAs<RecordType>();
2883 llvm::SmallPtrSet<MemberKind*, 1> Results;
2884
2885 if (!RT)
2886 return Results;
2887 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2888 if (!RD)
2889 return Results;
2890
2891 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2892 Sema::LookupMemberName);
2893
2894 // We just need to include all members of the right kind turned up by the
2895 // filter, at this point.
2896 if (S.LookupQualifiedName(R, RT->getDecl()))
2897 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2898 NamedDecl *decl = (*I)->getUnderlyingDecl();
2899 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2900 Results.insert(FK);
2901 }
2902 return Results;
2903}
2904
2905// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002906// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002907// Returns true when a c_str() conversion method is found.
2908bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgf3749f42012-08-07 08:11:26 +00002909 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith831421f2012-06-25 20:30:08 +00002910 const CharSourceRange &CSR) {
2911 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2912
2913 MethodSet Results =
2914 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2915
2916 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2917 MI != ME; ++MI) {
2918 const CXXMethodDecl *Method = *MI;
2919 if (Method->getNumParams() == 0 &&
Hans Wennborgf3749f42012-08-07 08:11:26 +00002920 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith831421f2012-06-25 20:30:08 +00002921 // FIXME: Suggest parens if the expression needs them.
2922 SourceLocation EndLoc =
2923 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2924 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2925 << "c_str()"
2926 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2927 return true;
2928 }
2929 }
2930
2931 return false;
2932}
2933
Ted Kremeneke0e53132010-01-28 23:39:18 +00002934bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002935CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002936 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002937 const char *startSpecifier,
2938 unsigned specifierLen) {
2939
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002940 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002941 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002942 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002943
Ted Kremenekbaa40062010-07-19 22:01:06 +00002944 if (FS.consumesDataArgument()) {
2945 if (atFirstArg) {
2946 atFirstArg = false;
2947 usesPositionalArgs = FS.usesPositionalArg();
2948 }
2949 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002950 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2951 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002952 return false;
2953 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002954 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002955
Ted Kremenekefaff192010-02-27 01:41:03 +00002956 // First check if the field width, precision, and conversion specifier
2957 // have matching data arguments.
2958 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2959 startSpecifier, specifierLen)) {
2960 return false;
2961 }
2962
2963 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2964 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002965 return false;
2966 }
2967
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002968 if (!CS.consumesDataArgument()) {
2969 // FIXME: Technically specifying a precision or field width here
2970 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002971 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002972 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002973
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002974 // Consume the argument.
2975 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002976 if (argIndex < NumDataArgs) {
2977 // The check to see if the argIndex is valid will come later.
2978 // We set the bit here because we may exit early from this
2979 // function if we encounter some other error.
2980 CoveredArgs.set(argIndex);
2981 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002982
2983 // Check for using an Objective-C specific conversion specifier
2984 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002985 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002986 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2987 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002988 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002989
Tom Caree4ee9662010-06-17 19:00:27 +00002990 // Check for invalid use of field width
2991 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002992 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002993 startSpecifier, specifierLen);
2994 }
2995
2996 // Check for invalid use of precision
2997 if (!FS.hasValidPrecision()) {
2998 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2999 startSpecifier, specifierLen);
3000 }
3001
3002 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00003003 if (!FS.hasValidThousandsGroupingPrefix())
3004 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00003005 if (!FS.hasValidLeadingZeros())
3006 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3007 if (!FS.hasValidPlusPrefix())
3008 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00003009 if (!FS.hasValidSpacePrefix())
3010 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00003011 if (!FS.hasValidAlternativeForm())
3012 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3013 if (!FS.hasValidLeftJustified())
3014 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3015
3016 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00003017 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3018 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3019 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00003020 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3021 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3022 startSpecifier, specifierLen);
3023
3024 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003025 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003026 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3027 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003028 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003029 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003030 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003031 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3032 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00003033
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003034 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3035 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3036
Ted Kremenekda51f0d2010-01-29 01:43:31 +00003037 // The remaining checks depend on the data arguments.
3038 if (HasVAListArg)
3039 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003040
Ted Kremenek666a1972010-07-26 19:45:42 +00003041 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00003042 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003043
Jordan Rose48716662012-07-19 18:10:08 +00003044 const Expr *Arg = getDataArg(argIndex);
3045 if (!Arg)
3046 return true;
3047
3048 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00003049}
3050
Jordan Roseec087352012-09-05 22:56:26 +00003051static bool requiresParensToAddCast(const Expr *E) {
3052 // FIXME: We should have a general way to reason about operator
3053 // precedence and whether parens are actually needed here.
3054 // Take care of a few common cases where they aren't.
3055 const Expr *Inside = E->IgnoreImpCasts();
3056 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3057 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3058
3059 switch (Inside->getStmtClass()) {
3060 case Stmt::ArraySubscriptExprClass:
3061 case Stmt::CallExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003062 case Stmt::CharacterLiteralClass:
3063 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003064 case Stmt::DeclRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003065 case Stmt::FloatingLiteralClass:
3066 case Stmt::IntegerLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003067 case Stmt::MemberExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003068 case Stmt::ObjCArrayLiteralClass:
3069 case Stmt::ObjCBoolLiteralExprClass:
3070 case Stmt::ObjCBoxedExprClass:
3071 case Stmt::ObjCDictionaryLiteralClass:
3072 case Stmt::ObjCEncodeExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003073 case Stmt::ObjCIvarRefExprClass:
3074 case Stmt::ObjCMessageExprClass:
3075 case Stmt::ObjCPropertyRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003076 case Stmt::ObjCStringLiteralClass:
3077 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003078 case Stmt::ParenExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003079 case Stmt::StringLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003080 case Stmt::UnaryOperatorClass:
3081 return false;
3082 default:
3083 return true;
3084 }
3085}
3086
Richard Smith831421f2012-06-25 20:30:08 +00003087bool
3088CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3089 const char *StartSpecifier,
3090 unsigned SpecifierLen,
3091 const Expr *E) {
3092 using namespace analyze_format_string;
3093 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003094 // Now type check the data expression that matches the
3095 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00003096 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3097 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00003098 if (!AT.isValid())
3099 return true;
Jordan Roseec087352012-09-05 22:56:26 +00003100
Jordan Rose448ac3e2012-12-05 18:44:40 +00003101 QualType ExprTy = E->getType();
Ted Kremenek02be9682013-04-10 06:26:26 +00003102 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3103 ExprTy = TET->getUnderlyingExpr()->getType();
3104 }
3105
Jordan Rose448ac3e2012-12-05 18:44:40 +00003106 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003107 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00003108
Jordan Rose614a8652012-09-05 22:56:19 +00003109 // Look through argument promotions for our error message's reported type.
3110 // This includes the integral and floating promotions, but excludes array
3111 // and function pointer decay; seeing that an argument intended to be a
3112 // string has type 'char [6]' is probably more confusing than 'char *'.
3113 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3114 if (ICE->getCastKind() == CK_IntegralCast ||
3115 ICE->getCastKind() == CK_FloatingCast) {
3116 E = ICE->getSubExpr();
Jordan Rose448ac3e2012-12-05 18:44:40 +00003117 ExprTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00003118
3119 // Check if we didn't match because of an implicit cast from a 'char'
3120 // or 'short' to an 'int'. This is done because printf is a varargs
3121 // function.
3122 if (ICE->getType() == S.Context.IntTy ||
3123 ICE->getType() == S.Context.UnsignedIntTy) {
3124 // All further checking is done on the subexpression.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003125 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003126 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00003127 }
Jordan Roseee0259d2012-06-04 22:48:57 +00003128 }
Jordan Rose448ac3e2012-12-05 18:44:40 +00003129 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3130 // Special case for 'a', which has type 'int' in C.
3131 // Note, however, that we do /not/ want to treat multibyte constants like
3132 // 'MooV' as characters! This form is deprecated but still exists.
3133 if (ExprTy == S.Context.IntTy)
3134 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3135 ExprTy = S.Context.CharTy;
Jordan Rose614a8652012-09-05 22:56:19 +00003136 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003137
Jordan Rose2cd34402012-12-05 18:44:49 +00003138 // %C in an Objective-C context prints a unichar, not a wchar_t.
3139 // If the argument is an integer of some kind, believe the %C and suggest
3140 // a cast instead of changing the conversion specifier.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003141 QualType IntendedTy = ExprTy;
Jordan Rose2cd34402012-12-05 18:44:49 +00003142 if (ObjCContext &&
3143 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3144 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3145 !ExprTy->isCharType()) {
3146 // 'unichar' is defined as a typedef of unsigned short, but we should
3147 // prefer using the typedef if it is visible.
3148 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenek656465d2013-10-15 05:25:17 +00003149
3150 // While we are here, check if the value is an IntegerLiteral that happens
3151 // to be within the valid range.
3152 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3153 const llvm::APInt &V = IL->getValue();
3154 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3155 return true;
3156 }
3157
Jordan Rose2cd34402012-12-05 18:44:49 +00003158 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3159 Sema::LookupOrdinaryName);
3160 if (S.LookupName(Result, S.getCurScope())) {
3161 NamedDecl *ND = Result.getFoundDecl();
3162 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3163 if (TD->getUnderlyingType() == IntendedTy)
3164 IntendedTy = S.Context.getTypedefType(TD);
3165 }
3166 }
3167 }
3168
3169 // Special-case some of Darwin's platform-independence types by suggesting
3170 // casts to primitive types that are known to be large enough.
3171 bool ShouldNotPrintDirectly = false;
Jordan Roseec087352012-09-05 22:56:26 +00003172 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenek6edb0292013-03-25 22:28:37 +00003173 // Use a 'while' to peel off layers of typedefs.
3174 QualType TyTy = IntendedTy;
3175 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseec087352012-09-05 22:56:26 +00003176 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose2cd34402012-12-05 18:44:49 +00003177 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseec087352012-09-05 22:56:26 +00003178 .Case("NSInteger", S.Context.LongTy)
3179 .Case("NSUInteger", S.Context.UnsignedLongTy)
3180 .Case("SInt32", S.Context.IntTy)
3181 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose2cd34402012-12-05 18:44:49 +00003182 .Default(QualType());
3183
3184 if (!CastTy.isNull()) {
3185 ShouldNotPrintDirectly = true;
3186 IntendedTy = CastTy;
Ted Kremenek6edb0292013-03-25 22:28:37 +00003187 break;
Jordan Rose2cd34402012-12-05 18:44:49 +00003188 }
Ted Kremenek6edb0292013-03-25 22:28:37 +00003189 TyTy = UserTy->desugar();
Jordan Roseec087352012-09-05 22:56:26 +00003190 }
3191 }
3192
Jordan Rose614a8652012-09-05 22:56:19 +00003193 // We may be able to offer a FixItHint if it is a supported type.
3194 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00003195 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00003196 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003197
Jordan Rose614a8652012-09-05 22:56:19 +00003198 if (success) {
3199 // Get the fix string from the fixed format specifier
3200 SmallString<16> buf;
3201 llvm::raw_svector_ostream os(buf);
3202 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003203
Jordan Roseec087352012-09-05 22:56:26 +00003204 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3205
Jordan Rose2cd34402012-12-05 18:44:49 +00003206 if (IntendedTy == ExprTy) {
3207 // In this case, the specifier is wrong and should be changed to match
3208 // the argument.
3209 EmitFormatDiagnostic(
3210 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3211 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3212 << E->getSourceRange(),
3213 E->getLocStart(),
3214 /*IsStringLocation*/false,
3215 SpecRange,
3216 FixItHint::CreateReplacement(SpecRange, os.str()));
3217
3218 } else {
Jordan Roseec087352012-09-05 22:56:26 +00003219 // The canonical type for formatting this value is different from the
3220 // actual type of the expression. (This occurs, for example, with Darwin's
3221 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3222 // should be printed as 'long' for 64-bit compatibility.)
3223 // Rather than emitting a normal format/argument mismatch, we want to
3224 // add a cast to the recommended type (and correct the format string
3225 // if necessary).
3226 SmallString<16> CastBuf;
3227 llvm::raw_svector_ostream CastFix(CastBuf);
3228 CastFix << "(";
3229 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3230 CastFix << ")";
3231
3232 SmallVector<FixItHint,4> Hints;
3233 if (!AT.matchesType(S.Context, IntendedTy))
3234 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3235
3236 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3237 // If there's already a cast present, just replace it.
3238 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3239 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3240
3241 } else if (!requiresParensToAddCast(E)) {
3242 // If the expression has high enough precedence,
3243 // just write the C-style cast.
3244 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3245 CastFix.str()));
3246 } else {
3247 // Otherwise, add parens around the expression as well as the cast.
3248 CastFix << "(";
3249 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3250 CastFix.str()));
3251
3252 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3253 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3254 }
3255
Jordan Rose2cd34402012-12-05 18:44:49 +00003256 if (ShouldNotPrintDirectly) {
3257 // The expression has a type that should not be printed directly.
3258 // We extract the name from the typedef because we don't want to show
3259 // the underlying type in the diagnostic.
3260 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseec087352012-09-05 22:56:26 +00003261
Jordan Rose2cd34402012-12-05 18:44:49 +00003262 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3263 << Name << IntendedTy
3264 << E->getSourceRange(),
3265 E->getLocStart(), /*IsStringLocation=*/false,
3266 SpecRange, Hints);
3267 } else {
3268 // In this case, the expression could be printed using a different
3269 // specifier, but we've decided that the specifier is probably correct
3270 // and we should cast instead. Just use the normal warning message.
3271 EmitFormatDiagnostic(
3272 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3273 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3274 << E->getSourceRange(),
3275 E->getLocStart(), /*IsStringLocation*/false,
3276 SpecRange, Hints);
3277 }
Jordan Roseec087352012-09-05 22:56:26 +00003278 }
Jordan Rose614a8652012-09-05 22:56:19 +00003279 } else {
3280 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3281 SpecifierLen);
3282 // Since the warning for passing non-POD types to variadic functions
3283 // was deferred until now, we emit a warning for non-POD
3284 // arguments here.
Richard Smith0e218972013-08-05 18:49:43 +00003285 switch (S.isValidVarArgType(ExprTy)) {
3286 case Sema::VAK_Valid:
3287 case Sema::VAK_ValidInCXX11:
Jordan Rose614a8652012-09-05 22:56:19 +00003288 EmitFormatDiagnostic(
Richard Smith0e218972013-08-05 18:49:43 +00003289 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3290 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3291 << CSR
3292 << E->getSourceRange(),
3293 E->getLocStart(), /*IsStringLocation*/false, CSR);
3294 break;
3295
3296 case Sema::VAK_Undefined:
3297 EmitFormatDiagnostic(
3298 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith80ad52f2013-01-02 11:42:31 +00003299 << S.getLangOpts().CPlusPlus11
Jordan Rose448ac3e2012-12-05 18:44:40 +00003300 << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00003301 << CallType
3302 << AT.getRepresentativeTypeName(S.Context)
3303 << CSR
3304 << E->getSourceRange(),
3305 E->getLocStart(), /*IsStringLocation*/false, CSR);
Jordan Rose614a8652012-09-05 22:56:19 +00003306 checkForCStrMembers(AT, E, CSR);
Richard Smith0e218972013-08-05 18:49:43 +00003307 break;
3308
3309 case Sema::VAK_Invalid:
3310 if (ExprTy->isObjCObjectType())
3311 EmitFormatDiagnostic(
3312 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3313 << S.getLangOpts().CPlusPlus11
3314 << ExprTy
3315 << CallType
3316 << AT.getRepresentativeTypeName(S.Context)
3317 << CSR
3318 << E->getSourceRange(),
3319 E->getLocStart(), /*IsStringLocation*/false, CSR);
3320 else
3321 // FIXME: If this is an initializer list, suggest removing the braces
3322 // or inserting a cast to the target type.
3323 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3324 << isa<InitListExpr>(E) << ExprTy << CallType
3325 << AT.getRepresentativeTypeName(S.Context)
3326 << E->getSourceRange();
3327 break;
3328 }
3329
3330 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3331 "format string specifier index out of range");
3332 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003333 }
3334
Ted Kremeneke0e53132010-01-28 23:39:18 +00003335 return true;
3336}
3337
Ted Kremenek826a3452010-07-16 02:11:22 +00003338//===--- CHECK: Scanf format string checking ------------------------------===//
3339
3340namespace {
3341class CheckScanfHandler : public CheckFormatHandler {
3342public:
3343 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3344 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003345 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003346 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003347 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00003348 Sema::VariadicCallType CallType,
3349 llvm::SmallBitVector &CheckedVarArgs)
3350 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3351 numDataArgs, beg, hasVAListArg,
3352 Args, formatIdx, inFunctionCall, CallType,
3353 CheckedVarArgs)
Jordan Roseddcfbc92012-07-19 18:10:23 +00003354 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00003355
3356 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3357 const char *startSpecifier,
3358 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003359
3360 bool HandleInvalidScanfConversionSpecifier(
3361 const analyze_scanf::ScanfSpecifier &FS,
3362 const char *startSpecifier,
3363 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00003364
3365 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00003366};
Ted Kremenek07d161f2010-01-29 01:50:07 +00003367}
Ted Kremeneke0e53132010-01-28 23:39:18 +00003368
Ted Kremenekb7c21012010-07-16 18:28:03 +00003369void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3370 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00003371 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3372 getLocationOfByte(end), /*IsStringLocation*/true,
3373 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00003374}
3375
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003376bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3377 const analyze_scanf::ScanfSpecifier &FS,
3378 const char *startSpecifier,
3379 unsigned specifierLen) {
3380
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003381 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003382 FS.getConversionSpecifier();
3383
3384 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3385 getLocationOfByte(CS.getStart()),
3386 startSpecifier, specifierLen,
3387 CS.getStart(), CS.getLength());
3388}
3389
Ted Kremenek826a3452010-07-16 02:11:22 +00003390bool CheckScanfHandler::HandleScanfSpecifier(
3391 const analyze_scanf::ScanfSpecifier &FS,
3392 const char *startSpecifier,
3393 unsigned specifierLen) {
3394
3395 using namespace analyze_scanf;
3396 using namespace analyze_format_string;
3397
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003398 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00003399
Ted Kremenekbaa40062010-07-19 22:01:06 +00003400 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3401 // be used to decide if we are using positional arguments consistently.
3402 if (FS.consumesDataArgument()) {
3403 if (atFirstArg) {
3404 atFirstArg = false;
3405 usesPositionalArgs = FS.usesPositionalArg();
3406 }
3407 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003408 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3409 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003410 return false;
3411 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003412 }
3413
3414 // Check if the field with is non-zero.
3415 const OptionalAmount &Amt = FS.getFieldWidth();
3416 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3417 if (Amt.getConstantAmount() == 0) {
3418 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3419 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00003420 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3421 getLocationOfByte(Amt.getStart()),
3422 /*IsStringLocation*/true, R,
3423 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00003424 }
3425 }
3426
3427 if (!FS.consumesDataArgument()) {
3428 // FIXME: Technically specifying a precision or field width here
3429 // makes no sense. Worth issuing a warning at some point.
3430 return true;
3431 }
3432
3433 // Consume the argument.
3434 unsigned argIndex = FS.getArgIndex();
3435 if (argIndex < NumDataArgs) {
3436 // The check to see if the argIndex is valid will come later.
3437 // We set the bit here because we may exit early from this
3438 // function if we encounter some other error.
3439 CoveredArgs.set(argIndex);
3440 }
3441
Ted Kremenek1e51c202010-07-20 20:04:47 +00003442 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003443 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003444 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3445 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003446 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003447 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003448 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003449 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3450 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00003451
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003452 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3453 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3454
Ted Kremenek826a3452010-07-16 02:11:22 +00003455 // The remaining checks depend on the data arguments.
3456 if (HasVAListArg)
3457 return true;
3458
Ted Kremenek666a1972010-07-26 19:45:42 +00003459 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00003460 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00003461
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003462 // Check that the argument type matches the format specifier.
3463 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00003464 if (!Ex)
3465 return true;
3466
Hans Wennborg58e1e542012-08-07 08:59:46 +00003467 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3468 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003469 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00003470 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00003471 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003472
3473 if (success) {
3474 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003475 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003476 llvm::raw_svector_ostream os(buf);
3477 fixedFS.toString(os);
3478
3479 EmitFormatDiagnostic(
3480 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003481 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003482 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003483 Ex->getLocStart(),
3484 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003485 getSpecifierRange(startSpecifier, specifierLen),
3486 FixItHint::CreateReplacement(
3487 getSpecifierRange(startSpecifier, specifierLen),
3488 os.str()));
3489 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003490 EmitFormatDiagnostic(
3491 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003492 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003493 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003494 Ex->getLocStart(),
3495 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003496 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003497 }
3498 }
3499
Ted Kremenek826a3452010-07-16 02:11:22 +00003500 return true;
3501}
3502
3503void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003504 const Expr *OrigFormatExpr,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003505 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003506 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003507 unsigned firstDataArg, FormatStringType Type,
Richard Smith0e218972013-08-05 18:49:43 +00003508 bool inFunctionCall, VariadicCallType CallType,
3509 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003510
Ted Kremeneke0e53132010-01-28 23:39:18 +00003511 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00003512 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003513 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003514 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003515 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3516 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003517 return;
3518 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003519
Ted Kremeneke0e53132010-01-28 23:39:18 +00003520 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00003521 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003522 const char *Str = StrRef.data();
3523 unsigned StrLen = StrRef.size();
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003524 const unsigned numDataArgs = Args.size() - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00003525
Ted Kremeneke0e53132010-01-28 23:39:18 +00003526 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00003527 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00003528 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003529 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003530 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3531 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003532 return;
3533 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003534
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003535 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003536 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003537 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003538 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00003539 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00003540
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003541 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003542 getLangOpts(),
3543 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003544 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003545 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00003546 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003547 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00003548 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00003549
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003550 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003551 getLangOpts(),
3552 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003553 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003554 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00003555}
3556
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003557//===--- CHECK: Standard memory functions ---------------------------------===//
3558
Douglas Gregor2a053a32011-05-03 20:05:22 +00003559/// \brief Determine whether the given type is a dynamic class type (e.g.,
3560/// whether it has a vtable).
3561static bool isDynamicClassType(QualType T) {
3562 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3563 if (CXXRecordDecl *Definition = Record->getDefinition())
3564 if (Definition->isDynamicClass())
3565 return true;
3566
3567 return false;
3568}
3569
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003570/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00003571/// otherwise returns NULL.
3572static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00003573 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00003574 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3575 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3576 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003577
Chandler Carruth000d4282011-06-16 09:09:40 +00003578 return 0;
3579}
3580
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003581/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00003582static QualType getSizeOfArgType(const Expr* E) {
3583 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3584 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3585 if (SizeOf->getKind() == clang::UETT_SizeOf)
3586 return SizeOf->getTypeOfArgument();
3587
3588 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00003589}
3590
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003591/// \brief Check for dangerous or invalid arguments to memset().
3592///
Chandler Carruth929f0132011-06-03 06:23:57 +00003593/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003594/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3595/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003596///
3597/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003598void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00003599 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003600 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00003601 assert(BId != 0);
3602
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003603 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00003604 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00003605 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00003606 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003607 return;
3608
Anna Zaks0a151a12012-01-17 00:37:07 +00003609 unsigned LastArg = (BId == Builtin::BImemset ||
3610 BId == Builtin::BIstrndup ? 1 : 2);
3611 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00003612 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00003613
3614 // We have special checking when the length is a sizeof expression.
3615 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3616 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3617 llvm::FoldingSetNodeID SizeOfArgID;
3618
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003619 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3620 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003621 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003622
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003623 QualType DestTy = Dest->getType();
3624 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3625 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00003626
Chandler Carruth000d4282011-06-16 09:09:40 +00003627 // Never warn about void type pointers. This can be used to suppress
3628 // false positives.
3629 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003630 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003631
Chandler Carruth000d4282011-06-16 09:09:40 +00003632 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3633 // actually comparing the expressions for equality. Because computing the
3634 // expression IDs can be expensive, we only do this if the diagnostic is
3635 // enabled.
3636 if (SizeOfArg &&
3637 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3638 SizeOfArg->getExprLoc())) {
3639 // We only compute IDs for expressions if the warning is enabled, and
3640 // cache the sizeof arg's ID.
3641 if (SizeOfArgID == llvm::FoldingSetNodeID())
3642 SizeOfArg->Profile(SizeOfArgID, Context, true);
3643 llvm::FoldingSetNodeID DestID;
3644 Dest->Profile(DestID, Context, true);
3645 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00003646 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3647 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00003648 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003649 StringRef ReadableName = FnName->getName();
3650
Chandler Carruth000d4282011-06-16 09:09:40 +00003651 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00003652 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00003653 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian7adf4172013-01-30 01:12:44 +00003654 if (!PointeeTy->isIncompleteType() &&
3655 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth000d4282011-06-16 09:09:40 +00003656 ActionIdx = 2; // If the pointee's size is sizeof(char),
3657 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003658
3659 // If the function is defined as a builtin macro, do not show macro
3660 // expansion.
3661 SourceLocation SL = SizeOfArg->getExprLoc();
3662 SourceRange DSR = Dest->getSourceRange();
3663 SourceRange SSR = SizeOfArg->getSourceRange();
3664 SourceManager &SM = PP.getSourceManager();
3665
3666 if (SM.isMacroArgExpansion(SL)) {
3667 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3668 SL = SM.getSpellingLoc(SL);
3669 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3670 SM.getSpellingLoc(DSR.getEnd()));
3671 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3672 SM.getSpellingLoc(SSR.getEnd()));
3673 }
3674
Anna Zaks90c78322012-05-30 23:14:52 +00003675 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00003676 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00003677 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00003678 << PointeeTy
3679 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00003680 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00003681 << SSR);
3682 DiagRuntimeBehavior(SL, SizeOfArg,
3683 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3684 << ActionIdx
3685 << SSR);
3686
Chandler Carruth000d4282011-06-16 09:09:40 +00003687 break;
3688 }
3689 }
3690
3691 // Also check for cases where the sizeof argument is the exact same
3692 // type as the memory argument, and where it points to a user-defined
3693 // record type.
3694 if (SizeOfArgTy != QualType()) {
3695 if (PointeeTy->isRecordType() &&
3696 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3697 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3698 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3699 << FnName << SizeOfArgTy << ArgIdx
3700 << PointeeTy << Dest->getSourceRange()
3701 << LenExpr->getSourceRange());
3702 break;
3703 }
Nico Webere4a1c642011-06-14 16:14:58 +00003704 }
3705
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003706 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00003707 if (isDynamicClassType(PointeeTy)) {
3708
3709 unsigned OperationType = 0;
3710 // "overwritten" if we're warning about the destination for any call
3711 // but memcmp; otherwise a verb appropriate to the call.
3712 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3713 if (BId == Builtin::BImemcpy)
3714 OperationType = 1;
3715 else if(BId == Builtin::BImemmove)
3716 OperationType = 2;
3717 else if (BId == Builtin::BImemcmp)
3718 OperationType = 3;
3719 }
3720
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003721 DiagRuntimeBehavior(
3722 Dest->getExprLoc(), Dest,
3723 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003724 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003725 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003726 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003727 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003728 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3729 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003730 DiagRuntimeBehavior(
3731 Dest->getExprLoc(), Dest,
3732 PDiag(diag::warn_arc_object_memaccess)
3733 << ArgIdx << FnName << PointeeTy
3734 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003735 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003736 continue;
John McCallf85e1932011-06-15 23:02:42 +00003737
3738 DiagRuntimeBehavior(
3739 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003740 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003741 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3742 break;
3743 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003744 }
3745}
3746
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003747// A little helper routine: ignore addition and subtraction of integer literals.
3748// This intentionally does not ignore all integer constant expressions because
3749// we don't want to remove sizeof().
3750static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3751 Ex = Ex->IgnoreParenCasts();
3752
3753 for (;;) {
3754 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3755 if (!BO || !BO->isAdditiveOp())
3756 break;
3757
3758 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3759 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3760
3761 if (isa<IntegerLiteral>(RHS))
3762 Ex = LHS;
3763 else if (isa<IntegerLiteral>(LHS))
3764 Ex = RHS;
3765 else
3766 break;
3767 }
3768
3769 return Ex;
3770}
3771
Anna Zaks0f38ace2012-08-08 21:42:23 +00003772static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3773 ASTContext &Context) {
3774 // Only handle constant-sized or VLAs, but not flexible members.
3775 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3776 // Only issue the FIXIT for arrays of size > 1.
3777 if (CAT->getSize().getSExtValue() <= 1)
3778 return false;
3779 } else if (!Ty->isVariableArrayType()) {
3780 return false;
3781 }
3782 return true;
3783}
3784
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003785// Warn if the user has made the 'size' argument to strlcpy or strlcat
3786// be the size of the source, instead of the destination.
3787void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3788 IdentifierInfo *FnName) {
3789
3790 // Don't crash if the user has the wrong number of arguments
3791 if (Call->getNumArgs() != 3)
3792 return;
3793
3794 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3795 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3796 const Expr *CompareWithSrc = NULL;
3797
3798 // Look for 'strlcpy(dst, x, sizeof(x))'
3799 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3800 CompareWithSrc = Ex;
3801 else {
3802 // Look for 'strlcpy(dst, x, strlen(x))'
3803 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003804 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003805 && SizeCall->getNumArgs() == 1)
3806 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3807 }
3808 }
3809
3810 if (!CompareWithSrc)
3811 return;
3812
3813 // Determine if the argument to sizeof/strlen is equal to the source
3814 // argument. In principle there's all kinds of things you could do
3815 // here, for instance creating an == expression and evaluating it with
3816 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3817 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3818 if (!SrcArgDRE)
3819 return;
3820
3821 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3822 if (!CompareWithSrcDRE ||
3823 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3824 return;
3825
3826 const Expr *OriginalSizeArg = Call->getArg(2);
3827 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3828 << OriginalSizeArg->getSourceRange() << FnName;
3829
3830 // Output a FIXIT hint if the destination is an array (rather than a
3831 // pointer to an array). This could be enhanced to handle some
3832 // pointers if we know the actual size, like if DstArg is 'array+2'
3833 // we could say 'sizeof(array)-2'.
3834 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00003835 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00003836 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00003837
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003838 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003839 llvm::raw_svector_ostream OS(sizeString);
3840 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003841 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003842 OS << ")";
3843
3844 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3845 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3846 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003847}
3848
Anna Zaksc36bedc2012-02-01 19:08:57 +00003849/// Check if two expressions refer to the same declaration.
3850static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3851 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3852 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3853 return D1->getDecl() == D2->getDecl();
3854 return false;
3855}
3856
3857static const Expr *getStrlenExprArg(const Expr *E) {
3858 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3859 const FunctionDecl *FD = CE->getDirectCallee();
3860 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3861 return 0;
3862 return CE->getArg(0)->IgnoreParenCasts();
3863 }
3864 return 0;
3865}
3866
3867// Warn on anti-patterns as the 'size' argument to strncat.
3868// The correct size argument should look like following:
3869// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3870void Sema::CheckStrncatArguments(const CallExpr *CE,
3871 IdentifierInfo *FnName) {
3872 // Don't crash if the user has the wrong number of arguments.
3873 if (CE->getNumArgs() < 3)
3874 return;
3875 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3876 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3877 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3878
3879 // Identify common expressions, which are wrongly used as the size argument
3880 // to strncat and may lead to buffer overflows.
3881 unsigned PatternType = 0;
3882 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3883 // - sizeof(dst)
3884 if (referToTheSameDecl(SizeOfArg, DstArg))
3885 PatternType = 1;
3886 // - sizeof(src)
3887 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3888 PatternType = 2;
3889 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3890 if (BE->getOpcode() == BO_Sub) {
3891 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3892 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3893 // - sizeof(dst) - strlen(dst)
3894 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3895 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3896 PatternType = 1;
3897 // - sizeof(src) - (anything)
3898 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3899 PatternType = 2;
3900 }
3901 }
3902
3903 if (PatternType == 0)
3904 return;
3905
Anna Zaksafdb0412012-02-03 01:27:37 +00003906 // Generate the diagnostic.
3907 SourceLocation SL = LenArg->getLocStart();
3908 SourceRange SR = LenArg->getSourceRange();
3909 SourceManager &SM = PP.getSourceManager();
3910
3911 // If the function is defined as a builtin macro, do not show macro expansion.
3912 if (SM.isMacroArgExpansion(SL)) {
3913 SL = SM.getSpellingLoc(SL);
3914 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3915 SM.getSpellingLoc(SR.getEnd()));
3916 }
3917
Anna Zaks0f38ace2012-08-08 21:42:23 +00003918 // Check if the destination is an array (rather than a pointer to an array).
3919 QualType DstTy = DstArg->getType();
3920 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3921 Context);
3922 if (!isKnownSizeArray) {
3923 if (PatternType == 1)
3924 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3925 else
3926 Diag(SL, diag::warn_strncat_src_size) << SR;
3927 return;
3928 }
3929
Anna Zaksc36bedc2012-02-01 19:08:57 +00003930 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003931 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003932 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003933 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003934
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003935 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003936 llvm::raw_svector_ostream OS(sizeString);
3937 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003938 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003939 OS << ") - ";
3940 OS << "strlen(";
Richard Smithd1420c62012-08-16 03:56:14 +00003941 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003942 OS << ") - 1";
3943
Anna Zaksafdb0412012-02-03 01:27:37 +00003944 Diag(SL, diag::note_strncat_wrong_size)
3945 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003946}
3947
Ted Kremenek06de2762007-08-17 16:46:58 +00003948//===--- CHECK: Return Address of Stack Variable --------------------------===//
3949
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003950static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3951 Decl *ParentDecl);
3952static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3953 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003954
3955/// CheckReturnStackAddr - Check if a return statement returns the address
3956/// of a stack variable.
3957void
3958Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3959 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003960
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003961 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003962 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003963
3964 // Perform checking for returned stack addresses, local blocks,
3965 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003966 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003967 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003968 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003969 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003970 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003971 }
3972
3973 if (stackE == 0)
3974 return; // Nothing suspicious was found.
3975
3976 SourceLocation diagLoc;
3977 SourceRange diagRange;
3978 if (refVars.empty()) {
3979 diagLoc = stackE->getLocStart();
3980 diagRange = stackE->getSourceRange();
3981 } else {
3982 // We followed through a reference variable. 'stackE' contains the
3983 // problematic expression but we will warn at the return statement pointing
3984 // at the reference variable. We will later display the "trail" of
3985 // reference variables using notes.
3986 diagLoc = refVars[0]->getLocStart();
3987 diagRange = refVars[0]->getSourceRange();
3988 }
3989
3990 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3991 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3992 : diag::warn_ret_stack_addr)
3993 << DR->getDecl()->getDeclName() << diagRange;
3994 } else if (isa<BlockExpr>(stackE)) { // local block.
3995 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3996 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3997 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3998 } else { // local temporary.
3999 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4000 : diag::warn_ret_local_temp_addr)
4001 << diagRange;
4002 }
4003
4004 // Display the "trail" of reference variables that we followed until we
4005 // found the problematic expression using notes.
4006 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4007 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4008 // If this var binds to another reference var, show the range of the next
4009 // var, otherwise the var binds to the problematic expression, in which case
4010 // show the range of the expression.
4011 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4012 : stackE->getSourceRange();
4013 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4014 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00004015 }
4016}
4017
4018/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4019/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004020/// to a location on the stack, a local block, an address of a label, or a
4021/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00004022/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004023/// encounter a subexpression that (1) clearly does not lead to one of the
4024/// above problematic expressions (2) is something we cannot determine leads to
4025/// a problematic expression based on such local checking.
4026///
4027/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4028/// the expression that they point to. Such variables are added to the
4029/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00004030///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00004031/// EvalAddr processes expressions that are pointers that are used as
4032/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004033/// At the base case of the recursion is a check for the above problematic
4034/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00004035///
4036/// This implementation handles:
4037///
4038/// * pointer-to-pointer casts
4039/// * implicit conversions from array references to pointers
4040/// * taking the address of fields
4041/// * arbitrary interplay between "&" and "*" operators
4042/// * pointer arithmetic from an address of a stack variable
4043/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004044static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4045 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004046 if (E->isTypeDependent())
Craig Topperb61c2942013-08-02 05:10:31 +00004047 return NULL;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004048
Ted Kremenek06de2762007-08-17 16:46:58 +00004049 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00004050 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00004051 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004052 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004053 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00004054
Peter Collingbournef111d932011-04-15 00:35:48 +00004055 E = E->IgnoreParens();
4056
Ted Kremenek06de2762007-08-17 16:46:58 +00004057 // Our "symbolic interpreter" is just a dispatch off the currently
4058 // viewed AST node. We then recursively traverse the AST by calling
4059 // EvalAddr and EvalVal appropriately.
4060 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004061 case Stmt::DeclRefExprClass: {
4062 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4063
4064 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4065 // If this is a reference variable, follow through to the expression that
4066 // it points to.
4067 if (V->hasLocalStorage() &&
4068 V->getType()->isReferenceType() && V->hasInit()) {
4069 // Add the reference variable to the "trail".
4070 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004071 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004072 }
4073
4074 return NULL;
4075 }
Ted Kremenek06de2762007-08-17 16:46:58 +00004076
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004077 case Stmt::UnaryOperatorClass: {
4078 // The only unary operator that make sense to handle here
4079 // is AddrOf. All others don't make sense as pointers.
4080 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004081
John McCall2de56d12010-08-25 11:45:40 +00004082 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004083 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004084 else
Ted Kremenek06de2762007-08-17 16:46:58 +00004085 return NULL;
4086 }
Mike Stump1eb44332009-09-09 15:08:12 +00004087
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004088 case Stmt::BinaryOperatorClass: {
4089 // Handle pointer arithmetic. All other binary operators are not valid
4090 // in this context.
4091 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00004092 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00004093
John McCall2de56d12010-08-25 11:45:40 +00004094 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004095 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00004096
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004097 Expr *Base = B->getLHS();
4098
4099 // Determine which argument is the real pointer base. It could be
4100 // the RHS argument instead of the LHS.
4101 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00004102
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004103 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004104 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004105 }
Steve Naroff61f40a22008-09-10 19:17:48 +00004106
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004107 // For conditional operators we need to see if either the LHS or RHS are
4108 // valid DeclRefExpr*s. If one of them is valid, we return it.
4109 case Stmt::ConditionalOperatorClass: {
4110 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004111
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004112 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004113 if (Expr *lhsExpr = C->getLHS()) {
4114 // In C++, we can have a throw-expression, which has 'void' type.
4115 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004116 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004117 return LHS;
4118 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004119
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004120 // In C++, we can have a throw-expression, which has 'void' type.
4121 if (C->getRHS()->getType()->isVoidType())
4122 return NULL;
4123
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004124 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004125 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004126
4127 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00004128 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004129 return E; // local block.
4130 return NULL;
4131
4132 case Stmt::AddrLabelExprClass:
4133 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00004134
John McCall80ee6e82011-11-10 05:35:25 +00004135 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004136 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4137 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00004138
Ted Kremenek54b52742008-08-07 00:49:01 +00004139 // For casts, we need to handle conversions from arrays to
4140 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00004141 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00004142 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00004143 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00004144 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00004145 case Stmt::CXXStaticCastExprClass:
4146 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00004147 case Stmt::CXXConstCastExprClass:
4148 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00004149 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4150 switch (cast<CastExpr>(E)->getCastKind()) {
4151 case CK_BitCast:
4152 case CK_LValueToRValue:
4153 case CK_NoOp:
4154 case CK_BaseToDerived:
4155 case CK_DerivedToBase:
4156 case CK_UncheckedDerivedToBase:
4157 case CK_Dynamic:
4158 case CK_CPointerToObjCPointerCast:
4159 case CK_BlockPointerToObjCPointerCast:
4160 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004161 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00004162
4163 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004164 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00004165
4166 default:
4167 return 0;
4168 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004169 }
Mike Stump1eb44332009-09-09 15:08:12 +00004170
Douglas Gregor03e80032011-06-21 17:03:29 +00004171 case Stmt::MaterializeTemporaryExprClass:
4172 if (Expr *Result = EvalAddr(
4173 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004174 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00004175 return Result;
4176
4177 return E;
4178
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004179 // Everything else: we simply don't reason about them.
4180 default:
4181 return NULL;
4182 }
Ted Kremenek06de2762007-08-17 16:46:58 +00004183}
Mike Stump1eb44332009-09-09 15:08:12 +00004184
Ted Kremenek06de2762007-08-17 16:46:58 +00004185
4186/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4187/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004188static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4189 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004190do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00004191 // We should only be called for evaluating non-pointer expressions, or
4192 // expressions with a pointer type that are not used as references but instead
4193 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00004194
Ted Kremenek06de2762007-08-17 16:46:58 +00004195 // Our "symbolic interpreter" is just a dispatch off the currently
4196 // viewed AST node. We then recursively traverse the AST by calling
4197 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00004198
4199 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00004200 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004201 case Stmt::ImplicitCastExprClass: {
4202 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00004203 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004204 E = IE->getSubExpr();
4205 continue;
4206 }
4207 return NULL;
4208 }
4209
John McCall80ee6e82011-11-10 05:35:25 +00004210 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004211 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00004212
Douglas Gregora2813ce2009-10-23 18:54:35 +00004213 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004214 // When we hit a DeclRefExpr we are looking at code that refers to a
4215 // variable's name. If it's not a reference variable we check if it has
4216 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00004217 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004218
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004219 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4220 // Check if it refers to itself, e.g. "int& i = i;".
4221 if (V == ParentDecl)
4222 return DR;
4223
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004224 if (V->hasLocalStorage()) {
4225 if (!V->getType()->isReferenceType())
4226 return DR;
4227
4228 // Reference variable, follow through to the expression that
4229 // it points to.
4230 if (V->hasInit()) {
4231 // Add the reference variable to the "trail".
4232 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004233 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004234 }
4235 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004236 }
Mike Stump1eb44332009-09-09 15:08:12 +00004237
Ted Kremenek06de2762007-08-17 16:46:58 +00004238 return NULL;
4239 }
Mike Stump1eb44332009-09-09 15:08:12 +00004240
Ted Kremenek06de2762007-08-17 16:46:58 +00004241 case Stmt::UnaryOperatorClass: {
4242 // The only unary operator that make sense to handle here
4243 // is Deref. All others don't resolve to a "name." This includes
4244 // handling all sorts of rvalues passed to a unary operator.
4245 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004246
John McCall2de56d12010-08-25 11:45:40 +00004247 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004248 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004249
4250 return NULL;
4251 }
Mike Stump1eb44332009-09-09 15:08:12 +00004252
Ted Kremenek06de2762007-08-17 16:46:58 +00004253 case Stmt::ArraySubscriptExprClass: {
4254 // Array subscripts are potential references to data on the stack. We
4255 // retrieve the DeclRefExpr* for the array variable if it indeed
4256 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004257 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004258 }
Mike Stump1eb44332009-09-09 15:08:12 +00004259
Ted Kremenek06de2762007-08-17 16:46:58 +00004260 case Stmt::ConditionalOperatorClass: {
4261 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004262 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00004263 ConditionalOperator *C = cast<ConditionalOperator>(E);
4264
Anders Carlsson39073232007-11-30 19:04:31 +00004265 // Handle the GNU extension for missing LHS.
4266 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004267 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00004268 return LHS;
4269
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004270 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004271 }
Mike Stump1eb44332009-09-09 15:08:12 +00004272
Ted Kremenek06de2762007-08-17 16:46:58 +00004273 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00004274 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00004275 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004276
Ted Kremenek06de2762007-08-17 16:46:58 +00004277 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00004278 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00004279 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00004280
4281 // Check whether the member type is itself a reference, in which case
4282 // we're not going to refer to the member, but to what the member refers to.
4283 if (M->getMemberDecl()->getType()->isReferenceType())
4284 return NULL;
4285
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004286 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004287 }
Mike Stump1eb44332009-09-09 15:08:12 +00004288
Douglas Gregor03e80032011-06-21 17:03:29 +00004289 case Stmt::MaterializeTemporaryExprClass:
4290 if (Expr *Result = EvalVal(
4291 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004292 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00004293 return Result;
4294
4295 return E;
4296
Ted Kremenek06de2762007-08-17 16:46:58 +00004297 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004298 // Check that we don't return or take the address of a reference to a
4299 // temporary. This is only useful in C++.
4300 if (!E->isTypeDependent() && E->isRValue())
4301 return E;
4302
4303 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00004304 return NULL;
4305 }
Ted Kremenek68957a92010-08-04 20:01:07 +00004306} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00004307}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004308
4309//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4310
4311/// Check for comparisons of floating point operands using != and ==.
4312/// Issue a warning if these are no self-comparisons, as they are not likely
4313/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00004314void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00004315 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4316 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004317
4318 // Special case: check for x == x (which is OK).
4319 // Do not emit warnings for such cases.
4320 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4321 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4322 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00004323 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004324
4325
Ted Kremenek1b500bb2007-11-29 00:59:04 +00004326 // Special case: check for comparisons against literals that can be exactly
4327 // represented by APFloat. In such cases, do not emit a warning. This
4328 // is a heuristic: often comparison against such literals are used to
4329 // detect if a value in a variable has not changed. This clearly can
4330 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00004331 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4332 if (FLL->isExact())
4333 return;
4334 } else
4335 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4336 if (FLR->isExact())
4337 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004338
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004339 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00004340 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
4341 if (CL->isBuiltinCall())
4342 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004343
David Blaikie980343b2012-07-16 20:47:22 +00004344 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
4345 if (CR->isBuiltinCall())
4346 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004347
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004348 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00004349 Diag(Loc, diag::warn_floatingpoint_eq)
4350 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004351}
John McCallba26e582010-01-04 23:21:16 +00004352
John McCallf2370c92010-01-06 05:24:50 +00004353//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4354//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00004355
John McCallf2370c92010-01-06 05:24:50 +00004356namespace {
John McCallba26e582010-01-04 23:21:16 +00004357
John McCallf2370c92010-01-06 05:24:50 +00004358/// Structure recording the 'active' range of an integer-valued
4359/// expression.
4360struct IntRange {
4361 /// The number of bits active in the int.
4362 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00004363
John McCallf2370c92010-01-06 05:24:50 +00004364 /// True if the int is known not to have negative values.
4365 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00004366
John McCallf2370c92010-01-06 05:24:50 +00004367 IntRange(unsigned Width, bool NonNegative)
4368 : Width(Width), NonNegative(NonNegative)
4369 {}
John McCallba26e582010-01-04 23:21:16 +00004370
John McCall1844a6e2010-11-10 23:38:19 +00004371 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00004372 static IntRange forBoolType() {
4373 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00004374 }
4375
John McCall1844a6e2010-11-10 23:38:19 +00004376 /// Returns the range of an opaque value of the given integral type.
4377 static IntRange forValueOfType(ASTContext &C, QualType T) {
4378 return forValueOfCanonicalType(C,
4379 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00004380 }
4381
John McCall1844a6e2010-11-10 23:38:19 +00004382 /// Returns the range of an opaque value of a canonical integral type.
4383 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00004384 assert(T->isCanonicalUnqualified());
4385
4386 if (const VectorType *VT = dyn_cast<VectorType>(T))
4387 T = VT->getElementType().getTypePtr();
4388 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4389 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00004390
David Majnemerf9eaf982013-06-07 22:07:20 +00004391 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00004392 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemerf9eaf982013-06-07 22:07:20 +00004393 EnumDecl *Enum = ET->getDecl();
4394 if (!Enum->isCompleteDefinition())
4395 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall091f23f2010-11-09 22:22:12 +00004396
David Majnemerf9eaf982013-06-07 22:07:20 +00004397 unsigned NumPositive = Enum->getNumPositiveBits();
4398 unsigned NumNegative = Enum->getNumNegativeBits();
John McCall323ed742010-05-06 08:58:33 +00004399
David Majnemerf9eaf982013-06-07 22:07:20 +00004400 if (NumNegative == 0)
4401 return IntRange(NumPositive, true/*NonNegative*/);
4402 else
4403 return IntRange(std::max(NumPositive + 1, NumNegative),
4404 false/*NonNegative*/);
John McCall323ed742010-05-06 08:58:33 +00004405 }
John McCallf2370c92010-01-06 05:24:50 +00004406
4407 const BuiltinType *BT = cast<BuiltinType>(T);
4408 assert(BT->isInteger());
4409
4410 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4411 }
4412
John McCall1844a6e2010-11-10 23:38:19 +00004413 /// Returns the "target" range of a canonical integral type, i.e.
4414 /// the range of values expressible in the type.
4415 ///
4416 /// This matches forValueOfCanonicalType except that enums have the
4417 /// full range of their type, not the range of their enumerators.
4418 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4419 assert(T->isCanonicalUnqualified());
4420
4421 if (const VectorType *VT = dyn_cast<VectorType>(T))
4422 T = VT->getElementType().getTypePtr();
4423 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4424 T = CT->getElementType().getTypePtr();
4425 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00004426 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00004427
4428 const BuiltinType *BT = cast<BuiltinType>(T);
4429 assert(BT->isInteger());
4430
4431 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4432 }
4433
4434 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004435 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00004436 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00004437 L.NonNegative && R.NonNegative);
4438 }
4439
John McCall1844a6e2010-11-10 23:38:19 +00004440 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004441 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00004442 return IntRange(std::min(L.Width, R.Width),
4443 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00004444 }
4445};
4446
Ted Kremenek0692a192012-01-31 05:37:37 +00004447static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4448 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004449 if (value.isSigned() && value.isNegative())
4450 return IntRange(value.getMinSignedBits(), false);
4451
4452 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00004453 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004454
4455 // isNonNegative() just checks the sign bit without considering
4456 // signedness.
4457 return IntRange(value.getActiveBits(), true);
4458}
4459
Ted Kremenek0692a192012-01-31 05:37:37 +00004460static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4461 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004462 if (result.isInt())
4463 return GetValueRange(C, result.getInt(), MaxWidth);
4464
4465 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00004466 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4467 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4468 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4469 R = IntRange::join(R, El);
4470 }
John McCallf2370c92010-01-06 05:24:50 +00004471 return R;
4472 }
4473
4474 if (result.isComplexInt()) {
4475 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4476 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4477 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00004478 }
4479
4480 // This can happen with lossless casts to intptr_t of "based" lvalues.
4481 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00004482 // FIXME: The only reason we need to pass the type in here is to get
4483 // the sign right on this one case. It would be nice if APValue
4484 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00004485 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004486 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00004487}
John McCallf2370c92010-01-06 05:24:50 +00004488
Eli Friedman09bddcf2013-07-08 20:20:06 +00004489static QualType GetExprType(Expr *E) {
4490 QualType Ty = E->getType();
4491 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4492 Ty = AtomicRHS->getValueType();
4493 return Ty;
4494}
4495
John McCallf2370c92010-01-06 05:24:50 +00004496/// Pseudo-evaluate the given integer expression, estimating the
4497/// range of values it might take.
4498///
4499/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00004500static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004501 E = E->IgnoreParens();
4502
4503 // Try a full evaluation first.
4504 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004505 if (E->EvaluateAsRValue(result, C))
Eli Friedman09bddcf2013-07-08 20:20:06 +00004506 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004507
4508 // I think we only want to look through implicit casts here; if the
4509 // user has an explicit widening cast, we should treat the value as
4510 // being of the new, wider type.
4511 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00004512 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00004513 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4514
Eli Friedman09bddcf2013-07-08 20:20:06 +00004515 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCallf2370c92010-01-06 05:24:50 +00004516
John McCall2de56d12010-08-25 11:45:40 +00004517 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00004518
John McCallf2370c92010-01-06 05:24:50 +00004519 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00004520 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00004521 return OutputTypeRange;
4522
4523 IntRange SubRange
4524 = GetExprRange(C, CE->getSubExpr(),
4525 std::min(MaxWidth, OutputTypeRange.Width));
4526
4527 // Bail out if the subexpr's range is as wide as the cast type.
4528 if (SubRange.Width >= OutputTypeRange.Width)
4529 return OutputTypeRange;
4530
4531 // Otherwise, we take the smaller width, and we're non-negative if
4532 // either the output type or the subexpr is.
4533 return IntRange(SubRange.Width,
4534 SubRange.NonNegative || OutputTypeRange.NonNegative);
4535 }
4536
4537 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4538 // If we can fold the condition, just take that operand.
4539 bool CondResult;
4540 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4541 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4542 : CO->getFalseExpr(),
4543 MaxWidth);
4544
4545 // Otherwise, conservatively merge.
4546 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4547 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4548 return IntRange::join(L, R);
4549 }
4550
4551 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4552 switch (BO->getOpcode()) {
4553
4554 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00004555 case BO_LAnd:
4556 case BO_LOr:
4557 case BO_LT:
4558 case BO_GT:
4559 case BO_LE:
4560 case BO_GE:
4561 case BO_EQ:
4562 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00004563 return IntRange::forBoolType();
4564
John McCall862ff872011-07-13 06:35:24 +00004565 // The type of the assignments is the type of the LHS, so the RHS
4566 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00004567 case BO_MulAssign:
4568 case BO_DivAssign:
4569 case BO_RemAssign:
4570 case BO_AddAssign:
4571 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00004572 case BO_XorAssign:
4573 case BO_OrAssign:
4574 // TODO: bitfields?
Eli Friedman09bddcf2013-07-08 20:20:06 +00004575 return IntRange::forValueOfType(C, GetExprType(E));
John McCallc0cd21d2010-02-23 19:22:29 +00004576
John McCall862ff872011-07-13 06:35:24 +00004577 // Simple assignments just pass through the RHS, which will have
4578 // been coerced to the LHS type.
4579 case BO_Assign:
4580 // TODO: bitfields?
4581 return GetExprRange(C, BO->getRHS(), MaxWidth);
4582
John McCallf2370c92010-01-06 05:24:50 +00004583 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004584 case BO_PtrMemD:
4585 case BO_PtrMemI:
Eli Friedman09bddcf2013-07-08 20:20:06 +00004586 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004587
John McCall60fad452010-01-06 22:07:33 +00004588 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00004589 case BO_And:
4590 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00004591 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4592 GetExprRange(C, BO->getRHS(), MaxWidth));
4593
John McCallf2370c92010-01-06 05:24:50 +00004594 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00004595 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00004596 // ...except that we want to treat '1 << (blah)' as logically
4597 // positive. It's an important idiom.
4598 if (IntegerLiteral *I
4599 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4600 if (I->getValue() == 1) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00004601 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall3aae6092010-04-07 01:14:35 +00004602 return IntRange(R.Width, /*NonNegative*/ true);
4603 }
4604 }
4605 // fallthrough
4606
John McCall2de56d12010-08-25 11:45:40 +00004607 case BO_ShlAssign:
Eli Friedman09bddcf2013-07-08 20:20:06 +00004608 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004609
John McCall60fad452010-01-06 22:07:33 +00004610 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00004611 case BO_Shr:
4612 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00004613 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4614
4615 // If the shift amount is a positive constant, drop the width by
4616 // that much.
4617 llvm::APSInt shift;
4618 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4619 shift.isNonNegative()) {
4620 unsigned zext = shift.getZExtValue();
4621 if (zext >= L.Width)
4622 L.Width = (L.NonNegative ? 0 : 1);
4623 else
4624 L.Width -= zext;
4625 }
4626
4627 return L;
4628 }
4629
4630 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00004631 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00004632 return GetExprRange(C, BO->getRHS(), MaxWidth);
4633
John McCall60fad452010-01-06 22:07:33 +00004634 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00004635 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00004636 if (BO->getLHS()->getType()->isPointerType())
Eli Friedman09bddcf2013-07-08 20:20:06 +00004637 return IntRange::forValueOfType(C, GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004638 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00004639
John McCall00fe7612011-07-14 22:39:48 +00004640 // The width of a division result is mostly determined by the size
4641 // of the LHS.
4642 case BO_Div: {
4643 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00004644 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004645 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4646
4647 // If the divisor is constant, use that.
4648 llvm::APSInt divisor;
4649 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4650 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4651 if (log2 >= L.Width)
4652 L.Width = (L.NonNegative ? 0 : 1);
4653 else
4654 L.Width = std::min(L.Width - log2, MaxWidth);
4655 return L;
4656 }
4657
4658 // Otherwise, just use the LHS's width.
4659 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4660 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4661 }
4662
4663 // The result of a remainder can't be larger than the result of
4664 // either side.
4665 case BO_Rem: {
4666 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00004667 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004668 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4669 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4670
4671 IntRange meet = IntRange::meet(L, R);
4672 meet.Width = std::min(meet.Width, MaxWidth);
4673 return meet;
4674 }
4675
4676 // The default behavior is okay for these.
4677 case BO_Mul:
4678 case BO_Add:
4679 case BO_Xor:
4680 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00004681 break;
4682 }
4683
John McCall00fe7612011-07-14 22:39:48 +00004684 // The default case is to treat the operation as if it were closed
4685 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004686 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4687 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4688 return IntRange::join(L, R);
4689 }
4690
4691 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4692 switch (UO->getOpcode()) {
4693 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004694 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004695 return IntRange::forBoolType();
4696
4697 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004698 case UO_Deref:
4699 case UO_AddrOf: // should be impossible
Eli Friedman09bddcf2013-07-08 20:20:06 +00004700 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004701
4702 default:
4703 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4704 }
4705 }
4706
Ted Kremenek728a1fb2013-10-14 18:55:27 +00004707 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
4708 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
4709
John McCall993f43f2013-05-06 21:39:12 +00004710 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004711 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004712 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004713
Eli Friedman09bddcf2013-07-08 20:20:06 +00004714 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004715}
John McCall51313c32010-01-04 23:31:57 +00004716
Ted Kremenek0692a192012-01-31 05:37:37 +00004717static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00004718 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCall323ed742010-05-06 08:58:33 +00004719}
4720
John McCall51313c32010-01-04 23:31:57 +00004721/// Checks whether the given value, which currently has the given
4722/// source semantics, has the same value when coerced through the
4723/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004724static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4725 const llvm::fltSemantics &Src,
4726 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004727 llvm::APFloat truncated = value;
4728
4729 bool ignored;
4730 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4731 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4732
4733 return truncated.bitwiseIsEqual(value);
4734}
4735
4736/// Checks whether the given value, which currently has the given
4737/// source semantics, has the same value when coerced through the
4738/// target semantics.
4739///
4740/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004741static bool IsSameFloatAfterCast(const APValue &value,
4742 const llvm::fltSemantics &Src,
4743 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004744 if (value.isFloat())
4745 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4746
4747 if (value.isVector()) {
4748 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4749 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4750 return false;
4751 return true;
4752 }
4753
4754 assert(value.isComplexFloat());
4755 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4756 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4757}
4758
Ted Kremenek0692a192012-01-31 05:37:37 +00004759static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004760
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004761static bool IsZero(Sema &S, Expr *E) {
4762 // Suppress cases where we are comparing against an enum constant.
4763 if (const DeclRefExpr *DR =
4764 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4765 if (isa<EnumConstantDecl>(DR->getDecl()))
4766 return false;
4767
4768 // Suppress cases where the '0' value is expanded from a macro.
4769 if (E->getLocStart().isMacroID())
4770 return false;
4771
John McCall323ed742010-05-06 08:58:33 +00004772 llvm::APSInt Value;
4773 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4774}
4775
John McCall372e1032010-10-06 00:25:24 +00004776static bool HasEnumType(Expr *E) {
4777 // Strip off implicit integral promotions.
4778 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004779 if (ICE->getCastKind() != CK_IntegralCast &&
4780 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004781 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004782 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004783 }
4784
4785 return E->getType()->isEnumeralType();
4786}
4787
Ted Kremenek0692a192012-01-31 05:37:37 +00004788static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieucbc19872013-11-01 21:47:19 +00004789 // Disable warning in template instantiations.
4790 if (!S.ActiveTemplateInstantiations.empty())
4791 return;
4792
John McCall2de56d12010-08-25 11:45:40 +00004793 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004794 if (E->isValueDependent())
4795 return;
4796
John McCall2de56d12010-08-25 11:45:40 +00004797 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004798 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004799 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004800 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004801 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004802 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004803 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004804 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004805 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004806 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004807 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004808 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004809 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004810 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004811 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004812 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4813 }
4814}
4815
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004816static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004817 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004818 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004819 bool RhsConstant) {
Richard Trieu311cb2b2013-11-01 21:19:43 +00004820 // Disable warning in template instantiations.
4821 if (!S.ActiveTemplateInstantiations.empty())
4822 return;
4823
Richard Trieu526e6272012-11-14 22:50:24 +00004824 // 0 values are handled later by CheckTrivialUnsignedComparison().
4825 if (Value == 0)
4826 return;
4827
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004828 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004829 QualType OtherT = Other->getType();
4830 QualType ConstantT = Constant->getType();
Richard Trieu526e6272012-11-14 22:50:24 +00004831 QualType CommonT = E->getLHS()->getType();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004832 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004833 return;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004834 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004835 && "comparison with non-integer type");
Richard Trieu526e6272012-11-14 22:50:24 +00004836
4837 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu526e6272012-11-14 22:50:24 +00004838 bool CommonSigned = CommonT->isSignedIntegerType();
4839
4840 bool EqualityOnly = false;
4841
4842 // TODO: Investigate using GetExprRange() to get tighter bounds on
4843 // on the bit ranges.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004844 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu526e6272012-11-14 22:50:24 +00004845 unsigned OtherWidth = OtherRange.Width;
4846
4847 if (CommonSigned) {
4848 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedmand87de7b2012-11-30 23:09:29 +00004849 if (!OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004850 // Check that the constant is representable in type OtherT.
4851 if (ConstantSigned) {
4852 if (OtherWidth >= Value.getMinSignedBits())
4853 return;
4854 } else { // !ConstantSigned
4855 if (OtherWidth >= Value.getActiveBits() + 1)
4856 return;
4857 }
4858 } else { // !OtherSigned
4859 // Check that the constant is representable in type OtherT.
4860 // Negative values are out of range.
4861 if (ConstantSigned) {
4862 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4863 return;
4864 } else { // !ConstantSigned
4865 if (OtherWidth >= Value.getActiveBits())
4866 return;
4867 }
4868 }
4869 } else { // !CommonSigned
Eli Friedmand87de7b2012-11-30 23:09:29 +00004870 if (OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004871 if (OtherWidth >= Value.getActiveBits())
4872 return;
Eli Friedmand87de7b2012-11-30 23:09:29 +00004873 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu526e6272012-11-14 22:50:24 +00004874 // Check to see if the constant is representable in OtherT.
4875 if (OtherWidth > Value.getActiveBits())
4876 return;
4877 // Check to see if the constant is equivalent to a negative value
4878 // cast to CommonT.
4879 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu5d1cf4f2012-11-15 03:43:50 +00004880 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu526e6272012-11-14 22:50:24 +00004881 return;
4882 // The constant value rests between values that OtherT can represent after
4883 // conversion. Relational comparison still works, but equality
4884 // comparisons will be tautological.
4885 EqualityOnly = true;
4886 } else { // OtherSigned && ConstantSigned
4887 assert(0 && "Two signed types converted to unsigned types.");
4888 }
4889 }
4890
4891 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4892
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004893 bool IsTrue = true;
Richard Trieu526e6272012-11-14 22:50:24 +00004894 if (op == BO_EQ || op == BO_NE) {
4895 IsTrue = op == BO_NE;
4896 } else if (EqualityOnly) {
4897 return;
4898 } else if (RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004899 if (op == BO_GT || op == BO_GE)
Richard Trieu526e6272012-11-14 22:50:24 +00004900 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004901 else // op == BO_LT || op == BO_LE
Richard Trieu526e6272012-11-14 22:50:24 +00004902 IsTrue = PositiveConstant;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004903 } else {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004904 if (op == BO_LT || op == BO_LE)
Richard Trieu526e6272012-11-14 22:50:24 +00004905 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004906 else // op == BO_GT || op == BO_GE
Richard Trieu526e6272012-11-14 22:50:24 +00004907 IsTrue = PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004908 }
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004909
4910 // If this is a comparison to an enum constant, include that
4911 // constant in the diagnostic.
4912 const EnumConstantDecl *ED = 0;
4913 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
4914 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
4915
4916 SmallString<64> PrettySourceValue;
4917 llvm::raw_svector_ostream OS(PrettySourceValue);
4918 if (ED)
Ted Kremenek9de50942013-03-15 22:02:46 +00004919 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004920 else
4921 OS << Value;
4922
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004923 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004924 << OS.str() << OtherT << IsTrue
Richard Trieu526e6272012-11-14 22:50:24 +00004925 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004926}
4927
John McCall323ed742010-05-06 08:58:33 +00004928/// Analyze the operands of the given comparison. Implements the
4929/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004930static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004931 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4932 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004933}
John McCall51313c32010-01-04 23:31:57 +00004934
John McCallba26e582010-01-04 23:21:16 +00004935/// \brief Implements -Wsign-compare.
4936///
Richard Trieudd225092011-09-15 21:56:47 +00004937/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004938static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004939 // The type the comparison is being performed in.
4940 QualType T = E->getLHS()->getType();
4941 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4942 && "comparison with mismatched types");
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00004943 if (E->isValueDependent())
4944 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004945
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004946 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4947 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004948
4949 bool IsComparisonConstant = false;
4950
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004951 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004952 // of 'true' or 'false'.
4953 if (T->isIntegralType(S.Context)) {
4954 llvm::APSInt RHSValue;
4955 bool IsRHSIntegralLiteral =
4956 RHS->isIntegerConstantExpr(RHSValue, S.Context);
4957 llvm::APSInt LHSValue;
4958 bool IsLHSIntegralLiteral =
4959 LHS->isIntegerConstantExpr(LHSValue, S.Context);
4960 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4961 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4962 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4963 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4964 else
4965 IsComparisonConstant =
4966 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004967 } else if (!T->hasUnsignedIntegerRepresentation())
4968 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004969
John McCall323ed742010-05-06 08:58:33 +00004970 // We don't do anything special if this isn't an unsigned integral
4971 // comparison: we're only interested in integral comparisons, and
4972 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004973 //
4974 // We also don't care about value-dependent expressions or expressions
4975 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004976 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00004977 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004978
John McCall323ed742010-05-06 08:58:33 +00004979 // Check to see if one of the (unmodified) operands is of different
4980 // signedness.
4981 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004982 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4983 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004984 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004985 signedOperand = LHS;
4986 unsignedOperand = RHS;
4987 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4988 signedOperand = RHS;
4989 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004990 } else {
John McCall323ed742010-05-06 08:58:33 +00004991 CheckTrivialUnsignedComparison(S, E);
4992 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004993 }
4994
John McCall323ed742010-05-06 08:58:33 +00004995 // Otherwise, calculate the effective range of the signed operand.
4996 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004997
John McCall323ed742010-05-06 08:58:33 +00004998 // Go ahead and analyze implicit conversions in the operands. Note
4999 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00005000 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5001 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00005002
John McCall323ed742010-05-06 08:58:33 +00005003 // If the signed range is non-negative, -Wsign-compare won't fire,
5004 // but we should still check for comparisons which are always true
5005 // or false.
5006 if (signedRange.NonNegative)
5007 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00005008
5009 // For (in)equality comparisons, if the unsigned operand is a
5010 // constant which cannot collide with a overflowed signed operand,
5011 // then reinterpreting the signed operand as unsigned will not
5012 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00005013 if (E->isEqualityOp()) {
5014 unsigned comparisonWidth = S.Context.getIntWidth(T);
5015 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00005016
John McCall323ed742010-05-06 08:58:33 +00005017 // We should never be unable to prove that the unsigned operand is
5018 // non-negative.
5019 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5020
5021 if (unsignedRange.Width < comparisonWidth)
5022 return;
5023 }
5024
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00005025 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5026 S.PDiag(diag::warn_mixed_sign_comparison)
5027 << LHS->getType() << RHS->getType()
5028 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00005029}
5030
John McCall15d7d122010-11-11 03:21:53 +00005031/// Analyzes an attempt to assign the given value to a bitfield.
5032///
5033/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00005034static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5035 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00005036 assert(Bitfield->isBitField());
5037 if (Bitfield->isInvalidDecl())
5038 return false;
5039
John McCall91b60142010-11-11 05:33:51 +00005040 // White-list bool bitfields.
5041 if (Bitfield->getType()->isBooleanType())
5042 return false;
5043
Douglas Gregor46ff3032011-02-04 13:09:01 +00005044 // Ignore value- or type-dependent expressions.
5045 if (Bitfield->getBitWidth()->isValueDependent() ||
5046 Bitfield->getBitWidth()->isTypeDependent() ||
5047 Init->isValueDependent() ||
5048 Init->isTypeDependent())
5049 return false;
5050
John McCall15d7d122010-11-11 03:21:53 +00005051 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5052
Richard Smith80d4b552011-12-28 19:48:30 +00005053 llvm::APSInt Value;
5054 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00005055 return false;
5056
John McCall15d7d122010-11-11 03:21:53 +00005057 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005058 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00005059
5060 if (OriginalWidth <= FieldWidth)
5061 return false;
5062
Eli Friedman3a643af2012-01-26 23:11:39 +00005063 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00005064 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00005065 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00005066
Eli Friedman3a643af2012-01-26 23:11:39 +00005067 // Check whether the stored value is equal to the original value.
5068 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00005069 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00005070 return false;
5071
Eli Friedman3a643af2012-01-26 23:11:39 +00005072 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00005073 // therefore don't strictly fit into a signed bitfield of width 1.
5074 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00005075 return false;
5076
John McCall15d7d122010-11-11 03:21:53 +00005077 std::string PrettyValue = Value.toString(10);
5078 std::string PrettyTrunc = TruncatedValue.toString(10);
5079
5080 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5081 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5082 << Init->getSourceRange();
5083
5084 return true;
5085}
5086
John McCallbeb22aa2010-11-09 23:24:47 +00005087/// Analyze the given simple or compound assignment for warning-worthy
5088/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00005089static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00005090 // Just recurse on the LHS.
5091 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5092
5093 // We want to recurse on the RHS as normal unless we're assigning to
5094 // a bitfield.
John McCall993f43f2013-05-06 21:39:12 +00005095 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005096 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall15d7d122010-11-11 03:21:53 +00005097 E->getOperatorLoc())) {
5098 // Recurse, ignoring any implicit conversions on the RHS.
5099 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5100 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00005101 }
5102 }
5103
5104 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5105}
5106
John McCall51313c32010-01-04 23:31: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 SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00005109 SourceLocation CContext, unsigned diag,
5110 bool pruneControlFlow = false) {
5111 if (pruneControlFlow) {
5112 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5113 S.PDiag(diag)
5114 << SourceType << T << E->getSourceRange()
5115 << SourceRange(CContext));
5116 return;
5117 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005118 S.Diag(E->getExprLoc(), diag)
5119 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5120}
5121
Chandler Carruthe1b02e02011-04-05 06:47:57 +00005122/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00005123static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00005124 SourceLocation CContext, unsigned diag,
5125 bool pruneControlFlow = false) {
5126 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00005127}
5128
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005129/// Diagnose an implicit cast from a literal expression. Does not warn when the
5130/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00005131void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5132 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005133 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00005134 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005135 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00005136 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5137 T->hasUnsignedIntegerRepresentation());
5138 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00005139 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005140 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00005141 return;
5142
Eli Friedman4e1a82c2013-08-29 23:44:43 +00005143 // FIXME: Force the precision of the source value down so we don't print
5144 // digits which are usually useless (we don't really care here if we
5145 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5146 // would automatically print the shortest representation, but it's a bit
5147 // tricky to implement.
David Blaikiebe0ee872012-05-15 16:56:36 +00005148 SmallString<16> PrettySourceValue;
Eli Friedman4e1a82c2013-08-29 23:44:43 +00005149 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5150 precision = (precision * 59 + 195) / 196;
5151 Value.toString(PrettySourceValue, precision);
5152
David Blaikiede7e7b82012-05-15 17:18:27 +00005153 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00005154 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5155 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5156 else
David Blaikiede7e7b82012-05-15 17:18:27 +00005157 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00005158
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005159 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00005160 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5161 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00005162}
5163
John McCall091f23f2010-11-09 22:22:12 +00005164std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5165 if (!Range.Width) return "0";
5166
5167 llvm::APSInt ValueInRange = Value;
5168 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00005169 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00005170 return ValueInRange.toString(10);
5171}
5172
Hans Wennborg88617a22012-08-28 15:44:30 +00005173static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5174 if (!isa<ImplicitCastExpr>(Ex))
5175 return false;
5176
5177 Expr *InnerE = Ex->IgnoreParenImpCasts();
5178 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5179 const Type *Source =
5180 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5181 if (Target->isDependentType())
5182 return false;
5183
5184 const BuiltinType *FloatCandidateBT =
5185 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5186 const Type *BoolCandidateType = ToBool ? Target : Source;
5187
5188 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5189 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5190}
5191
5192void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5193 SourceLocation CC) {
5194 unsigned NumArgs = TheCall->getNumArgs();
5195 for (unsigned i = 0; i < NumArgs; ++i) {
5196 Expr *CurrA = TheCall->getArg(i);
5197 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5198 continue;
5199
5200 bool IsSwapped = ((i > 0) &&
5201 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5202 IsSwapped |= ((i < (NumArgs - 1)) &&
5203 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5204 if (IsSwapped) {
5205 // Warn on this floating-point to bool conversion.
5206 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5207 CurrA->getType(), CC,
5208 diag::warn_impcast_floating_point_to_bool);
5209 }
5210 }
5211}
5212
John McCall323ed742010-05-06 08:58:33 +00005213void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005214 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00005215 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00005216
John McCall323ed742010-05-06 08:58:33 +00005217 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5218 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5219 if (Source == Target) return;
5220 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00005221
Chandler Carruth108f7562011-07-26 05:40:03 +00005222 // If the conversion context location is invalid don't complain. We also
5223 // don't want to emit a warning if the issue occurs from the expansion of
5224 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5225 // delay this check as long as possible. Once we detect we are in that
5226 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00005227 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00005228 return;
5229
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005230 // Diagnose implicit casts to bool.
5231 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5232 if (isa<StringLiteral>(E))
5233 // Warn on string literal to bool. Checks for string literals in logical
5234 // expressions, for instances, assert(0 && "error here"), is prevented
5235 // by a check in AnalyzeImplicitConversions().
5236 return DiagnoseImpCast(S, E, T, CC,
5237 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00005238 if (Source->isFunctionType()) {
5239 // Warn on function to bool. Checks free functions and static member
5240 // functions. Weakly imported functions are excluded from the check,
5241 // since it's common to test their value to check whether the linker
5242 // found a definition for them.
5243 ValueDecl *D = 0;
5244 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
5245 D = R->getDecl();
5246 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
5247 D = M->getMemberDecl();
5248 }
5249
5250 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00005251 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
5252 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
5253 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00005254 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
5255 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
5256 QualType ReturnType;
5257 UnresolvedSet<4> NonTemplateOverloads;
David Blaikiec8fa5252013-06-21 23:54:45 +00005258 S.tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
David Blaikie2def7732011-12-09 21:42:37 +00005259 if (!ReturnType.isNull()
5260 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
5261 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
5262 << FixItHint::CreateInsertion(
5263 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00005264 return;
5265 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00005266 }
5267 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005268 }
John McCall51313c32010-01-04 23:31:57 +00005269
5270 // Strip vector types.
5271 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005272 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005273 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005274 return;
John McCallb4eb64d2010-10-08 02:01:28 +00005275 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005276 }
Chris Lattnerb792b302011-06-14 04:51:15 +00005277
5278 // If the vector cast is cast between two vectors of the same size, it is
5279 // a bitcast, not a conversion.
5280 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5281 return;
John McCall51313c32010-01-04 23:31:57 +00005282
5283 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5284 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5285 }
5286
5287 // Strip complex types.
5288 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005289 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005290 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005291 return;
5292
John McCallb4eb64d2010-10-08 02:01:28 +00005293 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005294 }
John McCall51313c32010-01-04 23:31:57 +00005295
5296 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5297 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5298 }
5299
5300 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5301 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5302
5303 // If the source is floating point...
5304 if (SourceBT && SourceBT->isFloatingPoint()) {
5305 // ...and the target is floating point...
5306 if (TargetBT && TargetBT->isFloatingPoint()) {
5307 // ...then warn if we're dropping FP rank.
5308
5309 // Builtin FP kinds are ordered by increasing FP rank.
5310 if (SourceBT->getKind() > TargetBT->getKind()) {
5311 // Don't warn about float constants that are precisely
5312 // representable in the target type.
5313 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00005314 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00005315 // Value might be a float, a float vector, or a float complex.
5316 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00005317 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5318 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00005319 return;
5320 }
5321
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005322 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005323 return;
5324
John McCallb4eb64d2010-10-08 02:01:28 +00005325 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00005326 }
5327 return;
5328 }
5329
Ted Kremenekef9ff882011-03-10 20:03:42 +00005330 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00005331 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005332 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005333 return;
5334
Chandler Carrutha5b93322011-02-17 11:05:49 +00005335 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00005336 // We also want to warn on, e.g., "int i = -1.234"
5337 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5338 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5339 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5340
Chandler Carruthf65076e2011-04-10 08:36:24 +00005341 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5342 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00005343 } else {
5344 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5345 }
5346 }
John McCall51313c32010-01-04 23:31:57 +00005347
Hans Wennborg88617a22012-08-28 15:44:30 +00005348 // If the target is bool, warn if expr is a function or method call.
5349 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5350 isa<CallExpr>(E)) {
5351 // Check last argument of function call to see if it is an
5352 // implicit cast from a type matching the type the result
5353 // is being cast to.
5354 CallExpr *CEx = cast<CallExpr>(E);
5355 unsigned NumArgs = CEx->getNumArgs();
5356 if (NumArgs > 0) {
5357 Expr *LastA = CEx->getArg(NumArgs - 1);
5358 Expr *InnerE = LastA->IgnoreParenImpCasts();
5359 const Type *InnerType =
5360 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5361 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5362 // Warn on this floating-point to bool conversion
5363 DiagnoseImpCast(S, E, T, CC,
5364 diag::warn_impcast_floating_point_to_bool);
5365 }
5366 }
5367 }
John McCall51313c32010-01-04 23:31:57 +00005368 return;
5369 }
5370
Richard Trieu1838ca52011-05-29 19:59:02 +00005371 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00005372 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiee81b43b2012-11-08 00:41:20 +00005373 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikie896c7dd2013-02-16 00:56:22 +00005374 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieb1360492012-03-16 20:30:12 +00005375 SourceLocation Loc = E->getSourceRange().getBegin();
5376 if (Loc.isMacroID())
5377 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00005378 if (!Loc.isMacroID() || CC.isMacroID())
5379 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5380 << T << clang::SourceRange(CC)
Richard Smith8adf8372013-09-20 00:27:40 +00005381 << FixItHint::CreateReplacement(Loc,
5382 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieu1838ca52011-05-29 19:59:02 +00005383 }
5384
David Blaikieb26331b2012-06-19 21:19:06 +00005385 if (!Source->isIntegerType() || !Target->isIntegerType())
5386 return;
5387
David Blaikiebe0ee872012-05-15 16:56:36 +00005388 // TODO: remove this early return once the false positives for constant->bool
5389 // in templates, macros, etc, are reduced or removed.
5390 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5391 return;
5392
John McCall323ed742010-05-06 08:58:33 +00005393 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00005394 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00005395
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005396 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer25ffbef2013-03-28 19:07:11 +00005397 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005398 // TODO: this should happen for bitfield stores, too.
5399 llvm::APSInt Value(32);
5400 if (E->isIntegerConstantExpr(Value, S.Context)) {
5401 if (S.SourceMgr.isInSystemMacro(CC))
5402 return;
5403
John McCall091f23f2010-11-09 22:22:12 +00005404 std::string PrettySourceValue = Value.toString(10);
5405 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005406
Ted Kremenek5e745da2011-10-22 02:37:33 +00005407 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5408 S.PDiag(diag::warn_impcast_integer_precision_constant)
5409 << PrettySourceValue << PrettyTargetValue
5410 << E->getType() << T << E->getSourceRange()
5411 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00005412 return;
5413 }
5414
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005415 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5416 if (S.SourceMgr.isInSystemMacro(CC))
5417 return;
5418
David Blaikie37050842012-04-12 22:40:54 +00005419 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00005420 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5421 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00005422 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00005423 }
5424
5425 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5426 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5427 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005428
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005429 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005430 return;
5431
John McCall323ed742010-05-06 08:58:33 +00005432 unsigned DiagID = diag::warn_impcast_integer_sign;
5433
5434 // Traditionally, gcc has warned about this under -Wsign-compare.
5435 // We also want to warn about it in -Wconversion.
5436 // So if -Wconversion is off, use a completely identical diagnostic
5437 // in the sign-compare group.
5438 // The conditional-checking code will
5439 if (ICContext) {
5440 DiagID = diag::warn_impcast_integer_sign_conditional;
5441 *ICContext = true;
5442 }
5443
John McCallb4eb64d2010-10-08 02:01:28 +00005444 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00005445 }
5446
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005447 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005448 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5449 // type, to give us better diagnostics.
5450 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00005451 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005452 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5453 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5454 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5455 SourceType = S.Context.getTypeDeclType(Enum);
5456 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5457 }
5458 }
5459
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005460 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5461 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall83972f12013-03-09 00:54:27 +00005462 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5463 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00005464 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005465 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005466 return;
5467
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005468 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005469 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005470 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005471
John McCall51313c32010-01-04 23:31:57 +00005472 return;
5473}
5474
David Blaikie9fb1ac52012-05-15 21:57:38 +00005475void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5476 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00005477
5478void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00005479 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00005480 E = E->IgnoreParenImpCasts();
5481
5482 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00005483 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00005484
John McCallb4eb64d2010-10-08 02:01:28 +00005485 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005486 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005487 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00005488 return;
5489}
5490
David Blaikie9fb1ac52012-05-15 21:57:38 +00005491void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5492 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00005493 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00005494
5495 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00005496 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5497 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005498
5499 // If -Wconversion would have warned about either of the candidates
5500 // for a signedness conversion to the context type...
5501 if (!Suspicious) return;
5502
5503 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005504 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5505 CC))
John McCall323ed742010-05-06 08:58:33 +00005506 return;
5507
John McCall323ed742010-05-06 08:58:33 +00005508 // ...then check whether it would have warned about either of the
5509 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00005510 if (E->getType() == T) return;
5511
5512 Suspicious = false;
5513 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5514 E->getType(), CC, &Suspicious);
5515 if (!Suspicious)
5516 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00005517 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005518}
5519
5520/// AnalyzeImplicitConversions - Find and report any interesting
5521/// implicit conversions in the given expression. There are a couple
5522/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005523void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005524 QualType T = OrigE->getType();
5525 Expr *E = OrigE->IgnoreParenImpCasts();
5526
Douglas Gregorf8b6e152011-10-10 17:38:18 +00005527 if (E->isTypeDependent() || E->isValueDependent())
5528 return;
5529
John McCall323ed742010-05-06 08:58:33 +00005530 // For conditional operators, we analyze the arguments as if they
5531 // were being fed directly into the output.
5532 if (isa<ConditionalOperator>(E)) {
5533 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00005534 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00005535 return;
5536 }
5537
Hans Wennborg88617a22012-08-28 15:44:30 +00005538 // Check implicit argument conversions for function calls.
5539 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5540 CheckImplicitArgumentConversions(S, Call, CC);
5541
John McCall323ed742010-05-06 08:58:33 +00005542 // Go ahead and check any implicit conversions we might have skipped.
5543 // The non-canonical typecheck is just an optimization;
5544 // CheckImplicitConversion will filter out dead implicit conversions.
5545 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005546 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00005547
5548 // Now continue drilling into this expression.
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005549
5550 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005551 if (POE->getResultExpr())
5552 E = POE->getResultExpr();
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005553 }
5554
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005555 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5556 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5557
John McCall323ed742010-05-06 08:58:33 +00005558 // Skip past explicit casts.
5559 if (isa<ExplicitCastExpr>(E)) {
5560 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00005561 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005562 }
5563
John McCallbeb22aa2010-11-09 23:24:47 +00005564 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5565 // Do a somewhat different check with comparison operators.
5566 if (BO->isComparisonOp())
5567 return AnalyzeComparison(S, BO);
5568
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005569 // And with simple assignments.
5570 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00005571 return AnalyzeAssignment(S, BO);
5572 }
John McCall323ed742010-05-06 08:58:33 +00005573
5574 // These break the otherwise-useful invariant below. Fortunately,
5575 // we don't really need to recurse into them, because any internal
5576 // expressions should have been analyzed already when they were
5577 // built into statements.
5578 if (isa<StmtExpr>(E)) return;
5579
5580 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005581 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00005582
5583 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00005584 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005585 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5586 bool IsLogicalOperator = BO && BO->isLogicalOp();
5587 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00005588 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00005589 if (!ChildExpr)
5590 continue;
5591
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005592 if (IsLogicalOperator &&
5593 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5594 // Ignore checking string literals that are in logical operators.
5595 continue;
5596 AnalyzeImplicitConversions(S, ChildExpr, CC);
5597 }
John McCall323ed742010-05-06 08:58:33 +00005598}
5599
5600} // end anonymous namespace
5601
5602/// Diagnoses "dangerous" implicit conversions within the given
5603/// expression (which is a full expression). Implements -Wconversion
5604/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005605///
5606/// \param CC the "context" location of the implicit conversion, i.e.
5607/// the most location of the syntactic entity requiring the implicit
5608/// conversion
5609void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005610 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00005611 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00005612 return;
5613
5614 // Don't diagnose for value- or type-dependent expressions.
5615 if (E->isTypeDependent() || E->isValueDependent())
5616 return;
5617
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005618 // Check for array bounds violations in cases where the check isn't triggered
5619 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5620 // ArraySubscriptExpr is on the RHS of a variable initialization.
5621 CheckArrayAccess(E);
5622
John McCallb4eb64d2010-10-08 02:01:28 +00005623 // This is not the right CC for (e.g.) a variable initialization.
5624 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005625}
5626
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005627/// Diagnose when expression is an integer constant expression and its evaluation
5628/// results in integer overflow
5629void Sema::CheckForIntOverflow (Expr *E) {
Richard Smith00043292013-11-05 22:23:30 +00005630 if (isa<BinaryOperator>(E->IgnoreParens()))
5631 E->EvaluateForOverflow(Context);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005632}
5633
Richard Smith6c3af3d2013-01-17 01:17:56 +00005634namespace {
5635/// \brief Visitor for expressions which looks for unsequenced operations on the
5636/// same object.
5637class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smith0c0b3902013-06-30 10:40:20 +00005638 typedef EvaluatedExprVisitor<SequenceChecker> Base;
5639
Richard Smith6c3af3d2013-01-17 01:17:56 +00005640 /// \brief A tree of sequenced regions within an expression. Two regions are
5641 /// unsequenced if one is an ancestor or a descendent of the other. When we
5642 /// finish processing an expression with sequencing, such as a comma
5643 /// expression, we fold its tree nodes into its parent, since they are
5644 /// unsequenced with respect to nodes we will visit later.
5645 class SequenceTree {
5646 struct Value {
5647 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5648 unsigned Parent : 31;
5649 bool Merged : 1;
5650 };
Robert Wilhelme7205c02013-08-10 12:33:24 +00005651 SmallVector<Value, 8> Values;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005652
5653 public:
5654 /// \brief A region within an expression which may be sequenced with respect
5655 /// to some other region.
5656 class Seq {
5657 explicit Seq(unsigned N) : Index(N) {}
5658 unsigned Index;
5659 friend class SequenceTree;
5660 public:
5661 Seq() : Index(0) {}
5662 };
5663
5664 SequenceTree() { Values.push_back(Value(0)); }
5665 Seq root() const { return Seq(0); }
5666
5667 /// \brief Create a new sequence of operations, which is an unsequenced
5668 /// subset of \p Parent. This sequence of operations is sequenced with
5669 /// respect to other children of \p Parent.
5670 Seq allocate(Seq Parent) {
5671 Values.push_back(Value(Parent.Index));
5672 return Seq(Values.size() - 1);
5673 }
5674
5675 /// \brief Merge a sequence of operations into its parent.
5676 void merge(Seq S) {
5677 Values[S.Index].Merged = true;
5678 }
5679
5680 /// \brief Determine whether two operations are unsequenced. This operation
5681 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5682 /// should have been merged into its parent as appropriate.
5683 bool isUnsequenced(Seq Cur, Seq Old) {
5684 unsigned C = representative(Cur.Index);
5685 unsigned Target = representative(Old.Index);
5686 while (C >= Target) {
5687 if (C == Target)
5688 return true;
5689 C = Values[C].Parent;
5690 }
5691 return false;
5692 }
5693
5694 private:
5695 /// \brief Pick a representative for a sequence.
5696 unsigned representative(unsigned K) {
5697 if (Values[K].Merged)
5698 // Perform path compression as we go.
5699 return Values[K].Parent = representative(Values[K].Parent);
5700 return K;
5701 }
5702 };
5703
5704 /// An object for which we can track unsequenced uses.
5705 typedef NamedDecl *Object;
5706
5707 /// Different flavors of object usage which we track. We only track the
5708 /// least-sequenced usage of each kind.
5709 enum UsageKind {
5710 /// A read of an object. Multiple unsequenced reads are OK.
5711 UK_Use,
5712 /// A modification of an object which is sequenced before the value
Richard Smith418dd3e2013-06-26 23:16:51 +00005713 /// computation of the expression, such as ++n in C++.
Richard Smith6c3af3d2013-01-17 01:17:56 +00005714 UK_ModAsValue,
5715 /// A modification of an object which is not sequenced before the value
5716 /// computation of the expression, such as n++.
5717 UK_ModAsSideEffect,
5718
5719 UK_Count = UK_ModAsSideEffect + 1
5720 };
5721
5722 struct Usage {
5723 Usage() : Use(0), Seq() {}
5724 Expr *Use;
5725 SequenceTree::Seq Seq;
5726 };
5727
5728 struct UsageInfo {
5729 UsageInfo() : Diagnosed(false) {}
5730 Usage Uses[UK_Count];
5731 /// Have we issued a diagnostic for this variable already?
5732 bool Diagnosed;
5733 };
5734 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5735
5736 Sema &SemaRef;
5737 /// Sequenced regions within the expression.
5738 SequenceTree Tree;
5739 /// Declaration modifications and references which we have seen.
5740 UsageInfoMap UsageMap;
5741 /// The region we are currently within.
5742 SequenceTree::Seq Region;
5743 /// Filled in with declarations which were modified as a side-effect
5744 /// (that is, post-increment operations).
Robert Wilhelme7205c02013-08-10 12:33:24 +00005745 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smith1a2dcd52013-01-17 23:18:09 +00005746 /// Expressions to check later. We defer checking these to reduce
5747 /// stack usage.
Robert Wilhelme7205c02013-08-10 12:33:24 +00005748 SmallVectorImpl<Expr *> &WorkList;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005749
5750 /// RAII object wrapping the visitation of a sequenced subexpression of an
5751 /// expression. At the end of this process, the side-effects of the evaluation
5752 /// become sequenced with respect to the value computation of the result, so
5753 /// we downgrade any UK_ModAsSideEffect within the evaluation to
5754 /// UK_ModAsValue.
5755 struct SequencedSubexpression {
5756 SequencedSubexpression(SequenceChecker &Self)
5757 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5758 Self.ModAsSideEffect = &ModAsSideEffect;
5759 }
5760 ~SequencedSubexpression() {
5761 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5762 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5763 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5764 Self.addUsage(U, ModAsSideEffect[I].first,
5765 ModAsSideEffect[I].second.Use, UK_ModAsValue);
5766 }
5767 Self.ModAsSideEffect = OldModAsSideEffect;
5768 }
5769
5770 SequenceChecker &Self;
Robert Wilhelme7205c02013-08-10 12:33:24 +00005771 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5772 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005773 };
5774
Richard Smith67470052013-06-20 22:21:56 +00005775 /// RAII object wrapping the visitation of a subexpression which we might
5776 /// choose to evaluate as a constant. If any subexpression is evaluated and
5777 /// found to be non-constant, this allows us to suppress the evaluation of
5778 /// the outer expression.
5779 class EvaluationTracker {
5780 public:
5781 EvaluationTracker(SequenceChecker &Self)
5782 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
5783 Self.EvalTracker = this;
5784 }
5785 ~EvaluationTracker() {
5786 Self.EvalTracker = Prev;
5787 if (Prev)
5788 Prev->EvalOK &= EvalOK;
5789 }
5790
5791 bool evaluate(const Expr *E, bool &Result) {
5792 if (!EvalOK || E->isValueDependent())
5793 return false;
5794 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
5795 return EvalOK;
5796 }
5797
5798 private:
5799 SequenceChecker &Self;
5800 EvaluationTracker *Prev;
5801 bool EvalOK;
5802 } *EvalTracker;
5803
Richard Smith6c3af3d2013-01-17 01:17:56 +00005804 /// \brief Find the object which is produced by the specified expression,
5805 /// if any.
5806 Object getObject(Expr *E, bool Mod) const {
5807 E = E->IgnoreParenCasts();
5808 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5809 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5810 return getObject(UO->getSubExpr(), Mod);
5811 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5812 if (BO->getOpcode() == BO_Comma)
5813 return getObject(BO->getRHS(), Mod);
5814 if (Mod && BO->isAssignmentOp())
5815 return getObject(BO->getLHS(), Mod);
5816 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5817 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5818 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5819 return ME->getMemberDecl();
5820 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5821 // FIXME: If this is a reference, map through to its value.
5822 return DRE->getDecl();
5823 return 0;
5824 }
5825
5826 /// \brief Note that an object was modified or used by an expression.
5827 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5828 Usage &U = UI.Uses[UK];
5829 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5830 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5831 ModAsSideEffect->push_back(std::make_pair(O, U));
5832 U.Use = Ref;
5833 U.Seq = Region;
5834 }
5835 }
5836 /// \brief Check whether a modification or use conflicts with a prior usage.
5837 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5838 bool IsModMod) {
5839 if (UI.Diagnosed)
5840 return;
5841
5842 const Usage &U = UI.Uses[OtherKind];
5843 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5844 return;
5845
5846 Expr *Mod = U.Use;
5847 Expr *ModOrUse = Ref;
5848 if (OtherKind == UK_Use)
5849 std::swap(Mod, ModOrUse);
5850
5851 SemaRef.Diag(Mod->getExprLoc(),
5852 IsModMod ? diag::warn_unsequenced_mod_mod
5853 : diag::warn_unsequenced_mod_use)
5854 << O << SourceRange(ModOrUse->getExprLoc());
5855 UI.Diagnosed = true;
5856 }
5857
5858 void notePreUse(Object O, Expr *Use) {
5859 UsageInfo &U = UsageMap[O];
5860 // Uses conflict with other modifications.
5861 checkUsage(O, U, Use, UK_ModAsValue, false);
5862 }
5863 void notePostUse(Object O, Expr *Use) {
5864 UsageInfo &U = UsageMap[O];
5865 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5866 addUsage(U, O, Use, UK_Use);
5867 }
5868
5869 void notePreMod(Object O, Expr *Mod) {
5870 UsageInfo &U = UsageMap[O];
5871 // Modifications conflict with other modifications and with uses.
5872 checkUsage(O, U, Mod, UK_ModAsValue, true);
5873 checkUsage(O, U, Mod, UK_Use, false);
5874 }
5875 void notePostMod(Object O, Expr *Use, UsageKind UK) {
5876 UsageInfo &U = UsageMap[O];
5877 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5878 addUsage(U, O, Use, UK);
5879 }
5880
5881public:
Robert Wilhelme7205c02013-08-10 12:33:24 +00005882 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
5883 : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
5884 WorkList(WorkList), EvalTracker(0) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005885 Visit(E);
5886 }
5887
5888 void VisitStmt(Stmt *S) {
5889 // Skip all statements which aren't expressions for now.
5890 }
5891
5892 void VisitExpr(Expr *E) {
5893 // By default, just recurse to evaluated subexpressions.
Richard Smith0c0b3902013-06-30 10:40:20 +00005894 Base::VisitStmt(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005895 }
5896
5897 void VisitCastExpr(CastExpr *E) {
5898 Object O = Object();
5899 if (E->getCastKind() == CK_LValueToRValue)
5900 O = getObject(E->getSubExpr(), false);
5901
5902 if (O)
5903 notePreUse(O, E);
5904 VisitExpr(E);
5905 if (O)
5906 notePostUse(O, E);
5907 }
5908
5909 void VisitBinComma(BinaryOperator *BO) {
5910 // C++11 [expr.comma]p1:
5911 // Every value computation and side effect associated with the left
5912 // expression is sequenced before every value computation and side
5913 // effect associated with the right expression.
5914 SequenceTree::Seq LHS = Tree.allocate(Region);
5915 SequenceTree::Seq RHS = Tree.allocate(Region);
5916 SequenceTree::Seq OldRegion = Region;
5917
5918 {
5919 SequencedSubexpression SeqLHS(*this);
5920 Region = LHS;
5921 Visit(BO->getLHS());
5922 }
5923
5924 Region = RHS;
5925 Visit(BO->getRHS());
5926
5927 Region = OldRegion;
5928
5929 // Forget that LHS and RHS are sequenced. They are both unsequenced
5930 // with respect to other stuff.
5931 Tree.merge(LHS);
5932 Tree.merge(RHS);
5933 }
5934
5935 void VisitBinAssign(BinaryOperator *BO) {
5936 // The modification is sequenced after the value computation of the LHS
5937 // and RHS, so check it before inspecting the operands and update the
5938 // map afterwards.
5939 Object O = getObject(BO->getLHS(), true);
5940 if (!O)
5941 return VisitExpr(BO);
5942
5943 notePreMod(O, BO);
5944
5945 // C++11 [expr.ass]p7:
5946 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
5947 // only once.
5948 //
5949 // Therefore, for a compound assignment operator, O is considered used
5950 // everywhere except within the evaluation of E1 itself.
5951 if (isa<CompoundAssignOperator>(BO))
5952 notePreUse(O, BO);
5953
5954 Visit(BO->getLHS());
5955
5956 if (isa<CompoundAssignOperator>(BO))
5957 notePostUse(O, BO);
5958
5959 Visit(BO->getRHS());
5960
Richard Smith418dd3e2013-06-26 23:16:51 +00005961 // C++11 [expr.ass]p1:
5962 // the assignment is sequenced [...] before the value computation of the
5963 // assignment expression.
5964 // C11 6.5.16/3 has no such rule.
5965 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5966 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005967 }
5968 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
5969 VisitBinAssign(CAO);
5970 }
5971
5972 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5973 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5974 void VisitUnaryPreIncDec(UnaryOperator *UO) {
5975 Object O = getObject(UO->getSubExpr(), true);
5976 if (!O)
5977 return VisitExpr(UO);
5978
5979 notePreMod(O, UO);
5980 Visit(UO->getSubExpr());
Richard Smith418dd3e2013-06-26 23:16:51 +00005981 // C++11 [expr.pre.incr]p1:
5982 // the expression ++x is equivalent to x+=1
5983 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5984 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005985 }
5986
5987 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5988 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5989 void VisitUnaryPostIncDec(UnaryOperator *UO) {
5990 Object O = getObject(UO->getSubExpr(), true);
5991 if (!O)
5992 return VisitExpr(UO);
5993
5994 notePreMod(O, UO);
5995 Visit(UO->getSubExpr());
5996 notePostMod(O, UO, UK_ModAsSideEffect);
5997 }
5998
5999 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6000 void VisitBinLOr(BinaryOperator *BO) {
6001 // The side-effects of the LHS of an '&&' are sequenced before the
6002 // value computation of the RHS, and hence before the value computation
6003 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6004 // as if they were unconditionally sequenced.
Richard Smith67470052013-06-20 22:21:56 +00006005 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006006 {
6007 SequencedSubexpression Sequenced(*this);
6008 Visit(BO->getLHS());
6009 }
6010
6011 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00006012 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00006013 if (!Result)
6014 Visit(BO->getRHS());
6015 } else {
6016 // Check for unsequenced operations in the RHS, treating it as an
6017 // entirely separate evaluation.
6018 //
6019 // FIXME: If there are operations in the RHS which are unsequenced
6020 // with respect to operations outside the RHS, and those operations
6021 // are unconditionally evaluated, diagnose them.
Richard Smith1a2dcd52013-01-17 23:18:09 +00006022 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00006023 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006024 }
6025 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith67470052013-06-20 22:21:56 +00006026 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006027 {
6028 SequencedSubexpression Sequenced(*this);
6029 Visit(BO->getLHS());
6030 }
6031
6032 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00006033 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00006034 if (Result)
6035 Visit(BO->getRHS());
6036 } else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00006037 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00006038 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006039 }
6040
6041 // Only visit the condition, unless we can be sure which subexpression will
6042 // be chosen.
6043 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith67470052013-06-20 22:21:56 +00006044 EvaluationTracker Eval(*this);
Richard Smith418dd3e2013-06-26 23:16:51 +00006045 {
6046 SequencedSubexpression Sequenced(*this);
6047 Visit(CO->getCond());
6048 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006049
6050 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00006051 if (Eval.evaluate(CO->getCond(), Result))
Richard Smith6c3af3d2013-01-17 01:17:56 +00006052 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00006053 else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00006054 WorkList.push_back(CO->getTrueExpr());
6055 WorkList.push_back(CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00006056 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006057 }
6058
Richard Smith0c0b3902013-06-30 10:40:20 +00006059 void VisitCallExpr(CallExpr *CE) {
6060 // C++11 [intro.execution]p15:
6061 // When calling a function [...], every value computation and side effect
6062 // associated with any argument expression, or with the postfix expression
6063 // designating the called function, is sequenced before execution of every
6064 // expression or statement in the body of the function [and thus before
6065 // the value computation of its result].
6066 SequencedSubexpression Sequenced(*this);
6067 Base::VisitCallExpr(CE);
6068
6069 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6070 }
6071
Richard Smith6c3af3d2013-01-17 01:17:56 +00006072 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smith0c0b3902013-06-30 10:40:20 +00006073 // This is a call, so all subexpressions are sequenced before the result.
6074 SequencedSubexpression Sequenced(*this);
6075
Richard Smith6c3af3d2013-01-17 01:17:56 +00006076 if (!CCE->isListInitialization())
6077 return VisitExpr(CCE);
6078
6079 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00006080 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00006081 SequenceTree::Seq Parent = Region;
6082 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6083 E = CCE->arg_end();
6084 I != E; ++I) {
6085 Region = Tree.allocate(Parent);
6086 Elts.push_back(Region);
6087 Visit(*I);
6088 }
6089
6090 // Forget that the initializers are sequenced.
6091 Region = Parent;
6092 for (unsigned I = 0; I < Elts.size(); ++I)
6093 Tree.merge(Elts[I]);
6094 }
6095
6096 void VisitInitListExpr(InitListExpr *ILE) {
6097 if (!SemaRef.getLangOpts().CPlusPlus11)
6098 return VisitExpr(ILE);
6099
6100 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00006101 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00006102 SequenceTree::Seq Parent = Region;
6103 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6104 Expr *E = ILE->getInit(I);
6105 if (!E) continue;
6106 Region = Tree.allocate(Parent);
6107 Elts.push_back(Region);
6108 Visit(E);
6109 }
6110
6111 // Forget that the initializers are sequenced.
6112 Region = Parent;
6113 for (unsigned I = 0; I < Elts.size(); ++I)
6114 Tree.merge(Elts[I]);
6115 }
6116};
6117}
6118
6119void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelme7205c02013-08-10 12:33:24 +00006120 SmallVector<Expr *, 8> WorkList;
Richard Smith1a2dcd52013-01-17 23:18:09 +00006121 WorkList.push_back(E);
6122 while (!WorkList.empty()) {
Robert Wilhelm344472e2013-08-23 16:11:15 +00006123 Expr *Item = WorkList.pop_back_val();
Richard Smith1a2dcd52013-01-17 23:18:09 +00006124 SequenceChecker(*this, Item, WorkList);
6125 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006126}
6127
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006128void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6129 bool IsConstexpr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00006130 CheckImplicitConversions(E, CheckLoc);
6131 CheckUnsequencedOperations(E);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006132 if (!IsConstexpr && !E->isValueDependent())
6133 CheckForIntOverflow(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006134}
6135
John McCall15d7d122010-11-11 03:21:53 +00006136void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6137 FieldDecl *BitField,
6138 Expr *Init) {
6139 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6140}
6141
Mike Stumpf8c49212010-01-21 03:59:47 +00006142/// CheckParmsForFunctionDef - Check that the parameters of the given
6143/// function are appropriate for the definition of a function. This
6144/// takes care of any checks that cannot be performed on the
6145/// declaration itself, e.g., that the types of each of the function
6146/// parameters are complete.
Reid Kleckner8c0501c2013-06-24 14:38:26 +00006147bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6148 ParmVarDecl *const *PEnd,
Douglas Gregor82aa7132010-11-01 18:37:59 +00006149 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00006150 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00006151 for (; P != PEnd; ++P) {
6152 ParmVarDecl *Param = *P;
6153
Mike Stumpf8c49212010-01-21 03:59:47 +00006154 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6155 // function declarator that is part of a function definition of
6156 // that function shall not have incomplete type.
6157 //
6158 // This is also C++ [dcl.fct]p6.
6159 if (!Param->isInvalidDecl() &&
6160 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00006161 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00006162 Param->setInvalidDecl();
6163 HasInvalidParm = true;
6164 }
6165
6166 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6167 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00006168 if (CheckParameterNames &&
6169 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00006170 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006171 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00006172 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00006173
6174 // C99 6.7.5.3p12:
6175 // If the function declarator is not part of a definition of that
6176 // function, parameters may have incomplete type and may use the [*]
6177 // notation in their sequences of declarator specifiers to specify
6178 // variable length array types.
6179 QualType PType = Param->getOriginalType();
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006180 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigd17e3402010-02-01 05:02:49 +00006181 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitfc093362013-03-01 21:41:22 +00006182 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00006183 // information is added for it.
6184 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006185 break;
Sam Weinigd17e3402010-02-01 05:02:49 +00006186 }
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006187 PType= AT->getElementType();
Sam Weinigd17e3402010-02-01 05:02:49 +00006188 }
Reid Kleckner9b601952013-06-21 12:45:15 +00006189
6190 // MSVC destroys objects passed by value in the callee. Therefore a
6191 // function definition which takes such a parameter must be able to call the
6192 // object's destructor.
6193 if (getLangOpts().CPlusPlus &&
6194 Context.getTargetInfo().getCXXABI().isArgumentDestroyedByCallee()) {
6195 if (const RecordType *RT = Param->getType()->getAs<RecordType>())
6196 FinalizeVarWithDestructor(Param, RT);
6197 }
Mike Stumpf8c49212010-01-21 03:59:47 +00006198 }
6199
6200 return HasInvalidParm;
6201}
John McCallb7f4ffe2010-08-12 21:44:57 +00006202
6203/// CheckCastAlign - Implements -Wcast-align, which warns when a
6204/// pointer cast increases the alignment requirements.
6205void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6206 // This is actually a lot of work to potentially be doing on every
6207 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00006208 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6209 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00006210 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00006211 return;
6212
6213 // Ignore dependent types.
6214 if (T->isDependentType() || Op->getType()->isDependentType())
6215 return;
6216
6217 // Require that the destination be a pointer type.
6218 const PointerType *DestPtr = T->getAs<PointerType>();
6219 if (!DestPtr) return;
6220
6221 // If the destination has alignment 1, we're done.
6222 QualType DestPointee = DestPtr->getPointeeType();
6223 if (DestPointee->isIncompleteType()) return;
6224 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6225 if (DestAlign.isOne()) return;
6226
6227 // Require that the source be a pointer type.
6228 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6229 if (!SrcPtr) return;
6230 QualType SrcPointee = SrcPtr->getPointeeType();
6231
6232 // Whitelist casts from cv void*. We already implicitly
6233 // whitelisted casts to cv void*, since they have alignment 1.
6234 // Also whitelist casts involving incomplete types, which implicitly
6235 // includes 'void'.
6236 if (SrcPointee->isIncompleteType()) return;
6237
6238 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6239 if (SrcAlign >= DestAlign) return;
6240
6241 Diag(TRange.getBegin(), diag::warn_cast_align)
6242 << Op->getType() << T
6243 << static_cast<unsigned>(SrcAlign.getQuantity())
6244 << static_cast<unsigned>(DestAlign.getQuantity())
6245 << TRange << Op->getSourceRange();
6246}
6247
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006248static const Type* getElementType(const Expr *BaseExpr) {
6249 const Type* EltType = BaseExpr->getType().getTypePtr();
6250 if (EltType->isAnyPointerType())
6251 return EltType->getPointeeType().getTypePtr();
6252 else if (EltType->isArrayType())
6253 return EltType->getBaseElementTypeUnsafe();
6254 return EltType;
6255}
6256
Chandler Carruthc2684342011-08-05 09:10:50 +00006257/// \brief Check whether this array fits the idiom of a size-one tail padded
6258/// array member of a struct.
6259///
6260/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6261/// commonly used to emulate flexible arrays in C89 code.
6262static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6263 const NamedDecl *ND) {
6264 if (Size != 1 || !ND) return false;
6265
6266 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6267 if (!FD) return false;
6268
6269 // Don't consider sizes resulting from macro expansions or template argument
6270 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00006271
6272 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006273 while (TInfo) {
6274 TypeLoc TL = TInfo->getTypeLoc();
6275 // Look through typedefs.
David Blaikie39e6ab42013-02-18 22:06:02 +00006276 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6277 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006278 TInfo = TDL->getTypeSourceInfo();
6279 continue;
6280 }
David Blaikie39e6ab42013-02-18 22:06:02 +00006281 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6282 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier5e253012013-02-06 00:58:34 +00006283 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6284 return false;
6285 }
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006286 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00006287 }
Chandler Carruthc2684342011-08-05 09:10:50 +00006288
6289 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00006290 if (!RD) return false;
6291 if (RD->isUnion()) return false;
6292 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6293 if (!CRD->isStandardLayout()) return false;
6294 }
Chandler Carruthc2684342011-08-05 09:10:50 +00006295
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00006296 // See if this is the last field decl in the record.
6297 const Decl *D = FD;
6298 while ((D = D->getNextDeclInContext()))
6299 if (isa<FieldDecl>(D))
6300 return false;
6301 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00006302}
6303
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006304void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006305 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00006306 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00006307 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006308 if (IndexExpr->isValueDependent())
6309 return;
6310
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00006311 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006312 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00006313 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006314 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00006315 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00006316 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00006317
Chandler Carruth34064582011-02-17 20:55:08 +00006318 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006319 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00006320 return;
Richard Smith25b009a2011-12-16 19:31:14 +00006321 if (IndexNegated)
6322 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00006323
Chandler Carruthba447122011-08-05 08:07:29 +00006324 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00006325 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6326 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00006327 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00006328 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00006329
Ted Kremenek9e060ca2011-02-23 23:06:04 +00006330 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00006331 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00006332 if (!size.isStrictlyPositive())
6333 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006334
6335 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00006336 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006337 // Make sure we're comparing apples to apples when comparing index to size
6338 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6339 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00006340 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00006341 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006342 if (ptrarith_typesize != array_typesize) {
6343 // There's a cast to a different size type involved
6344 uint64_t ratio = array_typesize / ptrarith_typesize;
6345 // TODO: Be smarter about handling cases where array_typesize is not a
6346 // multiple of ptrarith_typesize
6347 if (ptrarith_typesize * ratio == array_typesize)
6348 size *= llvm::APInt(size.getBitWidth(), ratio);
6349 }
6350 }
6351
Chandler Carruth34064582011-02-17 20:55:08 +00006352 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00006353 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00006354 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00006355 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00006356
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006357 // For array subscripting the index must be less than size, but for pointer
6358 // arithmetic also allow the index (offset) to be equal to size since
6359 // computing the next address after the end of the array is legal and
6360 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00006361 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00006362 return;
6363
6364 // Also don't warn for arrays of size 1 which are members of some
6365 // structure. These are often used to approximate flexible arrays in C89
6366 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006367 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00006368 return;
Chandler Carruth34064582011-02-17 20:55:08 +00006369
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006370 // Suppress the warning if the subscript expression (as identified by the
6371 // ']' location) and the index expression are both from macro expansions
6372 // within a system header.
6373 if (ASE) {
6374 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6375 ASE->getRBracketLoc());
6376 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6377 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6378 IndexExpr->getLocStart());
Eli Friedman24146972013-08-22 00:27:10 +00006379 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006380 return;
6381 }
6382 }
6383
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006384 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006385 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006386 DiagID = diag::warn_array_index_exceeds_bounds;
6387
6388 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6389 PDiag(DiagID) << index.toString(10, true)
6390 << size.toString(10, true)
6391 << (unsigned)size.getLimitedValue(~0U)
6392 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00006393 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006394 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006395 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006396 DiagID = diag::warn_ptr_arith_precedes_bounds;
6397 if (index.isNegative()) index = -index;
6398 }
6399
6400 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6401 PDiag(DiagID) << index.toString(10, true)
6402 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006403 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00006404
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00006405 if (!ND) {
6406 // Try harder to find a NamedDecl to point at in the note.
6407 while (const ArraySubscriptExpr *ASE =
6408 dyn_cast<ArraySubscriptExpr>(BaseExpr))
6409 BaseExpr = ASE->getBase()->IgnoreParenCasts();
6410 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6411 ND = dyn_cast<NamedDecl>(DRE->getDecl());
6412 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6413 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6414 }
6415
Chandler Carruth35001ca2011-02-17 21:10:52 +00006416 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006417 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6418 PDiag(diag::note_array_index_out_of_bounds)
6419 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006420}
6421
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006422void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006423 int AllowOnePastEnd = 0;
6424 while (expr) {
6425 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006426 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006427 case Stmt::ArraySubscriptExprClass: {
6428 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006429 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006430 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006431 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006432 }
6433 case Stmt::UnaryOperatorClass: {
6434 // Only unwrap the * and & unary operators
6435 const UnaryOperator *UO = cast<UnaryOperator>(expr);
6436 expr = UO->getSubExpr();
6437 switch (UO->getOpcode()) {
6438 case UO_AddrOf:
6439 AllowOnePastEnd++;
6440 break;
6441 case UO_Deref:
6442 AllowOnePastEnd--;
6443 break;
6444 default:
6445 return;
6446 }
6447 break;
6448 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006449 case Stmt::ConditionalOperatorClass: {
6450 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
6451 if (const Expr *lhs = cond->getLHS())
6452 CheckArrayAccess(lhs);
6453 if (const Expr *rhs = cond->getRHS())
6454 CheckArrayAccess(rhs);
6455 return;
6456 }
6457 default:
6458 return;
6459 }
Peter Collingbournef111d932011-04-15 00:35:48 +00006460 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006461}
John McCallf85e1932011-06-15 23:02:42 +00006462
6463//===--- CHECK: Objective-C retain cycles ----------------------------------//
6464
6465namespace {
6466 struct RetainCycleOwner {
6467 RetainCycleOwner() : Variable(0), Indirect(false) {}
6468 VarDecl *Variable;
6469 SourceRange Range;
6470 SourceLocation Loc;
6471 bool Indirect;
6472
6473 void setLocsFrom(Expr *e) {
6474 Loc = e->getExprLoc();
6475 Range = e->getSourceRange();
6476 }
6477 };
6478}
6479
6480/// Consider whether capturing the given variable can possibly lead to
6481/// a retain cycle.
6482static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00006483 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00006484 // lifetime. In MRR, it's captured strongly if the variable is
6485 // __block and has an appropriate type.
6486 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6487 return false;
6488
6489 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00006490 if (ref)
6491 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00006492 return true;
6493}
6494
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006495static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00006496 while (true) {
6497 e = e->IgnoreParens();
6498 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6499 switch (cast->getCastKind()) {
6500 case CK_BitCast:
6501 case CK_LValueBitCast:
6502 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00006503 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00006504 e = cast->getSubExpr();
6505 continue;
6506
John McCallf85e1932011-06-15 23:02:42 +00006507 default:
6508 return false;
6509 }
6510 }
6511
6512 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6513 ObjCIvarDecl *ivar = ref->getDecl();
6514 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6515 return false;
6516
6517 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006518 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006519 return false;
6520
6521 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6522 owner.Indirect = true;
6523 return true;
6524 }
6525
6526 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6527 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6528 if (!var) return false;
6529 return considerVariable(var, ref, owner);
6530 }
6531
John McCallf85e1932011-06-15 23:02:42 +00006532 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6533 if (member->isArrow()) return false;
6534
6535 // Don't count this as an indirect ownership.
6536 e = member->getBase();
6537 continue;
6538 }
6539
John McCall4b9c2d22011-11-06 09:01:30 +00006540 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6541 // Only pay attention to pseudo-objects on property references.
6542 ObjCPropertyRefExpr *pre
6543 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6544 ->IgnoreParens());
6545 if (!pre) return false;
6546 if (pre->isImplicitProperty()) return false;
6547 ObjCPropertyDecl *property = pre->getExplicitProperty();
6548 if (!property->isRetaining() &&
6549 !(property->getPropertyIvarDecl() &&
6550 property->getPropertyIvarDecl()->getType()
6551 .getObjCLifetime() == Qualifiers::OCL_Strong))
6552 return false;
6553
6554 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006555 if (pre->isSuperReceiver()) {
6556 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6557 if (!owner.Variable)
6558 return false;
6559 owner.Loc = pre->getLocation();
6560 owner.Range = pre->getSourceRange();
6561 return true;
6562 }
John McCall4b9c2d22011-11-06 09:01:30 +00006563 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6564 ->getSourceExpr());
6565 continue;
6566 }
6567
John McCallf85e1932011-06-15 23:02:42 +00006568 // Array ivars?
6569
6570 return false;
6571 }
6572}
6573
6574namespace {
6575 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6576 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6577 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6578 Variable(variable), Capturer(0) {}
6579
6580 VarDecl *Variable;
6581 Expr *Capturer;
6582
6583 void VisitDeclRefExpr(DeclRefExpr *ref) {
6584 if (ref->getDecl() == Variable && !Capturer)
6585 Capturer = ref;
6586 }
6587
John McCallf85e1932011-06-15 23:02:42 +00006588 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6589 if (Capturer) return;
6590 Visit(ref->getBase());
6591 if (Capturer && ref->isFreeIvar())
6592 Capturer = ref;
6593 }
6594
6595 void VisitBlockExpr(BlockExpr *block) {
6596 // Look inside nested blocks
6597 if (block->getBlockDecl()->capturesVariable(Variable))
6598 Visit(block->getBlockDecl()->getBody());
6599 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00006600
6601 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6602 if (Capturer) return;
6603 if (OVE->getSourceExpr())
6604 Visit(OVE->getSourceExpr());
6605 }
John McCallf85e1932011-06-15 23:02:42 +00006606 };
6607}
6608
6609/// Check whether the given argument is a block which captures a
6610/// variable.
6611static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6612 assert(owner.Variable && owner.Loc.isValid());
6613
6614 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00006615
6616 // Look through [^{...} copy] and Block_copy(^{...}).
6617 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6618 Selector Cmd = ME->getSelector();
6619 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6620 e = ME->getInstanceReceiver();
6621 if (!e)
6622 return 0;
6623 e = e->IgnoreParenCasts();
6624 }
6625 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6626 if (CE->getNumArgs() == 1) {
6627 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00006628 if (Fn) {
6629 const IdentifierInfo *FnI = Fn->getIdentifier();
6630 if (FnI && FnI->isStr("_Block_copy")) {
6631 e = CE->getArg(0)->IgnoreParenCasts();
6632 }
6633 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00006634 }
6635 }
6636
John McCallf85e1932011-06-15 23:02:42 +00006637 BlockExpr *block = dyn_cast<BlockExpr>(e);
6638 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6639 return 0;
6640
6641 FindCaptureVisitor visitor(S.Context, owner.Variable);
6642 visitor.Visit(block->getBlockDecl()->getBody());
6643 return visitor.Capturer;
6644}
6645
6646static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6647 RetainCycleOwner &owner) {
6648 assert(capturer);
6649 assert(owner.Variable && owner.Loc.isValid());
6650
6651 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6652 << owner.Variable << capturer->getSourceRange();
6653 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6654 << owner.Indirect << owner.Range;
6655}
6656
6657/// Check for a keyword selector that starts with the word 'add' or
6658/// 'set'.
6659static bool isSetterLikeSelector(Selector sel) {
6660 if (sel.isUnarySelector()) return false;
6661
Chris Lattner5f9e2722011-07-23 10:55:15 +00006662 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00006663 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006664 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00006665 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006666 else if (str.startswith("add")) {
6667 // Specially whitelist 'addOperationWithBlock:'.
6668 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6669 return false;
6670 str = str.substr(3);
6671 }
John McCallf85e1932011-06-15 23:02:42 +00006672 else
6673 return false;
6674
6675 if (str.empty()) return true;
Jordan Rose3f6f51e2013-02-08 22:30:41 +00006676 return !isLowercase(str.front());
John McCallf85e1932011-06-15 23:02:42 +00006677}
6678
6679/// Check a message send to see if it's likely to cause a retain cycle.
6680void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6681 // Only check instance methods whose selector looks like a setter.
6682 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6683 return;
6684
6685 // Try to find a variable that the receiver is strongly owned by.
6686 RetainCycleOwner owner;
6687 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006688 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006689 return;
6690 } else {
6691 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6692 owner.Variable = getCurMethodDecl()->getSelfDecl();
6693 owner.Loc = msg->getSuperLoc();
6694 owner.Range = msg->getSuperLoc();
6695 }
6696
6697 // Check whether the receiver is captured by any of the arguments.
6698 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6699 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6700 return diagnoseRetainCycle(*this, capturer, owner);
6701}
6702
6703/// Check a property assign to see if it's likely to cause a retain cycle.
6704void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6705 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006706 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00006707 return;
6708
6709 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6710 diagnoseRetainCycle(*this, capturer, owner);
6711}
6712
Jordan Rosee10f4d32012-09-15 02:48:31 +00006713void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6714 RetainCycleOwner Owner;
6715 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6716 return;
6717
6718 // Because we don't have an expression for the variable, we have to set the
6719 // location explicitly here.
6720 Owner.Loc = Var->getLocation();
6721 Owner.Range = Var->getSourceRange();
6722
6723 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6724 diagnoseRetainCycle(*this, Capturer, Owner);
6725}
6726
Ted Kremenek9d084012012-12-21 08:04:28 +00006727static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6728 Expr *RHS, bool isProperty) {
6729 // Check if RHS is an Objective-C object literal, which also can get
6730 // immediately zapped in a weak reference. Note that we explicitly
6731 // allow ObjCStringLiterals, since those are designed to never really die.
6732 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006733
Ted Kremenekd3292c82012-12-21 22:46:35 +00006734 // This enum needs to match with the 'select' in
6735 // warn_objc_arc_literal_assign (off-by-1).
6736 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6737 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6738 return false;
Ted Kremenekf530ff72012-12-21 21:59:39 +00006739
6740 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenekd3292c82012-12-21 22:46:35 +00006741 << (unsigned) Kind
Ted Kremenek9d084012012-12-21 08:04:28 +00006742 << (isProperty ? 0 : 1)
6743 << RHS->getSourceRange();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006744
6745 return true;
Ted Kremenek9d084012012-12-21 08:04:28 +00006746}
6747
Ted Kremenekb29b30f2012-12-21 19:45:30 +00006748static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6749 Qualifiers::ObjCLifetime LT,
6750 Expr *RHS, bool isProperty) {
6751 // Strip off any implicit cast added to get to the one ARC-specific.
6752 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6753 if (cast->getCastKind() == CK_ARCConsumeObject) {
6754 S.Diag(Loc, diag::warn_arc_retained_assign)
6755 << (LT == Qualifiers::OCL_ExplicitNone)
6756 << (isProperty ? 0 : 1)
6757 << RHS->getSourceRange();
6758 return true;
6759 }
6760 RHS = cast->getSubExpr();
6761 }
6762
6763 if (LT == Qualifiers::OCL_Weak &&
6764 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6765 return true;
6766
6767 return false;
6768}
6769
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006770bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6771 QualType LHS, Expr *RHS) {
6772 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6773
6774 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6775 return false;
6776
6777 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6778 return true;
6779
6780 return false;
6781}
6782
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006783void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6784 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006785 QualType LHSType;
6786 // PropertyRef on LHS type need be directly obtained from
6787 // its declaration as it has a PsuedoType.
6788 ObjCPropertyRefExpr *PRE
6789 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6790 if (PRE && !PRE->isImplicitProperty()) {
6791 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6792 if (PD)
6793 LHSType = PD->getType();
6794 }
6795
6796 if (LHSType.isNull())
6797 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00006798
6799 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6800
6801 if (LT == Qualifiers::OCL_Weak) {
6802 DiagnosticsEngine::Level Level =
6803 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6804 if (Level != DiagnosticsEngine::Ignored)
6805 getCurFunction()->markSafeWeakUse(LHS);
6806 }
6807
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006808 if (checkUnsafeAssigns(Loc, LHSType, RHS))
6809 return;
Jordan Rose7a270482012-09-28 22:21:35 +00006810
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006811 // FIXME. Check for other life times.
6812 if (LT != Qualifiers::OCL_None)
6813 return;
6814
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006815 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006816 if (PRE->isImplicitProperty())
6817 return;
6818 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6819 if (!PD)
6820 return;
6821
Bill Wendlingad017fa2012-12-20 19:22:21 +00006822 unsigned Attributes = PD->getPropertyAttributes();
6823 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006824 // when 'assign' attribute was not explicitly specified
6825 // by user, ignore it and rely on property type itself
6826 // for lifetime info.
6827 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6828 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6829 LHSType->isObjCRetainableType())
6830 return;
6831
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006832 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00006833 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006834 Diag(Loc, diag::warn_arc_retained_property_assign)
6835 << RHS->getSourceRange();
6836 return;
6837 }
6838 RHS = cast->getSubExpr();
6839 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006840 }
Bill Wendlingad017fa2012-12-20 19:22:21 +00006841 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006842 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6843 return;
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00006844 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006845 }
6846}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00006847
6848//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6849
6850namespace {
6851bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6852 SourceLocation StmtLoc,
6853 const NullStmt *Body) {
6854 // Do not warn if the body is a macro that expands to nothing, e.g:
6855 //
6856 // #define CALL(x)
6857 // if (condition)
6858 // CALL(0);
6859 //
6860 if (Body->hasLeadingEmptyMacro())
6861 return false;
6862
6863 // Get line numbers of statement and body.
6864 bool StmtLineInvalid;
6865 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6866 &StmtLineInvalid);
6867 if (StmtLineInvalid)
6868 return false;
6869
6870 bool BodyLineInvalid;
6871 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
6872 &BodyLineInvalid);
6873 if (BodyLineInvalid)
6874 return false;
6875
6876 // Warn if null statement and body are on the same line.
6877 if (StmtLine != BodyLine)
6878 return false;
6879
6880 return true;
6881}
6882} // Unnamed namespace
6883
6884void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
6885 const Stmt *Body,
6886 unsigned DiagID) {
6887 // Since this is a syntactic check, don't emit diagnostic for template
6888 // instantiations, this just adds noise.
6889 if (CurrentInstantiationScope)
6890 return;
6891
6892 // The body should be a null statement.
6893 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6894 if (!NBody)
6895 return;
6896
6897 // Do the usual checks.
6898 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6899 return;
6900
6901 Diag(NBody->getSemiLoc(), DiagID);
6902 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6903}
6904
6905void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
6906 const Stmt *PossibleBody) {
6907 assert(!CurrentInstantiationScope); // Ensured by caller
6908
6909 SourceLocation StmtLoc;
6910 const Stmt *Body;
6911 unsigned DiagID;
6912 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
6913 StmtLoc = FS->getRParenLoc();
6914 Body = FS->getBody();
6915 DiagID = diag::warn_empty_for_body;
6916 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
6917 StmtLoc = WS->getCond()->getSourceRange().getEnd();
6918 Body = WS->getBody();
6919 DiagID = diag::warn_empty_while_body;
6920 } else
6921 return; // Neither `for' nor `while'.
6922
6923 // The body should be a null statement.
6924 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6925 if (!NBody)
6926 return;
6927
6928 // Skip expensive checks if diagnostic is disabled.
6929 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
6930 DiagnosticsEngine::Ignored)
6931 return;
6932
6933 // Do the usual checks.
6934 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6935 return;
6936
6937 // `for(...);' and `while(...);' are popular idioms, so in order to keep
6938 // noise level low, emit diagnostics only if for/while is followed by a
6939 // CompoundStmt, e.g.:
6940 // for (int i = 0; i < n; i++);
6941 // {
6942 // a(i);
6943 // }
6944 // or if for/while is followed by a statement with more indentation
6945 // than for/while itself:
6946 // for (int i = 0; i < n; i++);
6947 // a(i);
6948 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
6949 if (!ProbableTypo) {
6950 bool BodyColInvalid;
6951 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
6952 PossibleBody->getLocStart(),
6953 &BodyColInvalid);
6954 if (BodyColInvalid)
6955 return;
6956
6957 bool StmtColInvalid;
6958 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
6959 S->getLocStart(),
6960 &StmtColInvalid);
6961 if (StmtColInvalid)
6962 return;
6963
6964 if (BodyCol > StmtCol)
6965 ProbableTypo = true;
6966 }
6967
6968 if (ProbableTypo) {
6969 Diag(NBody->getSemiLoc(), DiagID);
6970 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6971 }
6972}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006973
6974//===--- Layout compatibility ----------------------------------------------//
6975
6976namespace {
6977
6978bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
6979
6980/// \brief Check if two enumeration types are layout-compatible.
6981bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
6982 // C++11 [dcl.enum] p8:
6983 // Two enumeration types are layout-compatible if they have the same
6984 // underlying type.
6985 return ED1->isComplete() && ED2->isComplete() &&
6986 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
6987}
6988
6989/// \brief Check if two fields are layout-compatible.
6990bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
6991 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
6992 return false;
6993
6994 if (Field1->isBitField() != Field2->isBitField())
6995 return false;
6996
6997 if (Field1->isBitField()) {
6998 // Make sure that the bit-fields are the same length.
6999 unsigned Bits1 = Field1->getBitWidthValue(C);
7000 unsigned Bits2 = Field2->getBitWidthValue(C);
7001
7002 if (Bits1 != Bits2)
7003 return false;
7004 }
7005
7006 return true;
7007}
7008
7009/// \brief Check if two standard-layout structs are layout-compatible.
7010/// (C++11 [class.mem] p17)
7011bool isLayoutCompatibleStruct(ASTContext &C,
7012 RecordDecl *RD1,
7013 RecordDecl *RD2) {
7014 // If both records are C++ classes, check that base classes match.
7015 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7016 // If one of records is a CXXRecordDecl we are in C++ mode,
7017 // thus the other one is a CXXRecordDecl, too.
7018 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7019 // Check number of base classes.
7020 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7021 return false;
7022
7023 // Check the base classes.
7024 for (CXXRecordDecl::base_class_const_iterator
7025 Base1 = D1CXX->bases_begin(),
7026 BaseEnd1 = D1CXX->bases_end(),
7027 Base2 = D2CXX->bases_begin();
7028 Base1 != BaseEnd1;
7029 ++Base1, ++Base2) {
7030 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7031 return false;
7032 }
7033 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7034 // If only RD2 is a C++ class, it should have zero base classes.
7035 if (D2CXX->getNumBases() > 0)
7036 return false;
7037 }
7038
7039 // Check the fields.
7040 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7041 Field2End = RD2->field_end(),
7042 Field1 = RD1->field_begin(),
7043 Field1End = RD1->field_end();
7044 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7045 if (!isLayoutCompatible(C, *Field1, *Field2))
7046 return false;
7047 }
7048 if (Field1 != Field1End || Field2 != Field2End)
7049 return false;
7050
7051 return true;
7052}
7053
7054/// \brief Check if two standard-layout unions are layout-compatible.
7055/// (C++11 [class.mem] p18)
7056bool isLayoutCompatibleUnion(ASTContext &C,
7057 RecordDecl *RD1,
7058 RecordDecl *RD2) {
7059 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
7060 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
7061 Field2End = RD2->field_end();
7062 Field2 != Field2End; ++Field2) {
7063 UnmatchedFields.insert(*Field2);
7064 }
7065
7066 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
7067 Field1End = RD1->field_end();
7068 Field1 != Field1End; ++Field1) {
7069 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7070 I = UnmatchedFields.begin(),
7071 E = UnmatchedFields.end();
7072
7073 for ( ; I != E; ++I) {
7074 if (isLayoutCompatible(C, *Field1, *I)) {
7075 bool Result = UnmatchedFields.erase(*I);
7076 (void) Result;
7077 assert(Result);
7078 break;
7079 }
7080 }
7081 if (I == E)
7082 return false;
7083 }
7084
7085 return UnmatchedFields.empty();
7086}
7087
7088bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7089 if (RD1->isUnion() != RD2->isUnion())
7090 return false;
7091
7092 if (RD1->isUnion())
7093 return isLayoutCompatibleUnion(C, RD1, RD2);
7094 else
7095 return isLayoutCompatibleStruct(C, RD1, RD2);
7096}
7097
7098/// \brief Check if two types are layout-compatible in C++11 sense.
7099bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7100 if (T1.isNull() || T2.isNull())
7101 return false;
7102
7103 // C++11 [basic.types] p11:
7104 // If two types T1 and T2 are the same type, then T1 and T2 are
7105 // layout-compatible types.
7106 if (C.hasSameType(T1, T2))
7107 return true;
7108
7109 T1 = T1.getCanonicalType().getUnqualifiedType();
7110 T2 = T2.getCanonicalType().getUnqualifiedType();
7111
7112 const Type::TypeClass TC1 = T1->getTypeClass();
7113 const Type::TypeClass TC2 = T2->getTypeClass();
7114
7115 if (TC1 != TC2)
7116 return false;
7117
7118 if (TC1 == Type::Enum) {
7119 return isLayoutCompatible(C,
7120 cast<EnumType>(T1)->getDecl(),
7121 cast<EnumType>(T2)->getDecl());
7122 } else if (TC1 == Type::Record) {
7123 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7124 return false;
7125
7126 return isLayoutCompatible(C,
7127 cast<RecordType>(T1)->getDecl(),
7128 cast<RecordType>(T2)->getDecl());
7129 }
7130
7131 return false;
7132}
7133}
7134
7135//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7136
7137namespace {
7138/// \brief Given a type tag expression find the type tag itself.
7139///
7140/// \param TypeExpr Type tag expression, as it appears in user's code.
7141///
7142/// \param VD Declaration of an identifier that appears in a type tag.
7143///
7144/// \param MagicValue Type tag magic value.
7145bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7146 const ValueDecl **VD, uint64_t *MagicValue) {
7147 while(true) {
7148 if (!TypeExpr)
7149 return false;
7150
7151 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7152
7153 switch (TypeExpr->getStmtClass()) {
7154 case Stmt::UnaryOperatorClass: {
7155 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7156 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7157 TypeExpr = UO->getSubExpr();
7158 continue;
7159 }
7160 return false;
7161 }
7162
7163 case Stmt::DeclRefExprClass: {
7164 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7165 *VD = DRE->getDecl();
7166 return true;
7167 }
7168
7169 case Stmt::IntegerLiteralClass: {
7170 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7171 llvm::APInt MagicValueAPInt = IL->getValue();
7172 if (MagicValueAPInt.getActiveBits() <= 64) {
7173 *MagicValue = MagicValueAPInt.getZExtValue();
7174 return true;
7175 } else
7176 return false;
7177 }
7178
7179 case Stmt::BinaryConditionalOperatorClass:
7180 case Stmt::ConditionalOperatorClass: {
7181 const AbstractConditionalOperator *ACO =
7182 cast<AbstractConditionalOperator>(TypeExpr);
7183 bool Result;
7184 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7185 if (Result)
7186 TypeExpr = ACO->getTrueExpr();
7187 else
7188 TypeExpr = ACO->getFalseExpr();
7189 continue;
7190 }
7191 return false;
7192 }
7193
7194 case Stmt::BinaryOperatorClass: {
7195 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7196 if (BO->getOpcode() == BO_Comma) {
7197 TypeExpr = BO->getRHS();
7198 continue;
7199 }
7200 return false;
7201 }
7202
7203 default:
7204 return false;
7205 }
7206 }
7207}
7208
7209/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7210///
7211/// \param TypeExpr Expression that specifies a type tag.
7212///
7213/// \param MagicValues Registered magic values.
7214///
7215/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7216/// kind.
7217///
7218/// \param TypeInfo Information about the corresponding C type.
7219///
7220/// \returns true if the corresponding C type was found.
7221bool GetMatchingCType(
7222 const IdentifierInfo *ArgumentKind,
7223 const Expr *TypeExpr, const ASTContext &Ctx,
7224 const llvm::DenseMap<Sema::TypeTagMagicValue,
7225 Sema::TypeTagData> *MagicValues,
7226 bool &FoundWrongKind,
7227 Sema::TypeTagData &TypeInfo) {
7228 FoundWrongKind = false;
7229
7230 // Variable declaration that has type_tag_for_datatype attribute.
7231 const ValueDecl *VD = NULL;
7232
7233 uint64_t MagicValue;
7234
7235 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7236 return false;
7237
7238 if (VD) {
7239 for (specific_attr_iterator<TypeTagForDatatypeAttr>
7240 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
7241 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
7242 I != E; ++I) {
7243 if (I->getArgumentKind() != ArgumentKind) {
7244 FoundWrongKind = true;
7245 return false;
7246 }
7247 TypeInfo.Type = I->getMatchingCType();
7248 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7249 TypeInfo.MustBeNull = I->getMustBeNull();
7250 return true;
7251 }
7252 return false;
7253 }
7254
7255 if (!MagicValues)
7256 return false;
7257
7258 llvm::DenseMap<Sema::TypeTagMagicValue,
7259 Sema::TypeTagData>::const_iterator I =
7260 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7261 if (I == MagicValues->end())
7262 return false;
7263
7264 TypeInfo = I->second;
7265 return true;
7266}
7267} // unnamed namespace
7268
7269void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7270 uint64_t MagicValue, QualType Type,
7271 bool LayoutCompatible,
7272 bool MustBeNull) {
7273 if (!TypeTagForDatatypeMagicValues)
7274 TypeTagForDatatypeMagicValues.reset(
7275 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7276
7277 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7278 (*TypeTagForDatatypeMagicValues)[Magic] =
7279 TypeTagData(Type, LayoutCompatible, MustBeNull);
7280}
7281
7282namespace {
7283bool IsSameCharType(QualType T1, QualType T2) {
7284 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7285 if (!BT1)
7286 return false;
7287
7288 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7289 if (!BT2)
7290 return false;
7291
7292 BuiltinType::Kind T1Kind = BT1->getKind();
7293 BuiltinType::Kind T2Kind = BT2->getKind();
7294
7295 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
7296 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
7297 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7298 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7299}
7300} // unnamed namespace
7301
7302void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7303 const Expr * const *ExprArgs) {
7304 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7305 bool IsPointerAttr = Attr->getIsPointer();
7306
7307 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7308 bool FoundWrongKind;
7309 TypeTagData TypeInfo;
7310 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7311 TypeTagForDatatypeMagicValues.get(),
7312 FoundWrongKind, TypeInfo)) {
7313 if (FoundWrongKind)
7314 Diag(TypeTagExpr->getExprLoc(),
7315 diag::warn_type_tag_for_datatype_wrong_kind)
7316 << TypeTagExpr->getSourceRange();
7317 return;
7318 }
7319
7320 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7321 if (IsPointerAttr) {
7322 // Skip implicit cast of pointer to `void *' (as a function argument).
7323 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5a249802012-11-03 16:07:49 +00007324 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkob57ce4e2012-11-03 22:10:18 +00007325 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00007326 ArgumentExpr = ICE->getSubExpr();
7327 }
7328 QualType ArgumentType = ArgumentExpr->getType();
7329
7330 // Passing a `void*' pointer shouldn't trigger a warning.
7331 if (IsPointerAttr && ArgumentType->isVoidPointerType())
7332 return;
7333
7334 if (TypeInfo.MustBeNull) {
7335 // Type tag with matching void type requires a null pointer.
7336 if (!ArgumentExpr->isNullPointerConstant(Context,
7337 Expr::NPC_ValueDependentIsNotNull)) {
7338 Diag(ArgumentExpr->getExprLoc(),
7339 diag::warn_type_safety_null_pointer_required)
7340 << ArgumentKind->getName()
7341 << ArgumentExpr->getSourceRange()
7342 << TypeTagExpr->getSourceRange();
7343 }
7344 return;
7345 }
7346
7347 QualType RequiredType = TypeInfo.Type;
7348 if (IsPointerAttr)
7349 RequiredType = Context.getPointerType(RequiredType);
7350
7351 bool mismatch = false;
7352 if (!TypeInfo.LayoutCompatible) {
7353 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7354
7355 // C++11 [basic.fundamental] p1:
7356 // Plain char, signed char, and unsigned char are three distinct types.
7357 //
7358 // But we treat plain `char' as equivalent to `signed char' or `unsigned
7359 // char' depending on the current char signedness mode.
7360 if (mismatch)
7361 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7362 RequiredType->getPointeeType())) ||
7363 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7364 mismatch = false;
7365 } else
7366 if (IsPointerAttr)
7367 mismatch = !isLayoutCompatible(Context,
7368 ArgumentType->getPointeeType(),
7369 RequiredType->getPointeeType());
7370 else
7371 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7372
7373 if (mismatch)
7374 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
7375 << ArgumentType << ArgumentKind->getName()
7376 << TypeInfo.LayoutCompatible << RequiredType
7377 << ArgumentExpr->getSourceRange()
7378 << TypeTagExpr->getSourceRange();
7379}