blob: f58396f14bf9b4ec2f99b88eb105a95998f5e574 [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/DeclObjC.h"
21#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikiebe0ee872012-05-15 16:56:36 +000022#include "clang/AST/Expr.h"
Ted Kremenek23245122007-08-20 16:18:38 +000023#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000024#include "clang/AST/ExprObjC.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000025#include "clang/AST/StmtCXX.h"
26#include "clang/AST/StmtObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000027#include "clang/Analysis/Analyses/FormatString.h"
28#include "clang/Basic/ConvertUTF.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000029#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000030#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "clang/Lex/Preprocessor.h"
32#include "clang/Sema/Initialization.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/ScopeInfo.h"
36#include "clang/Sema/Sema.h"
37#include "llvm/ADT/BitVector.h"
38#include "llvm/ADT/STLExtras.h"
39#include "llvm/ADT/SmallString.h"
40#include "llvm/Support/raw_ostream.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000041#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000042using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000043using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000044
Chris Lattner60800082009-02-18 17:49:48 +000045SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
46 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000047 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +000048 PP.getLangOpts(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000049}
50
John McCall8e10f3b2011-02-26 05:39:39 +000051/// Checks that a call expression's argument count is the desired number.
52/// This is useful when doing custom type-checking. Returns true on error.
53static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
54 unsigned argCount = call->getNumArgs();
55 if (argCount == desiredArgCount) return false;
56
57 if (argCount < desiredArgCount)
58 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
59 << 0 /*function call*/ << desiredArgCount << argCount
60 << call->getSourceRange();
61
62 // Highlight all the excess arguments.
63 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
64 call->getArg(argCount - 1)->getLocEnd());
65
66 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
67 << 0 /*function call*/ << desiredArgCount << argCount
68 << call->getArg(1)->getSourceRange();
69}
70
Julien Lerougee5939212012-04-28 17:39:16 +000071/// Check that the first argument to __builtin_annotation is an integer
72/// and the second argument is a non-wide string literal.
73static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
74 if (checkArgCount(S, TheCall, 2))
75 return true;
76
77 // First argument should be an integer.
78 Expr *ValArg = TheCall->getArg(0);
79 QualType Ty = ValArg->getType();
80 if (!Ty->isIntegerType()) {
81 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
82 << ValArg->getSourceRange();
Julien Lerouge77f68bb2011-09-09 22:41:49 +000083 return true;
84 }
Julien Lerougee5939212012-04-28 17:39:16 +000085
86 // Second argument should be a constant string.
87 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
88 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
89 if (!Literal || !Literal->isAscii()) {
90 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
91 << StrArg->getSourceRange();
92 return true;
93 }
94
95 TheCall->setType(Ty);
Julien Lerouge77f68bb2011-09-09 22:41:49 +000096 return false;
97}
98
John McCall60d7b3a2010-08-24 06:29:42 +000099ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000100Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +0000101 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000102
Chris Lattner946928f2010-10-01 23:23:24 +0000103 // Find out if any arguments are required to be integer constant expressions.
104 unsigned ICEArguments = 0;
105 ASTContext::GetBuiltinTypeError Error;
106 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
107 if (Error != ASTContext::GE_None)
108 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
109
110 // If any arguments are required to be ICE's, check and diagnose.
111 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
112 // Skip arguments not required to be ICE's.
113 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
114
115 llvm::APSInt Result;
116 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
117 return true;
118 ICEArguments &= ~(1 << ArgNo);
119 }
120
Anders Carlssond406bf02009-08-16 01:56:34 +0000121 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000122 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000123 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000124 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000125 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000126 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000127 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000128 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000129 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000130 if (SemaBuiltinVAStart(TheCall))
131 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000132 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000133 case Builtin::BI__builtin_isgreater:
134 case Builtin::BI__builtin_isgreaterequal:
135 case Builtin::BI__builtin_isless:
136 case Builtin::BI__builtin_islessequal:
137 case Builtin::BI__builtin_islessgreater:
138 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000139 if (SemaBuiltinUnorderedCompare(TheCall))
140 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000141 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000142 case Builtin::BI__builtin_fpclassify:
143 if (SemaBuiltinFPClassification(TheCall, 6))
144 return ExprError();
145 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000146 case Builtin::BI__builtin_isfinite:
147 case Builtin::BI__builtin_isinf:
148 case Builtin::BI__builtin_isinf_sign:
149 case Builtin::BI__builtin_isnan:
150 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000151 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000152 return ExprError();
153 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000154 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000155 return SemaBuiltinShuffleVector(TheCall);
156 // TheCall will be freed by the smart pointer here, but that's fine, since
157 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000158 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000159 if (SemaBuiltinPrefetch(TheCall))
160 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000161 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000162 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000163 if (SemaBuiltinObjectSize(TheCall))
164 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000165 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000166 case Builtin::BI__builtin_longjmp:
167 if (SemaBuiltinLongjmp(TheCall))
168 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000169 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000170
171 case Builtin::BI__builtin_classify_type:
172 if (checkArgCount(*this, TheCall, 1)) return true;
173 TheCall->setType(Context.IntTy);
174 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000175 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000176 if (checkArgCount(*this, TheCall, 1)) return true;
177 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000178 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000179 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000180 case Builtin::BI__sync_fetch_and_add_1:
181 case Builtin::BI__sync_fetch_and_add_2:
182 case Builtin::BI__sync_fetch_and_add_4:
183 case Builtin::BI__sync_fetch_and_add_8:
184 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000185 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000186 case Builtin::BI__sync_fetch_and_sub_1:
187 case Builtin::BI__sync_fetch_and_sub_2:
188 case Builtin::BI__sync_fetch_and_sub_4:
189 case Builtin::BI__sync_fetch_and_sub_8:
190 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000191 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000192 case Builtin::BI__sync_fetch_and_or_1:
193 case Builtin::BI__sync_fetch_and_or_2:
194 case Builtin::BI__sync_fetch_and_or_4:
195 case Builtin::BI__sync_fetch_and_or_8:
196 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000197 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000198 case Builtin::BI__sync_fetch_and_and_1:
199 case Builtin::BI__sync_fetch_and_and_2:
200 case Builtin::BI__sync_fetch_and_and_4:
201 case Builtin::BI__sync_fetch_and_and_8:
202 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000203 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000204 case Builtin::BI__sync_fetch_and_xor_1:
205 case Builtin::BI__sync_fetch_and_xor_2:
206 case Builtin::BI__sync_fetch_and_xor_4:
207 case Builtin::BI__sync_fetch_and_xor_8:
208 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000209 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000210 case Builtin::BI__sync_add_and_fetch_1:
211 case Builtin::BI__sync_add_and_fetch_2:
212 case Builtin::BI__sync_add_and_fetch_4:
213 case Builtin::BI__sync_add_and_fetch_8:
214 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000215 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000216 case Builtin::BI__sync_sub_and_fetch_1:
217 case Builtin::BI__sync_sub_and_fetch_2:
218 case Builtin::BI__sync_sub_and_fetch_4:
219 case Builtin::BI__sync_sub_and_fetch_8:
220 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000221 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000222 case Builtin::BI__sync_and_and_fetch_1:
223 case Builtin::BI__sync_and_and_fetch_2:
224 case Builtin::BI__sync_and_and_fetch_4:
225 case Builtin::BI__sync_and_and_fetch_8:
226 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000227 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000228 case Builtin::BI__sync_or_and_fetch_1:
229 case Builtin::BI__sync_or_and_fetch_2:
230 case Builtin::BI__sync_or_and_fetch_4:
231 case Builtin::BI__sync_or_and_fetch_8:
232 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000233 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000234 case Builtin::BI__sync_xor_and_fetch_1:
235 case Builtin::BI__sync_xor_and_fetch_2:
236 case Builtin::BI__sync_xor_and_fetch_4:
237 case Builtin::BI__sync_xor_and_fetch_8:
238 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000239 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000240 case Builtin::BI__sync_val_compare_and_swap_1:
241 case Builtin::BI__sync_val_compare_and_swap_2:
242 case Builtin::BI__sync_val_compare_and_swap_4:
243 case Builtin::BI__sync_val_compare_and_swap_8:
244 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000245 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000246 case Builtin::BI__sync_bool_compare_and_swap_1:
247 case Builtin::BI__sync_bool_compare_and_swap_2:
248 case Builtin::BI__sync_bool_compare_and_swap_4:
249 case Builtin::BI__sync_bool_compare_and_swap_8:
250 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000251 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000252 case Builtin::BI__sync_lock_test_and_set_1:
253 case Builtin::BI__sync_lock_test_and_set_2:
254 case Builtin::BI__sync_lock_test_and_set_4:
255 case Builtin::BI__sync_lock_test_and_set_8:
256 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000257 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000258 case Builtin::BI__sync_lock_release_1:
259 case Builtin::BI__sync_lock_release_2:
260 case Builtin::BI__sync_lock_release_4:
261 case Builtin::BI__sync_lock_release_8:
262 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000263 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000264 case Builtin::BI__sync_swap_1:
265 case Builtin::BI__sync_swap_2:
266 case Builtin::BI__sync_swap_4:
267 case Builtin::BI__sync_swap_8:
268 case Builtin::BI__sync_swap_16:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000269 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithff34d402012-04-12 05:08:17 +0000270#define BUILTIN(ID, TYPE, ATTRS)
271#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
272 case Builtin::BI##ID: \
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000273 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithff34d402012-04-12 05:08:17 +0000274#include "clang/Basic/Builtins.def"
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000275 case Builtin::BI__builtin_annotation:
Julien Lerougee5939212012-04-28 17:39:16 +0000276 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000277 return ExprError();
278 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000279 }
280
281 // Since the target specific builtins for each arch overlap, only check those
282 // of the arch we are compiling for.
283 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000284 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000285 case llvm::Triple::arm:
286 case llvm::Triple::thumb:
287 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
288 return ExprError();
289 break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000290 case llvm::Triple::mips:
291 case llvm::Triple::mipsel:
292 case llvm::Triple::mips64:
293 case llvm::Triple::mips64el:
294 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
295 return ExprError();
296 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000297 default:
298 break;
299 }
300 }
301
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000302 return TheCallResult;
Nate Begeman26a31422010-06-08 02:47:44 +0000303}
304
Nate Begeman61eecf52010-06-14 05:21:25 +0000305// Get the valid immediate range for the specified NEON type code.
306static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000307 NeonTypeFlags Type(t);
308 int IsQuad = Type.isQuad();
309 switch (Type.getEltType()) {
310 case NeonTypeFlags::Int8:
311 case NeonTypeFlags::Poly8:
312 return shift ? 7 : (8 << IsQuad) - 1;
313 case NeonTypeFlags::Int16:
314 case NeonTypeFlags::Poly16:
315 return shift ? 15 : (4 << IsQuad) - 1;
316 case NeonTypeFlags::Int32:
317 return shift ? 31 : (2 << IsQuad) - 1;
318 case NeonTypeFlags::Int64:
319 return shift ? 63 : (1 << IsQuad) - 1;
320 case NeonTypeFlags::Float16:
321 assert(!shift && "cannot shift float types!");
322 return (4 << IsQuad) - 1;
323 case NeonTypeFlags::Float32:
324 assert(!shift && "cannot shift float types!");
325 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000326 }
David Blaikie7530c032012-01-17 06:56:22 +0000327 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000328}
329
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000330/// getNeonEltType - Return the QualType corresponding to the elements of
331/// the vector type specified by the NeonTypeFlags. This is used to check
332/// the pointer arguments for Neon load/store intrinsics.
333static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
334 switch (Flags.getEltType()) {
335 case NeonTypeFlags::Int8:
336 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
337 case NeonTypeFlags::Int16:
338 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
339 case NeonTypeFlags::Int32:
340 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
341 case NeonTypeFlags::Int64:
342 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
343 case NeonTypeFlags::Poly8:
344 return Context.SignedCharTy;
345 case NeonTypeFlags::Poly16:
346 return Context.ShortTy;
347 case NeonTypeFlags::Float16:
348 return Context.UnsignedShortTy;
349 case NeonTypeFlags::Float32:
350 return Context.FloatTy;
351 }
David Blaikie7530c032012-01-17 06:56:22 +0000352 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000353}
354
Nate Begeman26a31422010-06-08 02:47:44 +0000355bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000356 llvm::APSInt Result;
357
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000358 uint64_t mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000359 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000360 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000361 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000362 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000363#define GET_NEON_OVERLOAD_CHECK
364#include "clang/Basic/arm_neon.inc"
365#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000366 }
367
Nate Begeman0d15c532010-06-13 04:47:52 +0000368 // For NEON intrinsics which are overloaded on vector element type, validate
369 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000370 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000371 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000372 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000373 return true;
374
Bob Wilsonda95f732011-11-08 01:16:11 +0000375 TV = Result.getLimitedValue(64);
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000376 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000377 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000378 << TheCall->getArg(ImmArg)->getSourceRange();
379 }
380
Bob Wilson46482552011-11-16 21:32:23 +0000381 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000382 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000383 Expr *Arg = TheCall->getArg(PtrArgNum);
384 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
385 Arg = ICE->getSubExpr();
386 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
387 QualType RHSTy = RHS.get()->getType();
388 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
389 if (HasConstPtr)
390 EltTy = EltTy.withConst();
391 QualType LHSTy = Context.getPointerType(EltTy);
392 AssignConvertType ConvTy;
393 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
394 if (RHS.isInvalid())
395 return true;
396 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
397 RHS.get(), AA_Assigning))
398 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000399 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000400
Nate Begeman0d15c532010-06-13 04:47:52 +0000401 // For NEON intrinsics which take an immediate value as part of the
402 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000403 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000404 switch (BuiltinID) {
405 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000406 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
407 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000408 case ARM::BI__builtin_arm_vcvtr_f:
409 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000410#define GET_NEON_IMMEDIATE_CHECK
411#include "clang/Basic/arm_neon.inc"
412#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000413 };
414
Douglas Gregor592a4232012-06-29 01:05:22 +0000415 // We can't check the value of a dependent argument.
416 if (TheCall->getArg(i)->isTypeDependent() ||
417 TheCall->getArg(i)->isValueDependent())
418 return false;
419
Nate Begeman61eecf52010-06-14 05:21:25 +0000420 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000421 if (SemaBuiltinConstantArg(TheCall, i, Result))
422 return true;
423
Nate Begeman61eecf52010-06-14 05:21:25 +0000424 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000425 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000426 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000427 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000428 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000429
Nate Begeman99c40bb2010-08-03 21:32:34 +0000430 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000431 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000432}
Daniel Dunbarde454282008-10-02 18:44:07 +0000433
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000434bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
435 unsigned i = 0, l = 0, u = 0;
436 switch (BuiltinID) {
437 default: return false;
438 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
439 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyanbe22cb82012-08-27 12:29:20 +0000440 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
441 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
442 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
443 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
444 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000445 };
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 llvm::APSInt Result;
454 if (SemaBuiltinConstantArg(TheCall, i, Result))
455 return true;
456
457 // Range check against the upper/lower values for this instruction.
458 unsigned Val = Result.getZExtValue();
459 if (Val < l || Val > u)
460 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
461 << l << u << TheCall->getArg(i)->getSourceRange();
462
463 return false;
464}
465
Richard Smith831421f2012-06-25 20:30:08 +0000466/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
467/// parameter with the FormatAttr's correct format_idx and firstDataArg.
468/// Returns true when the format fits the function and the FormatStringInfo has
469/// been populated.
470bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
471 FormatStringInfo *FSI) {
472 FSI->HasVAListArg = Format->getFirstArg() == 0;
473 FSI->FormatIdx = Format->getFormatIdx() - 1;
474 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssond406bf02009-08-16 01:56:34 +0000475
Richard Smith831421f2012-06-25 20:30:08 +0000476 // The way the format attribute works in GCC, the implicit this argument
477 // of member functions is counted. However, it doesn't appear in our own
478 // lists, so decrement format_idx in that case.
479 if (IsCXXMember) {
480 if(FSI->FormatIdx == 0)
481 return false;
482 --FSI->FormatIdx;
483 if (FSI->FirstDataArg != 0)
484 --FSI->FirstDataArg;
485 }
486 return true;
487}
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Richard Smith831421f2012-06-25 20:30:08 +0000489/// Handles the checks for format strings, non-POD arguments to vararg
490/// functions, and NULL arguments passed to non-NULL parameters.
491void Sema::checkCall(NamedDecl *FDecl, Expr **Args,
492 unsigned NumArgs,
493 unsigned NumProtoArgs,
494 bool IsMemberFunction,
495 SourceLocation Loc,
496 SourceRange Range,
497 VariadicCallType CallType) {
Jordan Rose66360e22012-10-02 01:49:54 +0000498 if (CurContext->isDependentContext())
499 return;
Daniel Dunbarde454282008-10-02 18:44:07 +0000500
Ted Kremenekc82faca2010-09-09 04:33:05 +0000501 // Printf and scanf checking.
Richard Smith831421f2012-06-25 20:30:08 +0000502 bool HandledFormatString = false;
Ted Kremenekc82faca2010-09-09 04:33:05 +0000503 for (specific_attr_iterator<FormatAttr>
Richard Smith831421f2012-06-25 20:30:08 +0000504 I = FDecl->specific_attr_begin<FormatAttr>(),
505 E = FDecl->specific_attr_end<FormatAttr>(); I != E ; ++I)
Jordan Roseddcfbc92012-07-19 18:10:23 +0000506 if (CheckFormatArguments(*I, Args, NumArgs, IsMemberFunction, CallType,
507 Loc, Range))
Richard Smith831421f2012-06-25 20:30:08 +0000508 HandledFormatString = true;
509
510 // Refuse POD arguments that weren't caught by the format string
511 // checks above.
512 if (!HandledFormatString && CallType != VariadicDoesNotApply)
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000513 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < NumArgs; ++ArgIdx) {
514 // Args[ArgIdx] can be null in malformed code.
515 if (Expr *Arg = Args[ArgIdx])
516 variadicArgumentPODCheck(Arg, CallType);
517 }
Mike Stump1eb44332009-09-09 15:08:12 +0000518
Ted Kremenekc82faca2010-09-09 04:33:05 +0000519 for (specific_attr_iterator<NonNullAttr>
Richard Smith831421f2012-06-25 20:30:08 +0000520 I = FDecl->specific_attr_begin<NonNullAttr>(),
521 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
522 CheckNonNullArguments(*I, Args, Loc);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000523
524 // Type safety checking.
525 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
526 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
527 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>(); i != e; ++i) {
528 CheckArgumentWithTypeTag(*i, Args);
529 }
Richard Smith831421f2012-06-25 20:30:08 +0000530}
531
532/// CheckConstructorCall - Check a constructor call for correctness and safety
533/// properties not enforced by the C type system.
534void Sema::CheckConstructorCall(FunctionDecl *FDecl, Expr **Args,
535 unsigned NumArgs,
536 const FunctionProtoType *Proto,
537 SourceLocation Loc) {
538 VariadicCallType CallType =
539 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
540 checkCall(FDecl, Args, NumArgs, Proto->getNumArgs(),
541 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
542}
543
544/// CheckFunctionCall - Check a direct function call for various correctness
545/// and safety properties not strictly enforced by the C type system.
546bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
547 const FunctionProtoType *Proto) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000548 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
549 isa<CXXMethodDecl>(FDecl);
550 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
551 IsMemberOperatorCall;
Richard Smith831421f2012-06-25 20:30:08 +0000552 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
553 TheCall->getCallee());
554 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Eli Friedman2edcde82012-10-11 00:30:58 +0000555 Expr** Args = TheCall->getArgs();
556 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmandf75b0c2012-10-11 00:34:15 +0000557 if (IsMemberOperatorCall) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000558 // If this is a call to a member operator, hide the first argument
559 // from checkCall.
560 // FIXME: Our choice of AST representation here is less than ideal.
561 ++Args;
562 --NumArgs;
563 }
564 checkCall(FDecl, Args, NumArgs, NumProtoArgs,
Richard Smith831421f2012-06-25 20:30:08 +0000565 IsMemberFunction, TheCall->getRParenLoc(),
566 TheCall->getCallee()->getSourceRange(), CallType);
567
568 IdentifierInfo *FnInfo = FDecl->getIdentifier();
569 // None of the checks below are needed for functions that don't have
570 // simple names (e.g., C++ conversion functions).
571 if (!FnInfo)
572 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +0000573
Anna Zaks0a151a12012-01-17 00:37:07 +0000574 unsigned CMId = FDecl->getMemoryFunctionKind();
575 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000576 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000577
Anna Zaksd9b859a2012-01-13 21:52:01 +0000578 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000579 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000580 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000581 else if (CMId == Builtin::BIstrncat)
582 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000583 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000584 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000585
Anders Carlssond406bf02009-08-16 01:56:34 +0000586 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000587}
588
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000589bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
590 Expr **Args, unsigned NumArgs) {
Richard Smith831421f2012-06-25 20:30:08 +0000591 VariadicCallType CallType =
592 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000593
Richard Smith831421f2012-06-25 20:30:08 +0000594 checkCall(Method, Args, NumArgs, Method->param_size(),
595 /*IsMemberFunction=*/false,
596 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000597
598 return false;
599}
600
Richard Smith831421f2012-06-25 20:30:08 +0000601bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall,
602 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000603 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
604 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000605 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000606
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000607 QualType Ty = V->getType();
608 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000609 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000610
Richard Smith831421f2012-06-25 20:30:08 +0000611 VariadicCallType CallType =
612 Proto && Proto->isVariadic() ? VariadicBlock : VariadicDoesNotApply ;
613 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000614
Richard Smith831421f2012-06-25 20:30:08 +0000615 checkCall(NDecl, TheCall->getArgs(), TheCall->getNumArgs(),
616 NumProtoArgs, /*IsMemberFunction=*/false,
617 TheCall->getRParenLoc(),
618 TheCall->getCallee()->getSourceRange(), CallType);
619
Anders Carlssond406bf02009-08-16 01:56:34 +0000620 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000621}
622
Richard Smithff34d402012-04-12 05:08:17 +0000623ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
624 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000625 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
626 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000627
Richard Smithff34d402012-04-12 05:08:17 +0000628 // All these operations take one of the following forms:
629 enum {
630 // C __c11_atomic_init(A *, C)
631 Init,
632 // C __c11_atomic_load(A *, int)
633 Load,
634 // void __atomic_load(A *, CP, int)
635 Copy,
636 // C __c11_atomic_add(A *, M, int)
637 Arithmetic,
638 // C __atomic_exchange_n(A *, CP, int)
639 Xchg,
640 // void __atomic_exchange(A *, C *, CP, int)
641 GNUXchg,
642 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
643 C11CmpXchg,
644 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
645 GNUCmpXchg
646 } Form = Init;
647 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
648 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
649 // where:
650 // C is an appropriate type,
651 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
652 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
653 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
654 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000655
Richard Smithff34d402012-04-12 05:08:17 +0000656 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
657 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
658 && "need to update code for modified C11 atomics");
659 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
660 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
661 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
662 Op == AtomicExpr::AO__atomic_store_n ||
663 Op == AtomicExpr::AO__atomic_exchange_n ||
664 Op == AtomicExpr::AO__atomic_compare_exchange_n;
665 bool IsAddSub = false;
666
667 switch (Op) {
668 case AtomicExpr::AO__c11_atomic_init:
669 Form = Init;
670 break;
671
672 case AtomicExpr::AO__c11_atomic_load:
673 case AtomicExpr::AO__atomic_load_n:
674 Form = Load;
675 break;
676
677 case AtomicExpr::AO__c11_atomic_store:
678 case AtomicExpr::AO__atomic_load:
679 case AtomicExpr::AO__atomic_store:
680 case AtomicExpr::AO__atomic_store_n:
681 Form = Copy;
682 break;
683
684 case AtomicExpr::AO__c11_atomic_fetch_add:
685 case AtomicExpr::AO__c11_atomic_fetch_sub:
686 case AtomicExpr::AO__atomic_fetch_add:
687 case AtomicExpr::AO__atomic_fetch_sub:
688 case AtomicExpr::AO__atomic_add_fetch:
689 case AtomicExpr::AO__atomic_sub_fetch:
690 IsAddSub = true;
691 // Fall through.
692 case AtomicExpr::AO__c11_atomic_fetch_and:
693 case AtomicExpr::AO__c11_atomic_fetch_or:
694 case AtomicExpr::AO__c11_atomic_fetch_xor:
695 case AtomicExpr::AO__atomic_fetch_and:
696 case AtomicExpr::AO__atomic_fetch_or:
697 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000698 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000699 case AtomicExpr::AO__atomic_and_fetch:
700 case AtomicExpr::AO__atomic_or_fetch:
701 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000702 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000703 Form = Arithmetic;
704 break;
705
706 case AtomicExpr::AO__c11_atomic_exchange:
707 case AtomicExpr::AO__atomic_exchange_n:
708 Form = Xchg;
709 break;
710
711 case AtomicExpr::AO__atomic_exchange:
712 Form = GNUXchg;
713 break;
714
715 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
716 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
717 Form = C11CmpXchg;
718 break;
719
720 case AtomicExpr::AO__atomic_compare_exchange:
721 case AtomicExpr::AO__atomic_compare_exchange_n:
722 Form = GNUCmpXchg;
723 break;
724 }
725
726 // Check we have the right number of arguments.
727 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000728 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000729 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000730 << TheCall->getCallee()->getSourceRange();
731 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000732 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
733 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000734 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000735 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000736 << TheCall->getCallee()->getSourceRange();
737 return ExprError();
738 }
739
Richard Smithff34d402012-04-12 05:08:17 +0000740 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000741 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000742 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
743 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
744 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +0000745 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +0000746 << Ptr->getType() << Ptr->getSourceRange();
747 return ExprError();
748 }
749
Richard Smithff34d402012-04-12 05:08:17 +0000750 // For a __c11 builtin, this should be a pointer to an _Atomic type.
751 QualType AtomTy = pointerType->getPointeeType(); // 'A'
752 QualType ValType = AtomTy; // 'C'
753 if (IsC11) {
754 if (!AtomTy->isAtomicType()) {
755 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
756 << Ptr->getType() << Ptr->getSourceRange();
757 return ExprError();
758 }
Richard Smithbc57b102012-09-15 06:09:58 +0000759 if (AtomTy.isConstQualified()) {
760 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
761 << Ptr->getType() << Ptr->getSourceRange();
762 return ExprError();
763 }
Richard Smithff34d402012-04-12 05:08:17 +0000764 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +0000765 }
Eli Friedman276b0612011-10-11 02:20:01 +0000766
Richard Smithff34d402012-04-12 05:08:17 +0000767 // For an arithmetic operation, the implied arithmetic must be well-formed.
768 if (Form == Arithmetic) {
769 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
770 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
771 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
772 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
773 return ExprError();
774 }
775 if (!IsAddSub && !ValType->isIntegerType()) {
776 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
777 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
778 return ExprError();
779 }
780 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
781 // For __atomic_*_n operations, the value type must be a scalar integral or
782 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +0000783 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +0000784 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
785 return ExprError();
786 }
787
788 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
789 // For GNU atomics, require a trivially-copyable type. This is not part of
790 // the GNU atomics specification, but we enforce it for sanity.
791 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +0000792 << Ptr->getType() << Ptr->getSourceRange();
793 return ExprError();
794 }
795
Richard Smithff34d402012-04-12 05:08:17 +0000796 // FIXME: For any builtin other than a load, the ValType must not be
797 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +0000798
799 switch (ValType.getObjCLifetime()) {
800 case Qualifiers::OCL_None:
801 case Qualifiers::OCL_ExplicitNone:
802 // okay
803 break;
804
805 case Qualifiers::OCL_Weak:
806 case Qualifiers::OCL_Strong:
807 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +0000808 // FIXME: Can this happen? By this point, ValType should be known
809 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +0000810 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
811 << ValType << Ptr->getSourceRange();
812 return ExprError();
813 }
814
815 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +0000816 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000817 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +0000818 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +0000819 ResultType = Context.BoolTy;
820
Richard Smithff34d402012-04-12 05:08:17 +0000821 // The type of a parameter passed 'by value'. In the GNU atomics, such
822 // arguments are actually passed as pointers.
823 QualType ByValType = ValType; // 'CP'
824 if (!IsC11 && !IsN)
825 ByValType = Ptr->getType();
826
Eli Friedman276b0612011-10-11 02:20:01 +0000827 // The first argument --- the pointer --- has a fixed type; we
828 // deduce the types of the rest of the arguments accordingly. Walk
829 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +0000830 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +0000831 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +0000832 if (i < NumVals[Form] + 1) {
833 switch (i) {
834 case 1:
835 // The second argument is the non-atomic operand. For arithmetic, this
836 // is always passed by value, and for a compare_exchange it is always
837 // passed by address. For the rest, GNU uses by-address and C11 uses
838 // by-value.
839 assert(Form != Load);
840 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
841 Ty = ValType;
842 else if (Form == Copy || Form == Xchg)
843 Ty = ByValType;
844 else if (Form == Arithmetic)
845 Ty = Context.getPointerDiffType();
846 else
847 Ty = Context.getPointerType(ValType.getUnqualifiedType());
848 break;
849 case 2:
850 // The third argument to compare_exchange / GNU exchange is a
851 // (pointer to a) desired value.
852 Ty = ByValType;
853 break;
854 case 3:
855 // The fourth argument to GNU compare_exchange is a 'weak' flag.
856 Ty = Context.BoolTy;
857 break;
858 }
Eli Friedman276b0612011-10-11 02:20:01 +0000859 } else {
860 // The order(s) are always converted to int.
861 Ty = Context.IntTy;
862 }
Richard Smithff34d402012-04-12 05:08:17 +0000863
Eli Friedman276b0612011-10-11 02:20:01 +0000864 InitializedEntity Entity =
865 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +0000866 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +0000867 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
868 if (Arg.isInvalid())
869 return true;
870 TheCall->setArg(i, Arg.get());
871 }
872
Richard Smithff34d402012-04-12 05:08:17 +0000873 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000874 SmallVector<Expr*, 5> SubExprs;
875 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +0000876 switch (Form) {
877 case Init:
878 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +0000879 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000880 break;
881 case Load:
882 SubExprs.push_back(TheCall->getArg(1)); // Order
883 break;
884 case Copy:
885 case Arithmetic:
886 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000887 SubExprs.push_back(TheCall->getArg(2)); // Order
888 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000889 break;
890 case GNUXchg:
891 // Note, AtomicExpr::getVal2() has a special case for this atomic.
892 SubExprs.push_back(TheCall->getArg(3)); // Order
893 SubExprs.push_back(TheCall->getArg(1)); // Val1
894 SubExprs.push_back(TheCall->getArg(2)); // Val2
895 break;
896 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000897 SubExprs.push_back(TheCall->getArg(3)); // Order
898 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000899 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +0000900 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +0000901 break;
902 case GNUCmpXchg:
903 SubExprs.push_back(TheCall->getArg(4)); // Order
904 SubExprs.push_back(TheCall->getArg(1)); // Val1
905 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
906 SubExprs.push_back(TheCall->getArg(2)); // Val2
907 SubExprs.push_back(TheCall->getArg(3)); // Weak
908 break;
Eli Friedman276b0612011-10-11 02:20:01 +0000909 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000910
911 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +0000912 SubExprs, ResultType, Op,
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000913 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000914}
915
916
John McCall5f8d6042011-08-27 01:09:30 +0000917/// checkBuiltinArgument - Given a call to a builtin function, perform
918/// normal type-checking on the given argument, updating the call in
919/// place. This is useful when a builtin function requires custom
920/// type-checking for some of its arguments but not necessarily all of
921/// them.
922///
923/// Returns true on error.
924static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
925 FunctionDecl *Fn = E->getDirectCallee();
926 assert(Fn && "builtin call without direct callee!");
927
928 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
929 InitializedEntity Entity =
930 InitializedEntity::InitializeParameter(S.Context, Param);
931
932 ExprResult Arg = E->getArg(0);
933 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
934 if (Arg.isInvalid())
935 return true;
936
937 E->setArg(ArgIndex, Arg.take());
938 return false;
939}
940
Chris Lattner5caa3702009-05-08 06:58:22 +0000941/// SemaBuiltinAtomicOverloaded - We have a call to a function like
942/// __sync_fetch_and_add, which is an overloaded function based on the pointer
943/// type of its first argument. The main ActOnCallExpr routines have already
944/// promoted the types of arguments because all of these calls are prototyped as
945/// void(...).
946///
947/// This function goes through and does final semantic checking for these
948/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000949ExprResult
950Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000951 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000952 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
953 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
954
955 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000956 if (TheCall->getNumArgs() < 1) {
957 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
958 << 0 << 1 << TheCall->getNumArgs()
959 << TheCall->getCallee()->getSourceRange();
960 return ExprError();
961 }
Mike Stump1eb44332009-09-09 15:08:12 +0000962
Chris Lattner5caa3702009-05-08 06:58:22 +0000963 // Inspect the first argument of the atomic builtin. This should always be
964 // a pointer type, whose element is an integral scalar or pointer type.
965 // Because it is a pointer type, we don't have to worry about any implicit
966 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000967 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000968 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +0000969 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
970 if (FirstArgResult.isInvalid())
971 return ExprError();
972 FirstArg = FirstArgResult.take();
973 TheCall->setArg(0, FirstArg);
974
John McCallf85e1932011-06-15 23:02:42 +0000975 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
976 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000977 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
978 << FirstArg->getType() << FirstArg->getSourceRange();
979 return ExprError();
980 }
Mike Stump1eb44332009-09-09 15:08:12 +0000981
John McCallf85e1932011-06-15 23:02:42 +0000982 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000983 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000984 !ValType->isBlockPointerType()) {
985 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
986 << FirstArg->getType() << FirstArg->getSourceRange();
987 return ExprError();
988 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000989
John McCallf85e1932011-06-15 23:02:42 +0000990 switch (ValType.getObjCLifetime()) {
991 case Qualifiers::OCL_None:
992 case Qualifiers::OCL_ExplicitNone:
993 // okay
994 break;
995
996 case Qualifiers::OCL_Weak:
997 case Qualifiers::OCL_Strong:
998 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000999 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001000 << ValType << FirstArg->getSourceRange();
1001 return ExprError();
1002 }
1003
John McCallb45ae252011-10-05 07:41:44 +00001004 // Strip any qualifiers off ValType.
1005 ValType = ValType.getUnqualifiedType();
1006
Chandler Carruth8d13d222010-07-18 20:54:12 +00001007 // The majority of builtins return a value, but a few have special return
1008 // types, so allow them to override appropriately below.
1009 QualType ResultType = ValType;
1010
Chris Lattner5caa3702009-05-08 06:58:22 +00001011 // We need to figure out which concrete builtin this maps onto. For example,
1012 // __sync_fetch_and_add with a 2 byte object turns into
1013 // __sync_fetch_and_add_2.
1014#define BUILTIN_ROW(x) \
1015 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1016 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +00001017
Chris Lattner5caa3702009-05-08 06:58:22 +00001018 static const unsigned BuiltinIndices[][5] = {
1019 BUILTIN_ROW(__sync_fetch_and_add),
1020 BUILTIN_ROW(__sync_fetch_and_sub),
1021 BUILTIN_ROW(__sync_fetch_and_or),
1022 BUILTIN_ROW(__sync_fetch_and_and),
1023 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +00001024
Chris Lattner5caa3702009-05-08 06:58:22 +00001025 BUILTIN_ROW(__sync_add_and_fetch),
1026 BUILTIN_ROW(__sync_sub_and_fetch),
1027 BUILTIN_ROW(__sync_and_and_fetch),
1028 BUILTIN_ROW(__sync_or_and_fetch),
1029 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001030
Chris Lattner5caa3702009-05-08 06:58:22 +00001031 BUILTIN_ROW(__sync_val_compare_and_swap),
1032 BUILTIN_ROW(__sync_bool_compare_and_swap),
1033 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001034 BUILTIN_ROW(__sync_lock_release),
1035 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001036 };
Mike Stump1eb44332009-09-09 15:08:12 +00001037#undef BUILTIN_ROW
1038
Chris Lattner5caa3702009-05-08 06:58:22 +00001039 // Determine the index of the size.
1040 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001041 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001042 case 1: SizeIndex = 0; break;
1043 case 2: SizeIndex = 1; break;
1044 case 4: SizeIndex = 2; break;
1045 case 8: SizeIndex = 3; break;
1046 case 16: SizeIndex = 4; break;
1047 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001048 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1049 << FirstArg->getType() << FirstArg->getSourceRange();
1050 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001051 }
Mike Stump1eb44332009-09-09 15:08:12 +00001052
Chris Lattner5caa3702009-05-08 06:58:22 +00001053 // Each of these builtins has one pointer argument, followed by some number of
1054 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1055 // that we ignore. Find out which row of BuiltinIndices to read from as well
1056 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001057 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001058 unsigned BuiltinIndex, NumFixed = 1;
1059 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001060 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001061 case Builtin::BI__sync_fetch_and_add:
1062 case Builtin::BI__sync_fetch_and_add_1:
1063 case Builtin::BI__sync_fetch_and_add_2:
1064 case Builtin::BI__sync_fetch_and_add_4:
1065 case Builtin::BI__sync_fetch_and_add_8:
1066 case Builtin::BI__sync_fetch_and_add_16:
1067 BuiltinIndex = 0;
1068 break;
1069
1070 case Builtin::BI__sync_fetch_and_sub:
1071 case Builtin::BI__sync_fetch_and_sub_1:
1072 case Builtin::BI__sync_fetch_and_sub_2:
1073 case Builtin::BI__sync_fetch_and_sub_4:
1074 case Builtin::BI__sync_fetch_and_sub_8:
1075 case Builtin::BI__sync_fetch_and_sub_16:
1076 BuiltinIndex = 1;
1077 break;
1078
1079 case Builtin::BI__sync_fetch_and_or:
1080 case Builtin::BI__sync_fetch_and_or_1:
1081 case Builtin::BI__sync_fetch_and_or_2:
1082 case Builtin::BI__sync_fetch_and_or_4:
1083 case Builtin::BI__sync_fetch_and_or_8:
1084 case Builtin::BI__sync_fetch_and_or_16:
1085 BuiltinIndex = 2;
1086 break;
1087
1088 case Builtin::BI__sync_fetch_and_and:
1089 case Builtin::BI__sync_fetch_and_and_1:
1090 case Builtin::BI__sync_fetch_and_and_2:
1091 case Builtin::BI__sync_fetch_and_and_4:
1092 case Builtin::BI__sync_fetch_and_and_8:
1093 case Builtin::BI__sync_fetch_and_and_16:
1094 BuiltinIndex = 3;
1095 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001096
Douglas Gregora9766412011-11-28 16:30:08 +00001097 case Builtin::BI__sync_fetch_and_xor:
1098 case Builtin::BI__sync_fetch_and_xor_1:
1099 case Builtin::BI__sync_fetch_and_xor_2:
1100 case Builtin::BI__sync_fetch_and_xor_4:
1101 case Builtin::BI__sync_fetch_and_xor_8:
1102 case Builtin::BI__sync_fetch_and_xor_16:
1103 BuiltinIndex = 4;
1104 break;
1105
1106 case Builtin::BI__sync_add_and_fetch:
1107 case Builtin::BI__sync_add_and_fetch_1:
1108 case Builtin::BI__sync_add_and_fetch_2:
1109 case Builtin::BI__sync_add_and_fetch_4:
1110 case Builtin::BI__sync_add_and_fetch_8:
1111 case Builtin::BI__sync_add_and_fetch_16:
1112 BuiltinIndex = 5;
1113 break;
1114
1115 case Builtin::BI__sync_sub_and_fetch:
1116 case Builtin::BI__sync_sub_and_fetch_1:
1117 case Builtin::BI__sync_sub_and_fetch_2:
1118 case Builtin::BI__sync_sub_and_fetch_4:
1119 case Builtin::BI__sync_sub_and_fetch_8:
1120 case Builtin::BI__sync_sub_and_fetch_16:
1121 BuiltinIndex = 6;
1122 break;
1123
1124 case Builtin::BI__sync_and_and_fetch:
1125 case Builtin::BI__sync_and_and_fetch_1:
1126 case Builtin::BI__sync_and_and_fetch_2:
1127 case Builtin::BI__sync_and_and_fetch_4:
1128 case Builtin::BI__sync_and_and_fetch_8:
1129 case Builtin::BI__sync_and_and_fetch_16:
1130 BuiltinIndex = 7;
1131 break;
1132
1133 case Builtin::BI__sync_or_and_fetch:
1134 case Builtin::BI__sync_or_and_fetch_1:
1135 case Builtin::BI__sync_or_and_fetch_2:
1136 case Builtin::BI__sync_or_and_fetch_4:
1137 case Builtin::BI__sync_or_and_fetch_8:
1138 case Builtin::BI__sync_or_and_fetch_16:
1139 BuiltinIndex = 8;
1140 break;
1141
1142 case Builtin::BI__sync_xor_and_fetch:
1143 case Builtin::BI__sync_xor_and_fetch_1:
1144 case Builtin::BI__sync_xor_and_fetch_2:
1145 case Builtin::BI__sync_xor_and_fetch_4:
1146 case Builtin::BI__sync_xor_and_fetch_8:
1147 case Builtin::BI__sync_xor_and_fetch_16:
1148 BuiltinIndex = 9;
1149 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001150
Chris Lattner5caa3702009-05-08 06:58:22 +00001151 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001152 case Builtin::BI__sync_val_compare_and_swap_1:
1153 case Builtin::BI__sync_val_compare_and_swap_2:
1154 case Builtin::BI__sync_val_compare_and_swap_4:
1155 case Builtin::BI__sync_val_compare_and_swap_8:
1156 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001157 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001158 NumFixed = 2;
1159 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001160
Chris Lattner5caa3702009-05-08 06:58:22 +00001161 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001162 case Builtin::BI__sync_bool_compare_and_swap_1:
1163 case Builtin::BI__sync_bool_compare_and_swap_2:
1164 case Builtin::BI__sync_bool_compare_and_swap_4:
1165 case Builtin::BI__sync_bool_compare_and_swap_8:
1166 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001167 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001168 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001169 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001170 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001171
1172 case Builtin::BI__sync_lock_test_and_set:
1173 case Builtin::BI__sync_lock_test_and_set_1:
1174 case Builtin::BI__sync_lock_test_and_set_2:
1175 case Builtin::BI__sync_lock_test_and_set_4:
1176 case Builtin::BI__sync_lock_test_and_set_8:
1177 case Builtin::BI__sync_lock_test_and_set_16:
1178 BuiltinIndex = 12;
1179 break;
1180
Chris Lattner5caa3702009-05-08 06:58:22 +00001181 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001182 case Builtin::BI__sync_lock_release_1:
1183 case Builtin::BI__sync_lock_release_2:
1184 case Builtin::BI__sync_lock_release_4:
1185 case Builtin::BI__sync_lock_release_8:
1186 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001187 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001188 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001189 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001190 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001191
1192 case Builtin::BI__sync_swap:
1193 case Builtin::BI__sync_swap_1:
1194 case Builtin::BI__sync_swap_2:
1195 case Builtin::BI__sync_swap_4:
1196 case Builtin::BI__sync_swap_8:
1197 case Builtin::BI__sync_swap_16:
1198 BuiltinIndex = 14;
1199 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001200 }
Mike Stump1eb44332009-09-09 15:08:12 +00001201
Chris Lattner5caa3702009-05-08 06:58:22 +00001202 // Now that we know how many fixed arguments we expect, first check that we
1203 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001204 if (TheCall->getNumArgs() < 1+NumFixed) {
1205 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1206 << 0 << 1+NumFixed << TheCall->getNumArgs()
1207 << TheCall->getCallee()->getSourceRange();
1208 return ExprError();
1209 }
Mike Stump1eb44332009-09-09 15:08:12 +00001210
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001211 // Get the decl for the concrete builtin from this, we can tell what the
1212 // concrete integer type we should convert to is.
1213 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1214 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001215 FunctionDecl *NewBuiltinDecl;
1216 if (NewBuiltinID == BuiltinID)
1217 NewBuiltinDecl = FDecl;
1218 else {
1219 // Perform builtin lookup to avoid redeclaring it.
1220 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1221 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1222 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1223 assert(Res.getFoundDecl());
1224 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1225 if (NewBuiltinDecl == 0)
1226 return ExprError();
1227 }
Chandler Carruthd2014572010-07-09 18:59:35 +00001228
John McCallf871d0c2010-08-07 06:22:56 +00001229 // The first argument --- the pointer --- has a fixed type; we
1230 // deduce the types of the rest of the arguments accordingly. Walk
1231 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001232 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001233 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001234
Chris Lattner5caa3702009-05-08 06:58:22 +00001235 // GCC does an implicit conversion to the pointer or integer ValType. This
1236 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001237 // Initialize the argument.
1238 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1239 ValType, /*consume*/ false);
1240 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001241 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001242 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001243
Chris Lattner5caa3702009-05-08 06:58:22 +00001244 // Okay, we have something that *can* be converted to the right type. Check
1245 // to see if there is a potentially weird extension going on here. This can
1246 // happen when you do an atomic operation on something like an char* and
1247 // pass in 42. The 42 gets converted to char. This is even more strange
1248 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001249 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001250 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001251 }
Mike Stump1eb44332009-09-09 15:08:12 +00001252
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001253 ASTContext& Context = this->getASTContext();
1254
1255 // Create a new DeclRefExpr to refer to the new decl.
1256 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1257 Context,
1258 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001259 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001260 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001261 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001262 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001263 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001264 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001265
Chris Lattner5caa3702009-05-08 06:58:22 +00001266 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001267 // FIXME: This loses syntactic information.
1268 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1269 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1270 CK_BuiltinFnToFnPtr);
John Wiegley429bb272011-04-08 18:41:53 +00001271 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001272
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001273 // Change the result type of the call to match the original value type. This
1274 // is arbitrary, but the codegen for these builtins ins design to handle it
1275 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001276 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001277
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001278 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001279}
1280
Chris Lattner69039812009-02-18 06:01:06 +00001281/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001282/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001283/// Note: It might also make sense to do the UTF-16 conversion here (would
1284/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001285bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001286 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001287 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1288
Douglas Gregor5cee1192011-07-27 05:40:30 +00001289 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001290 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1291 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001292 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001293 }
Mike Stump1eb44332009-09-09 15:08:12 +00001294
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001295 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001296 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001297 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001298 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00001299 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001300 UTF16 *ToPtr = &ToBuf[0];
1301
1302 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1303 &ToPtr, ToPtr + NumBytes,
1304 strictConversion);
1305 // Check for conversion failure.
1306 if (Result != conversionOK)
1307 Diag(Arg->getLocStart(),
1308 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1309 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001310 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001311}
1312
Chris Lattnerc27c6652007-12-20 00:05:45 +00001313/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1314/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001315bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1316 Expr *Fn = TheCall->getCallee();
1317 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001318 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001319 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001320 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1321 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001322 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001323 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001324 return true;
1325 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001326
1327 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001328 return Diag(TheCall->getLocEnd(),
1329 diag::err_typecheck_call_too_few_args_at_least)
1330 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001331 }
1332
John McCall5f8d6042011-08-27 01:09:30 +00001333 // Type-check the first argument normally.
1334 if (checkBuiltinArgument(*this, TheCall, 0))
1335 return true;
1336
Chris Lattnerc27c6652007-12-20 00:05:45 +00001337 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001338 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001339 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001340 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001341 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001342 else if (FunctionDecl *FD = getCurFunctionDecl())
1343 isVariadic = FD->isVariadic();
1344 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001345 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001346
Chris Lattnerc27c6652007-12-20 00:05:45 +00001347 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001348 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1349 return true;
1350 }
Mike Stump1eb44332009-09-09 15:08:12 +00001351
Chris Lattner30ce3442007-12-19 23:59:04 +00001352 // Verify that the second argument to the builtin is the last argument of the
1353 // current function or method.
1354 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001355 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001356
Anders Carlsson88cf2262008-02-11 04:20:54 +00001357 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1358 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001359 // FIXME: This isn't correct for methods (results in bogus warning).
1360 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001361 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001362 if (CurBlock)
1363 LastArg = *(CurBlock->TheDecl->param_end()-1);
1364 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001365 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001366 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001367 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001368 SecondArgIsLastNamedArgument = PV == LastArg;
1369 }
1370 }
Mike Stump1eb44332009-09-09 15:08:12 +00001371
Chris Lattner30ce3442007-12-19 23:59:04 +00001372 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001373 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001374 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1375 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001376}
Chris Lattner30ce3442007-12-19 23:59:04 +00001377
Chris Lattner1b9a0792007-12-20 00:26:33 +00001378/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1379/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001380bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1381 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001382 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001383 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001384 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001385 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001386 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001387 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001388 << SourceRange(TheCall->getArg(2)->getLocStart(),
1389 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001390
John Wiegley429bb272011-04-08 18:41:53 +00001391 ExprResult OrigArg0 = TheCall->getArg(0);
1392 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001393
Chris Lattner1b9a0792007-12-20 00:26:33 +00001394 // Do standard promotions between the two arguments, returning their common
1395 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001396 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001397 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1398 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001399
1400 // Make sure any conversions are pushed back into the call; this is
1401 // type safe since unordered compare builtins are declared as "_Bool
1402 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001403 TheCall->setArg(0, OrigArg0.get());
1404 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001405
John Wiegley429bb272011-04-08 18:41:53 +00001406 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001407 return false;
1408
Chris Lattner1b9a0792007-12-20 00:26:33 +00001409 // If the common type isn't a real floating type, then the arguments were
1410 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001411 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001412 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001413 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001414 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1415 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001416
Chris Lattner1b9a0792007-12-20 00:26:33 +00001417 return false;
1418}
1419
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001420/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1421/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001422/// to check everything. We expect the last argument to be a floating point
1423/// value.
1424bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1425 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001426 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001427 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001428 if (TheCall->getNumArgs() > NumArgs)
1429 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001430 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001431 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001432 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001433 (*(TheCall->arg_end()-1))->getLocEnd());
1434
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001435 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001436
Eli Friedman9ac6f622009-08-31 20:06:00 +00001437 if (OrigArg->isTypeDependent())
1438 return false;
1439
Chris Lattner81368fb2010-05-06 05:50:07 +00001440 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001441 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001442 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001443 diag::err_typecheck_call_invalid_unary_fp)
1444 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001445
Chris Lattner81368fb2010-05-06 05:50:07 +00001446 // If this is an implicit conversion from float -> double, remove it.
1447 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1448 Expr *CastArg = Cast->getSubExpr();
1449 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1450 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1451 "promotion from float to double is the only expected cast here");
1452 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001453 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001454 }
1455 }
1456
Eli Friedman9ac6f622009-08-31 20:06:00 +00001457 return false;
1458}
1459
Eli Friedmand38617c2008-05-14 19:38:39 +00001460/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1461// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001462ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001463 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001464 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001465 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001466 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001467 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001468
Nate Begeman37b6a572010-06-08 00:16:34 +00001469 // Determine which of the following types of shufflevector we're checking:
1470 // 1) unary, vector mask: (lhs, mask)
1471 // 2) binary, vector mask: (lhs, rhs, mask)
1472 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1473 QualType resType = TheCall->getArg(0)->getType();
1474 unsigned numElements = 0;
1475
Douglas Gregorcde01732009-05-19 22:10:17 +00001476 if (!TheCall->getArg(0)->isTypeDependent() &&
1477 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001478 QualType LHSType = TheCall->getArg(0)->getType();
1479 QualType RHSType = TheCall->getArg(1)->getType();
1480
1481 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001482 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001483 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001484 TheCall->getArg(1)->getLocEnd());
1485 return ExprError();
1486 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001487
1488 numElements = LHSType->getAs<VectorType>()->getNumElements();
1489 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001490
Nate Begeman37b6a572010-06-08 00:16:34 +00001491 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1492 // with mask. If so, verify that RHS is an integer vector type with the
1493 // same number of elts as lhs.
1494 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001495 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001496 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1497 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1498 << SourceRange(TheCall->getArg(1)->getLocStart(),
1499 TheCall->getArg(1)->getLocEnd());
1500 numResElements = numElements;
1501 }
1502 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001503 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001504 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001505 TheCall->getArg(1)->getLocEnd());
1506 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001507 } else if (numElements != numResElements) {
1508 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001509 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001510 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001511 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001512 }
1513
1514 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001515 if (TheCall->getArg(i)->isTypeDependent() ||
1516 TheCall->getArg(i)->isValueDependent())
1517 continue;
1518
Nate Begeman37b6a572010-06-08 00:16:34 +00001519 llvm::APSInt Result(32);
1520 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1521 return ExprError(Diag(TheCall->getLocStart(),
1522 diag::err_shufflevector_nonconstant_argument)
1523 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001524
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001525 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001526 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001527 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001528 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001529 }
1530
Chris Lattner5f9e2722011-07-23 10:55:15 +00001531 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001532
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001533 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001534 exprs.push_back(TheCall->getArg(i));
1535 TheCall->setArg(i, 0);
1536 }
1537
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001538 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001539 TheCall->getCallee()->getLocStart(),
1540 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001541}
Chris Lattner30ce3442007-12-19 23:59:04 +00001542
Daniel Dunbar4493f792008-07-21 22:59:13 +00001543/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1544// This is declared to take (const void*, ...) and can take two
1545// optional constant int args.
1546bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001547 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001548
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001549 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001550 return Diag(TheCall->getLocEnd(),
1551 diag::err_typecheck_call_too_many_args_at_most)
1552 << 0 /*function call*/ << 3 << NumArgs
1553 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001554
1555 // Argument 0 is checked for us and the remaining arguments must be
1556 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001557 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001558 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001559
1560 // We can't check the value of a dependent argument.
1561 if (Arg->isTypeDependent() || Arg->isValueDependent())
1562 continue;
1563
Eli Friedman9aef7262009-12-04 00:30:06 +00001564 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001565 if (SemaBuiltinConstantArg(TheCall, i, Result))
1566 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001567
Daniel Dunbar4493f792008-07-21 22:59:13 +00001568 // FIXME: gcc issues a warning and rewrites these to 0. These
1569 // seems especially odd for the third argument since the default
1570 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001571 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001572 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001573 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001574 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001575 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001576 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001577 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001578 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001579 }
1580 }
1581
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001582 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001583}
1584
Eric Christopher691ebc32010-04-17 02:26:23 +00001585/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1586/// TheCall is a constant expression.
1587bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1588 llvm::APSInt &Result) {
1589 Expr *Arg = TheCall->getArg(ArgNum);
1590 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1591 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1592
1593 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1594
1595 if (!Arg->isIntegerConstantExpr(Result, Context))
1596 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001597 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001598
Chris Lattner21fb98e2009-09-23 06:06:36 +00001599 return false;
1600}
1601
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001602/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1603/// int type). This simply type checks that type is one of the defined
1604/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001605// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001606bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001607 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001608
1609 // We can't check the value of a dependent argument.
1610 if (TheCall->getArg(1)->isTypeDependent() ||
1611 TheCall->getArg(1)->isValueDependent())
1612 return false;
1613
Eric Christopher691ebc32010-04-17 02:26:23 +00001614 // Check constant-ness first.
1615 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1616 return true;
1617
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001618 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001619 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001620 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1621 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001622 }
1623
1624 return false;
1625}
1626
Eli Friedman586d6a82009-05-03 06:04:26 +00001627/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001628/// This checks that val is a constant 1.
1629bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1630 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001631 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001632
Eric Christopher691ebc32010-04-17 02:26:23 +00001633 // TODO: This is less than ideal. Overload this to take a value.
1634 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1635 return true;
1636
1637 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001638 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1639 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1640
1641 return false;
1642}
1643
Richard Smith831421f2012-06-25 20:30:08 +00001644// Determine if an expression is a string literal or constant string.
1645// If this function returns false on the arguments to a function expecting a
1646// format string, we will usually need to emit a warning.
1647// True string literals are then checked by CheckFormatString.
1648Sema::StringLiteralCheckType
1649Sema::checkFormatStringExpr(const Expr *E, Expr **Args,
1650 unsigned NumArgs, bool HasVAListArg,
1651 unsigned format_idx, unsigned firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001652 FormatStringType Type, VariadicCallType CallType,
1653 bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001654 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001655 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001656 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001657
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001658 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001659
David Blaikiea73cdcb2012-02-10 21:07:25 +00001660 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1661 // Technically -Wformat-nonliteral does not warn about this case.
1662 // The behavior of printf and friends in this case is implementation
1663 // dependent. Ideally if the format string cannot be null then
1664 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith831421f2012-06-25 20:30:08 +00001665 return SLCT_CheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001666
Ted Kremenekd30ef872009-01-12 23:09:09 +00001667 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001668 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001669 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001670 // The expression is a literal if both sub-expressions were, and it was
1671 // completely checked only if both sub-expressions were checked.
1672 const AbstractConditionalOperator *C =
1673 cast<AbstractConditionalOperator>(E);
1674 StringLiteralCheckType Left =
1675 checkFormatStringExpr(C->getTrueExpr(), Args, NumArgs,
1676 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001677 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001678 if (Left == SLCT_NotALiteral)
1679 return SLCT_NotALiteral;
1680 StringLiteralCheckType Right =
1681 checkFormatStringExpr(C->getFalseExpr(), Args, NumArgs,
1682 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001683 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001684 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001685 }
1686
1687 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001688 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1689 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001690 }
1691
John McCall56ca35d2011-02-17 10:25:35 +00001692 case Stmt::OpaqueValueExprClass:
1693 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1694 E = src;
1695 goto tryAgain;
1696 }
Richard Smith831421f2012-06-25 20:30:08 +00001697 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00001698
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001699 case Stmt::PredefinedExprClass:
1700 // While __func__, etc., are technically not string literals, they
1701 // cannot contain format specifiers and thus are not a security
1702 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00001703 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001704
Ted Kremenek082d9362009-03-20 21:35:28 +00001705 case Stmt::DeclRefExprClass: {
1706 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001707
Ted Kremenek082d9362009-03-20 21:35:28 +00001708 // As an exception, do not flag errors for variables binding to
1709 // const string literals.
1710 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1711 bool isConstant = false;
1712 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001713
Ted Kremenek082d9362009-03-20 21:35:28 +00001714 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1715 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001716 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001717 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001718 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001719 } else if (T->isObjCObjectPointerType()) {
1720 // In ObjC, there is usually no "const ObjectPointer" type,
1721 // so don't check if the pointee type is constant.
1722 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001723 }
Mike Stump1eb44332009-09-09 15:08:12 +00001724
Ted Kremenek082d9362009-03-20 21:35:28 +00001725 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001726 if (const Expr *Init = VD->getAnyInitializer()) {
1727 // Look through initializers like const char c[] = { "foo" }
1728 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
1729 if (InitList->isStringLiteralInit())
1730 Init = InitList->getInit(0)->IgnoreParenImpCasts();
1731 }
Richard Smith831421f2012-06-25 20:30:08 +00001732 return checkFormatStringExpr(Init, Args, NumArgs,
1733 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001734 firstDataArg, Type, CallType,
Richard Smith831421f2012-06-25 20:30:08 +00001735 /*inFunctionCall*/false);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001736 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001737 }
Mike Stump1eb44332009-09-09 15:08:12 +00001738
Anders Carlssond966a552009-06-28 19:55:58 +00001739 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1740 // special check to see if the format string is a function parameter
1741 // of the function calling the printf function. If the function
1742 // has an attribute indicating it is a printf-like function, then we
1743 // should suppress warnings concerning non-literals being used in a call
1744 // to a vprintf function. For example:
1745 //
1746 // void
1747 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1748 // va_list ap;
1749 // va_start(ap, fmt);
1750 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1751 // ...
1752 //
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001753 if (HasVAListArg) {
1754 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1755 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1756 int PVIndex = PV->getFunctionScopeIndex() + 1;
1757 for (specific_attr_iterator<FormatAttr>
1758 i = ND->specific_attr_begin<FormatAttr>(),
1759 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1760 FormatAttr *PVFormat = *i;
1761 // adjust for implicit parameter
1762 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1763 if (MD->isInstance())
1764 ++PVIndex;
1765 // We also check if the formats are compatible.
1766 // We can't pass a 'scanf' string to a 'printf' function.
1767 if (PVIndex == PVFormat->getFormatIdx() &&
1768 Type == GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00001769 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001770 }
1771 }
1772 }
1773 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001774 }
Mike Stump1eb44332009-09-09 15:08:12 +00001775
Richard Smith831421f2012-06-25 20:30:08 +00001776 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00001777 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001778
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001779 case Stmt::CallExprClass:
1780 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001781 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001782 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1783 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1784 unsigned ArgIndex = FA->getFormatIdx();
1785 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1786 if (MD->isInstance())
1787 --ArgIndex;
1788 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001789
Richard Smith831421f2012-06-25 20:30:08 +00001790 return checkFormatStringExpr(Arg, Args, NumArgs,
1791 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001792 Type, CallType, inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001793 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1794 unsigned BuiltinID = FD->getBuiltinID();
1795 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
1796 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
1797 const Expr *Arg = CE->getArg(0);
Richard Smith831421f2012-06-25 20:30:08 +00001798 return checkFormatStringExpr(Arg, Args, NumArgs,
1799 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001800 firstDataArg, Type, CallType,
1801 inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001802 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00001803 }
1804 }
Mike Stump1eb44332009-09-09 15:08:12 +00001805
Richard Smith831421f2012-06-25 20:30:08 +00001806 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00001807 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001808 case Stmt::ObjCStringLiteralClass:
1809 case Stmt::StringLiteralClass: {
1810 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001811
Ted Kremenek082d9362009-03-20 21:35:28 +00001812 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001813 StrE = ObjCFExpr->getString();
1814 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001815 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001816
Ted Kremenekd30ef872009-01-12 23:09:09 +00001817 if (StrE) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001818 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001819 firstDataArg, Type, inFunctionCall, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001820 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001821 }
Mike Stump1eb44332009-09-09 15:08:12 +00001822
Richard Smith831421f2012-06-25 20:30:08 +00001823 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001824 }
Mike Stump1eb44332009-09-09 15:08:12 +00001825
Ted Kremenek082d9362009-03-20 21:35:28 +00001826 default:
Richard Smith831421f2012-06-25 20:30:08 +00001827 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001828 }
1829}
1830
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001831void
Mike Stump1eb44332009-09-09 15:08:12 +00001832Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001833 const Expr * const *ExprArgs,
1834 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001835 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1836 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001837 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001838 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001839 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001840 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001841 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001842 }
1843}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001844
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001845Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1846 return llvm::StringSwitch<FormatStringType>(Format->getType())
1847 .Case("scanf", FST_Scanf)
1848 .Cases("printf", "printf0", FST_Printf)
1849 .Cases("NSString", "CFString", FST_NSString)
1850 .Case("strftime", FST_Strftime)
1851 .Case("strfmon", FST_Strfmon)
1852 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1853 .Default(FST_Unknown);
1854}
1855
Jordan Roseddcfbc92012-07-19 18:10:23 +00001856/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00001857/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00001858/// Returns true if a format string has been fully checked.
Richard Smith831421f2012-06-25 20:30:08 +00001859bool Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001860 unsigned NumArgs, bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001861 VariadicCallType CallType,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001862 SourceLocation Loc, SourceRange Range) {
Richard Smith831421f2012-06-25 20:30:08 +00001863 FormatStringInfo FSI;
1864 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
1865 return CheckFormatArguments(Args, NumArgs, FSI.HasVAListArg, FSI.FormatIdx,
1866 FSI.FirstDataArg, GetFormatStringType(Format),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001867 CallType, Loc, Range);
Richard Smith831421f2012-06-25 20:30:08 +00001868 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001869}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001870
Richard Smith831421f2012-06-25 20:30:08 +00001871bool Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001872 bool HasVAListArg, unsigned format_idx,
1873 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001874 VariadicCallType CallType,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001875 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001876 // CHECK: printf/scanf-like function is called with no format string.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001877 if (format_idx >= NumArgs) {
1878 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00001879 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00001880 }
Mike Stump1eb44332009-09-09 15:08:12 +00001881
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001882 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001883
Chris Lattner59907c42007-08-10 20:18:51 +00001884 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001885 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001886 // Dynamically generated format strings are difficult to
1887 // automatically vet at compile time. Requiring that format strings
1888 // are string literals: (1) permits the checking of format strings by
1889 // the compiler and thereby (2) can practically remove the source of
1890 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001891
Mike Stump1eb44332009-09-09 15:08:12 +00001892 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001893 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001894 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001895 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00001896 StringLiteralCheckType CT =
1897 checkFormatStringExpr(OrigFormatExpr, Args, NumArgs, HasVAListArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001898 format_idx, firstDataArg, Type, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001899 if (CT != SLCT_NotALiteral)
1900 // Literal format string found, check done!
1901 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001902
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001903 // Strftime is particular as it always uses a single 'time' argument,
1904 // so it is safe to pass a non-literal string.
1905 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00001906 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001907
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001908 // Do not emit diag when the string param is a macro expansion and the
1909 // format is either NSString or CFString. This is a hack to prevent
1910 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1911 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00001912 if (Type == FST_NSString &&
1913 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00001914 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001915
Chris Lattner655f1412009-04-29 04:59:47 +00001916 // If there are no arguments specified, warn with -Wformat-security, otherwise
1917 // warn only with -Wformat-nonliteral.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001918 if (NumArgs == format_idx+1)
1919 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001920 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001921 << OrigFormatExpr->getSourceRange();
1922 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001923 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001924 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001925 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00001926 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001927}
Ted Kremenek71895b92007-08-14 17:39:48 +00001928
Ted Kremeneke0e53132010-01-28 23:39:18 +00001929namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001930class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1931protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001932 Sema &S;
1933 const StringLiteral *FExpr;
1934 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001935 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001936 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001937 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001938 const bool HasVAListArg;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001939 const Expr * const *Args;
1940 const unsigned NumArgs;
Ted Kremenek0d277352010-01-29 01:06:55 +00001941 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001942 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001943 bool usesPositionalArgs;
1944 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001945 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00001946 Sema::VariadicCallType CallType;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001947public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001948 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001949 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00001950 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001951 Expr **args, unsigned numArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001952 unsigned formatIdx, bool inFunctionCall,
1953 Sema::VariadicCallType callType)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001954 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00001955 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
1956 Beg(beg), HasVAListArg(hasVAListArg),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001957 Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001958 usesPositionalArgs(false), atFirstArg(true),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001959 inFunctionCall(inFunctionCall), CallType(callType) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001960 CoveredArgs.resize(numDataArgs);
1961 CoveredArgs.reset();
1962 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001963
Ted Kremenek07d161f2010-01-29 01:50:07 +00001964 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001965
Ted Kremenek826a3452010-07-16 02:11:22 +00001966 void HandleIncompleteSpecifier(const char *startSpecifier,
1967 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00001968
Jordan Rosebbb6bb42012-09-08 04:00:03 +00001969 void HandleInvalidLengthModifier(
1970 const analyze_format_string::FormatSpecifier &FS,
1971 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00001972 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00001973
Hans Wennborg76517422012-02-22 10:17:01 +00001974 void HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00001975 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00001976 const char *startSpecifier, unsigned specifierLen);
1977
1978 void HandleNonStandardConversionSpecifier(
1979 const analyze_format_string::ConversionSpecifier &CS,
1980 const char *startSpecifier, unsigned specifierLen);
1981
Hans Wennborgf8562642012-03-09 10:10:54 +00001982 virtual void HandlePosition(const char *startPos, unsigned posLen);
1983
Ted Kremenekefaff192010-02-27 01:41:03 +00001984 virtual void HandleInvalidPosition(const char *startSpecifier,
1985 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001986 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001987
1988 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1989
Ted Kremeneke0e53132010-01-28 23:39:18 +00001990 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001991
Richard Trieu55733de2011-10-28 00:41:25 +00001992 template <typename Range>
1993 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1994 const Expr *ArgumentExpr,
1995 PartialDiagnostic PDiag,
1996 SourceLocation StringLoc,
1997 bool IsStringLocation, Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00001998 ArrayRef<FixItHint> Fixit = ArrayRef<FixItHint>());
Richard Trieu55733de2011-10-28 00:41:25 +00001999
Ted Kremenek826a3452010-07-16 02:11:22 +00002000protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002001 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2002 const char *startSpec,
2003 unsigned specifierLen,
2004 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00002005
2006 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2007 const char *startSpec,
2008 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002009
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002010 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00002011 CharSourceRange getSpecifierRange(const char *startSpecifier,
2012 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002013 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002014
Ted Kremenek0d277352010-01-29 01:06:55 +00002015 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00002016
2017 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2018 const analyze_format_string::ConversionSpecifier &CS,
2019 const char *startSpecifier, unsigned specifierLen,
2020 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00002021
2022 template <typename Range>
2023 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2024 bool IsStringLocation, Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002025 ArrayRef<FixItHint> Fixit = ArrayRef<FixItHint>());
Richard Trieu55733de2011-10-28 00:41:25 +00002026
2027 void CheckPositionalAndNonpositionalArgs(
2028 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002029};
2030}
2031
Ted Kremenek826a3452010-07-16 02:11:22 +00002032SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002033 return OrigFormatExpr->getSourceRange();
2034}
2035
Ted Kremenek826a3452010-07-16 02:11:22 +00002036CharSourceRange CheckFormatHandler::
2037getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002038 SourceLocation Start = getLocationOfByte(startSpecifier);
2039 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2040
2041 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002042 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002043
2044 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002045}
2046
Ted Kremenek826a3452010-07-16 02:11:22 +00002047SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002048 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002049}
2050
Ted Kremenek826a3452010-07-16 02:11:22 +00002051void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2052 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002053 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2054 getLocationOfByte(startSpecifier),
2055 /*IsStringLocation*/true,
2056 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002057}
2058
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002059void CheckFormatHandler::HandleInvalidLengthModifier(
2060 const analyze_format_string::FormatSpecifier &FS,
2061 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002062 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002063 using namespace analyze_format_string;
2064
2065 const LengthModifier &LM = FS.getLengthModifier();
2066 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2067
2068 // See if we know how to fix this length modifier.
2069 llvm::Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2070 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002071 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002072 getLocationOfByte(LM.getStart()),
2073 /*IsStringLocation*/true,
2074 getSpecifierRange(startSpecifier, specifierLen));
2075
2076 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2077 << FixedLM->toString()
2078 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2079
2080 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00002081 FixItHint Hint;
2082 if (DiagID == diag::warn_format_nonsensical_length)
2083 Hint = FixItHint::CreateRemoval(LMRange);
2084
2085 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002086 getLocationOfByte(LM.getStart()),
2087 /*IsStringLocation*/true,
2088 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002089 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002090 }
2091}
2092
Hans Wennborg76517422012-02-22 10:17:01 +00002093void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002094 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002095 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002096 using namespace analyze_format_string;
2097
2098 const LengthModifier &LM = FS.getLengthModifier();
2099 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2100
2101 // See if we know how to fix this length modifier.
2102 llvm::Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2103 if (FixedLM) {
2104 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2105 << LM.toString() << 0,
2106 getLocationOfByte(LM.getStart()),
2107 /*IsStringLocation*/true,
2108 getSpecifierRange(startSpecifier, specifierLen));
2109
2110 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2111 << FixedLM->toString()
2112 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2113
2114 } else {
2115 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2116 << LM.toString() << 0,
2117 getLocationOfByte(LM.getStart()),
2118 /*IsStringLocation*/true,
2119 getSpecifierRange(startSpecifier, specifierLen));
2120 }
Hans Wennborg76517422012-02-22 10:17:01 +00002121}
2122
2123void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2124 const analyze_format_string::ConversionSpecifier &CS,
2125 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002126 using namespace analyze_format_string;
2127
2128 // See if we know how to fix this conversion specifier.
2129 llvm::Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
2130 if (FixedCS) {
2131 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2132 << CS.toString() << /*conversion specifier*/1,
2133 getLocationOfByte(CS.getStart()),
2134 /*IsStringLocation*/true,
2135 getSpecifierRange(startSpecifier, specifierLen));
2136
2137 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2138 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2139 << FixedCS->toString()
2140 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2141 } else {
2142 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2143 << CS.toString() << /*conversion specifier*/1,
2144 getLocationOfByte(CS.getStart()),
2145 /*IsStringLocation*/true,
2146 getSpecifierRange(startSpecifier, specifierLen));
2147 }
Hans Wennborg76517422012-02-22 10:17:01 +00002148}
2149
Hans Wennborgf8562642012-03-09 10:10:54 +00002150void CheckFormatHandler::HandlePosition(const char *startPos,
2151 unsigned posLen) {
2152 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2153 getLocationOfByte(startPos),
2154 /*IsStringLocation*/true,
2155 getSpecifierRange(startPos, posLen));
2156}
2157
Ted Kremenekefaff192010-02-27 01:41:03 +00002158void
Ted Kremenek826a3452010-07-16 02:11:22 +00002159CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2160 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002161 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2162 << (unsigned) p,
2163 getLocationOfByte(startPos), /*IsStringLocation*/true,
2164 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002165}
2166
Ted Kremenek826a3452010-07-16 02:11:22 +00002167void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002168 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002169 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2170 getLocationOfByte(startPos),
2171 /*IsStringLocation*/true,
2172 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002173}
2174
Ted Kremenek826a3452010-07-16 02:11:22 +00002175void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002176 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002177 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002178 EmitFormatDiagnostic(
2179 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2180 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2181 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002182 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002183}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002184
Jordan Rose48716662012-07-19 18:10:08 +00002185// Note that this may return NULL if there was an error parsing or building
2186// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002187const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002188 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002189}
2190
2191void CheckFormatHandler::DoneProcessing() {
2192 // Does the number of data arguments exceed the number of
2193 // format conversions in the format string?
2194 if (!HasVAListArg) {
2195 // Find any arguments that weren't covered.
2196 CoveredArgs.flip();
2197 signed notCoveredArg = CoveredArgs.find_first();
2198 if (notCoveredArg >= 0) {
2199 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002200 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2201 SourceLocation Loc = E->getLocStart();
2202 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2203 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2204 Loc, /*IsStringLocation*/false,
2205 getFormatStringRange());
2206 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002207 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002208 }
2209 }
2210}
2211
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002212bool
2213CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2214 SourceLocation Loc,
2215 const char *startSpec,
2216 unsigned specifierLen,
2217 const char *csStart,
2218 unsigned csLen) {
2219
2220 bool keepGoing = true;
2221 if (argIndex < NumDataArgs) {
2222 // Consider the argument coverered, even though the specifier doesn't
2223 // make sense.
2224 CoveredArgs.set(argIndex);
2225 }
2226 else {
2227 // If argIndex exceeds the number of data arguments we
2228 // don't issue a warning because that is just a cascade of warnings (and
2229 // they may have intended '%%' anyway). We don't want to continue processing
2230 // the format string after this point, however, as we will like just get
2231 // gibberish when trying to match arguments.
2232 keepGoing = false;
2233 }
2234
Richard Trieu55733de2011-10-28 00:41:25 +00002235 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2236 << StringRef(csStart, csLen),
2237 Loc, /*IsStringLocation*/true,
2238 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002239
2240 return keepGoing;
2241}
2242
Richard Trieu55733de2011-10-28 00:41:25 +00002243void
2244CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2245 const char *startSpec,
2246 unsigned specifierLen) {
2247 EmitFormatDiagnostic(
2248 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2249 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2250}
2251
Ted Kremenek666a1972010-07-26 19:45:42 +00002252bool
2253CheckFormatHandler::CheckNumArgs(
2254 const analyze_format_string::FormatSpecifier &FS,
2255 const analyze_format_string::ConversionSpecifier &CS,
2256 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2257
2258 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002259 PartialDiagnostic PDiag = FS.usesPositionalArg()
2260 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2261 << (argIndex+1) << NumDataArgs)
2262 : S.PDiag(diag::warn_printf_insufficient_data_args);
2263 EmitFormatDiagnostic(
2264 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2265 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002266 return false;
2267 }
2268 return true;
2269}
2270
Richard Trieu55733de2011-10-28 00:41:25 +00002271template<typename Range>
2272void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2273 SourceLocation Loc,
2274 bool IsStringLocation,
2275 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002276 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002277 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002278 Loc, IsStringLocation, StringRange, FixIt);
2279}
2280
2281/// \brief If the format string is not within the funcion call, emit a note
2282/// so that the function call and string are in diagnostic messages.
2283///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002284/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002285/// call and only one diagnostic message will be produced. Otherwise, an
2286/// extra note will be emitted pointing to location of the format string.
2287///
2288/// \param ArgumentExpr the expression that is passed as the format string
2289/// argument in the function call. Used for getting locations when two
2290/// diagnostics are emitted.
2291///
2292/// \param PDiag the callee should already have provided any strings for the
2293/// diagnostic message. This function only adds locations and fixits
2294/// to diagnostics.
2295///
2296/// \param Loc primary location for diagnostic. If two diagnostics are
2297/// required, one will be at Loc and a new SourceLocation will be created for
2298/// the other one.
2299///
2300/// \param IsStringLocation if true, Loc points to the format string should be
2301/// used for the note. Otherwise, Loc points to the argument list and will
2302/// be used with PDiag.
2303///
2304/// \param StringRange some or all of the string to highlight. This is
2305/// templated so it can accept either a CharSourceRange or a SourceRange.
2306///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002307/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002308template<typename Range>
2309void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2310 const Expr *ArgumentExpr,
2311 PartialDiagnostic PDiag,
2312 SourceLocation Loc,
2313 bool IsStringLocation,
2314 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002315 ArrayRef<FixItHint> FixIt) {
2316 if (InFunctionCall) {
2317 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2318 D << StringRange;
2319 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2320 I != E; ++I) {
2321 D << *I;
2322 }
2323 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00002324 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2325 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00002326
2327 const Sema::SemaDiagnosticBuilder &Note =
2328 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2329 diag::note_format_string_defined);
2330
2331 Note << StringRange;
2332 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2333 I != E; ++I) {
2334 Note << *I;
2335 }
Richard Trieu55733de2011-10-28 00:41:25 +00002336 }
2337}
2338
Ted Kremenek826a3452010-07-16 02:11:22 +00002339//===--- CHECK: Printf format string checking ------------------------------===//
2340
2341namespace {
2342class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002343 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002344public:
2345 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2346 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002347 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002348 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002349 Expr **Args, unsigned NumArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002350 unsigned formatIdx, bool inFunctionCall,
2351 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002352 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002353 numDataArgs, beg, hasVAListArg, Args, NumArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002354 formatIdx, inFunctionCall, CallType), ObjCContext(isObjC)
2355 {}
2356
Ted Kremenek826a3452010-07-16 02:11:22 +00002357
2358 bool HandleInvalidPrintfConversionSpecifier(
2359 const analyze_printf::PrintfSpecifier &FS,
2360 const char *startSpecifier,
2361 unsigned specifierLen);
2362
2363 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2364 const char *startSpecifier,
2365 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002366 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2367 const char *StartSpecifier,
2368 unsigned SpecifierLen,
2369 const Expr *E);
2370
Ted Kremenek826a3452010-07-16 02:11:22 +00002371 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2372 const char *startSpecifier, unsigned specifierLen);
2373 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2374 const analyze_printf::OptionalAmount &Amt,
2375 unsigned type,
2376 const char *startSpecifier, unsigned specifierLen);
2377 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2378 const analyze_printf::OptionalFlag &flag,
2379 const char *startSpecifier, unsigned specifierLen);
2380 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2381 const analyze_printf::OptionalFlag &ignoredFlag,
2382 const analyze_printf::OptionalFlag &flag,
2383 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002384 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith831421f2012-06-25 20:30:08 +00002385 const Expr *E, const CharSourceRange &CSR);
2386
Ted Kremenek826a3452010-07-16 02:11:22 +00002387};
2388}
2389
2390bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2391 const analyze_printf::PrintfSpecifier &FS,
2392 const char *startSpecifier,
2393 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002394 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002395 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002396
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002397 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2398 getLocationOfByte(CS.getStart()),
2399 startSpecifier, specifierLen,
2400 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002401}
2402
Ted Kremenek826a3452010-07-16 02:11:22 +00002403bool CheckPrintfHandler::HandleAmount(
2404 const analyze_format_string::OptionalAmount &Amt,
2405 unsigned k, const char *startSpecifier,
2406 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002407
2408 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002409 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002410 unsigned argIndex = Amt.getArgIndex();
2411 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002412 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2413 << k,
2414 getLocationOfByte(Amt.getStart()),
2415 /*IsStringLocation*/true,
2416 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002417 // Don't do any more checking. We will just emit
2418 // spurious errors.
2419 return false;
2420 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002421
Ted Kremenek0d277352010-01-29 01:06:55 +00002422 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002423 // Although not in conformance with C99, we also allow the argument to be
2424 // an 'unsigned int' as that is a reasonably safe case. GCC also
2425 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002426 CoveredArgs.set(argIndex);
2427 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002428 if (!Arg)
2429 return false;
2430
Ted Kremenek0d277352010-01-29 01:06:55 +00002431 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002432
Hans Wennborgf3749f42012-08-07 08:11:26 +00002433 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2434 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002435
Hans Wennborgf3749f42012-08-07 08:11:26 +00002436 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002437 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002438 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002439 << T << Arg->getSourceRange(),
2440 getLocationOfByte(Amt.getStart()),
2441 /*IsStringLocation*/true,
2442 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002443 // Don't do any more checking. We will just emit
2444 // spurious errors.
2445 return false;
2446 }
2447 }
2448 }
2449 return true;
2450}
Ted Kremenek0d277352010-01-29 01:06:55 +00002451
Tom Caree4ee9662010-06-17 19:00:27 +00002452void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002453 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002454 const analyze_printf::OptionalAmount &Amt,
2455 unsigned type,
2456 const char *startSpecifier,
2457 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002458 const analyze_printf::PrintfConversionSpecifier &CS =
2459 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002460
Richard Trieu55733de2011-10-28 00:41:25 +00002461 FixItHint fixit =
2462 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2463 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2464 Amt.getConstantLength()))
2465 : FixItHint();
2466
2467 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2468 << type << CS.toString(),
2469 getLocationOfByte(Amt.getStart()),
2470 /*IsStringLocation*/true,
2471 getSpecifierRange(startSpecifier, specifierLen),
2472 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002473}
2474
Ted Kremenek826a3452010-07-16 02:11:22 +00002475void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002476 const analyze_printf::OptionalFlag &flag,
2477 const char *startSpecifier,
2478 unsigned specifierLen) {
2479 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002480 const analyze_printf::PrintfConversionSpecifier &CS =
2481 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002482 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2483 << flag.toString() << CS.toString(),
2484 getLocationOfByte(flag.getPosition()),
2485 /*IsStringLocation*/true,
2486 getSpecifierRange(startSpecifier, specifierLen),
2487 FixItHint::CreateRemoval(
2488 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002489}
2490
2491void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002492 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002493 const analyze_printf::OptionalFlag &ignoredFlag,
2494 const analyze_printf::OptionalFlag &flag,
2495 const char *startSpecifier,
2496 unsigned specifierLen) {
2497 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002498 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2499 << ignoredFlag.toString() << flag.toString(),
2500 getLocationOfByte(ignoredFlag.getPosition()),
2501 /*IsStringLocation*/true,
2502 getSpecifierRange(startSpecifier, specifierLen),
2503 FixItHint::CreateRemoval(
2504 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002505}
2506
Richard Smith831421f2012-06-25 20:30:08 +00002507// Determines if the specified is a C++ class or struct containing
2508// a member with the specified name and kind (e.g. a CXXMethodDecl named
2509// "c_str()").
2510template<typename MemberKind>
2511static llvm::SmallPtrSet<MemberKind*, 1>
2512CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2513 const RecordType *RT = Ty->getAs<RecordType>();
2514 llvm::SmallPtrSet<MemberKind*, 1> Results;
2515
2516 if (!RT)
2517 return Results;
2518 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2519 if (!RD)
2520 return Results;
2521
2522 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2523 Sema::LookupMemberName);
2524
2525 // We just need to include all members of the right kind turned up by the
2526 // filter, at this point.
2527 if (S.LookupQualifiedName(R, RT->getDecl()))
2528 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2529 NamedDecl *decl = (*I)->getUnderlyingDecl();
2530 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2531 Results.insert(FK);
2532 }
2533 return Results;
2534}
2535
2536// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002537// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002538// Returns true when a c_str() conversion method is found.
2539bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgf3749f42012-08-07 08:11:26 +00002540 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith831421f2012-06-25 20:30:08 +00002541 const CharSourceRange &CSR) {
2542 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2543
2544 MethodSet Results =
2545 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2546
2547 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2548 MI != ME; ++MI) {
2549 const CXXMethodDecl *Method = *MI;
2550 if (Method->getNumParams() == 0 &&
Hans Wennborgf3749f42012-08-07 08:11:26 +00002551 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith831421f2012-06-25 20:30:08 +00002552 // FIXME: Suggest parens if the expression needs them.
2553 SourceLocation EndLoc =
2554 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2555 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2556 << "c_str()"
2557 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2558 return true;
2559 }
2560 }
2561
2562 return false;
2563}
2564
Ted Kremeneke0e53132010-01-28 23:39:18 +00002565bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002566CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002567 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002568 const char *startSpecifier,
2569 unsigned specifierLen) {
2570
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002571 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002572 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002573 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002574
Ted Kremenekbaa40062010-07-19 22:01:06 +00002575 if (FS.consumesDataArgument()) {
2576 if (atFirstArg) {
2577 atFirstArg = false;
2578 usesPositionalArgs = FS.usesPositionalArg();
2579 }
2580 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002581 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2582 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002583 return false;
2584 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002585 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002586
Ted Kremenekefaff192010-02-27 01:41:03 +00002587 // First check if the field width, precision, and conversion specifier
2588 // have matching data arguments.
2589 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2590 startSpecifier, specifierLen)) {
2591 return false;
2592 }
2593
2594 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2595 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002596 return false;
2597 }
2598
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002599 if (!CS.consumesDataArgument()) {
2600 // FIXME: Technically specifying a precision or field width here
2601 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002602 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002603 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002604
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002605 // Consume the argument.
2606 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002607 if (argIndex < NumDataArgs) {
2608 // The check to see if the argIndex is valid will come later.
2609 // We set the bit here because we may exit early from this
2610 // function if we encounter some other error.
2611 CoveredArgs.set(argIndex);
2612 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002613
2614 // Check for using an Objective-C specific conversion specifier
2615 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002616 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002617 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2618 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002619 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002620
Tom Caree4ee9662010-06-17 19:00:27 +00002621 // Check for invalid use of field width
2622 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002623 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002624 startSpecifier, specifierLen);
2625 }
2626
2627 // Check for invalid use of precision
2628 if (!FS.hasValidPrecision()) {
2629 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2630 startSpecifier, specifierLen);
2631 }
2632
2633 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002634 if (!FS.hasValidThousandsGroupingPrefix())
2635 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002636 if (!FS.hasValidLeadingZeros())
2637 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2638 if (!FS.hasValidPlusPrefix())
2639 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002640 if (!FS.hasValidSpacePrefix())
2641 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002642 if (!FS.hasValidAlternativeForm())
2643 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2644 if (!FS.hasValidLeftJustified())
2645 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2646
2647 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002648 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2649 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2650 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002651 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2652 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2653 startSpecifier, specifierLen);
2654
2655 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002656 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00002657 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2658 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002659 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00002660 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002661 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00002662 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2663 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00002664
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002665 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
2666 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2667
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002668 // The remaining checks depend on the data arguments.
2669 if (HasVAListArg)
2670 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002671
Ted Kremenek666a1972010-07-26 19:45:42 +00002672 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002673 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002674
Jordan Rose48716662012-07-19 18:10:08 +00002675 const Expr *Arg = getDataArg(argIndex);
2676 if (!Arg)
2677 return true;
2678
2679 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00002680}
2681
Jordan Roseec087352012-09-05 22:56:26 +00002682static bool requiresParensToAddCast(const Expr *E) {
2683 // FIXME: We should have a general way to reason about operator
2684 // precedence and whether parens are actually needed here.
2685 // Take care of a few common cases where they aren't.
2686 const Expr *Inside = E->IgnoreImpCasts();
2687 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
2688 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
2689
2690 switch (Inside->getStmtClass()) {
2691 case Stmt::ArraySubscriptExprClass:
2692 case Stmt::CallExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002693 case Stmt::CharacterLiteralClass:
2694 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002695 case Stmt::DeclRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002696 case Stmt::FloatingLiteralClass:
2697 case Stmt::IntegerLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00002698 case Stmt::MemberExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002699 case Stmt::ObjCArrayLiteralClass:
2700 case Stmt::ObjCBoolLiteralExprClass:
2701 case Stmt::ObjCBoxedExprClass:
2702 case Stmt::ObjCDictionaryLiteralClass:
2703 case Stmt::ObjCEncodeExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002704 case Stmt::ObjCIvarRefExprClass:
2705 case Stmt::ObjCMessageExprClass:
2706 case Stmt::ObjCPropertyRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002707 case Stmt::ObjCStringLiteralClass:
2708 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002709 case Stmt::ParenExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002710 case Stmt::StringLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00002711 case Stmt::UnaryOperatorClass:
2712 return false;
2713 default:
2714 return true;
2715 }
2716}
2717
Richard Smith831421f2012-06-25 20:30:08 +00002718bool
2719CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2720 const char *StartSpecifier,
2721 unsigned SpecifierLen,
2722 const Expr *E) {
2723 using namespace analyze_format_string;
2724 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002725 // Now type check the data expression that matches the
2726 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00002727 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
2728 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00002729 if (!AT.isValid())
2730 return true;
Jordan Roseec087352012-09-05 22:56:26 +00002731
Jordan Rose448ac3e2012-12-05 18:44:40 +00002732 QualType ExprTy = E->getType();
2733 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002734 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00002735
Jordan Rose614a8652012-09-05 22:56:19 +00002736 // Look through argument promotions for our error message's reported type.
2737 // This includes the integral and floating promotions, but excludes array
2738 // and function pointer decay; seeing that an argument intended to be a
2739 // string has type 'char [6]' is probably more confusing than 'char *'.
2740 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2741 if (ICE->getCastKind() == CK_IntegralCast ||
2742 ICE->getCastKind() == CK_FloatingCast) {
2743 E = ICE->getSubExpr();
Jordan Rose448ac3e2012-12-05 18:44:40 +00002744 ExprTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00002745
2746 // Check if we didn't match because of an implicit cast from a 'char'
2747 // or 'short' to an 'int'. This is done because printf is a varargs
2748 // function.
2749 if (ICE->getType() == S.Context.IntTy ||
2750 ICE->getType() == S.Context.UnsignedIntTy) {
2751 // All further checking is done on the subexpression.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002752 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002753 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002754 }
Jordan Roseee0259d2012-06-04 22:48:57 +00002755 }
Jordan Rose448ac3e2012-12-05 18:44:40 +00002756 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
2757 // Special case for 'a', which has type 'int' in C.
2758 // Note, however, that we do /not/ want to treat multibyte constants like
2759 // 'MooV' as characters! This form is deprecated but still exists.
2760 if (ExprTy == S.Context.IntTy)
2761 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
2762 ExprTy = S.Context.CharTy;
Jordan Rose614a8652012-09-05 22:56:19 +00002763 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002764
Jordan Rose2cd34402012-12-05 18:44:49 +00002765 // %C in an Objective-C context prints a unichar, not a wchar_t.
2766 // If the argument is an integer of some kind, believe the %C and suggest
2767 // a cast instead of changing the conversion specifier.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002768 QualType IntendedTy = ExprTy;
Jordan Rose2cd34402012-12-05 18:44:49 +00002769 if (ObjCContext &&
2770 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
2771 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
2772 !ExprTy->isCharType()) {
2773 // 'unichar' is defined as a typedef of unsigned short, but we should
2774 // prefer using the typedef if it is visible.
2775 IntendedTy = S.Context.UnsignedShortTy;
2776
2777 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
2778 Sema::LookupOrdinaryName);
2779 if (S.LookupName(Result, S.getCurScope())) {
2780 NamedDecl *ND = Result.getFoundDecl();
2781 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
2782 if (TD->getUnderlyingType() == IntendedTy)
2783 IntendedTy = S.Context.getTypedefType(TD);
2784 }
2785 }
2786 }
2787
2788 // Special-case some of Darwin's platform-independence types by suggesting
2789 // casts to primitive types that are known to be large enough.
2790 bool ShouldNotPrintDirectly = false;
Jordan Roseec087352012-09-05 22:56:26 +00002791 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Jordan Roseec087352012-09-05 22:56:26 +00002792 if (const TypedefType *UserTy = IntendedTy->getAs<TypedefType>()) {
2793 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose2cd34402012-12-05 18:44:49 +00002794 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseec087352012-09-05 22:56:26 +00002795 .Case("NSInteger", S.Context.LongTy)
2796 .Case("NSUInteger", S.Context.UnsignedLongTy)
2797 .Case("SInt32", S.Context.IntTy)
2798 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose2cd34402012-12-05 18:44:49 +00002799 .Default(QualType());
2800
2801 if (!CastTy.isNull()) {
2802 ShouldNotPrintDirectly = true;
2803 IntendedTy = CastTy;
2804 }
Jordan Roseec087352012-09-05 22:56:26 +00002805 }
2806 }
2807
Jordan Rose614a8652012-09-05 22:56:19 +00002808 // We may be able to offer a FixItHint if it is a supported type.
2809 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00002810 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00002811 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002812
Jordan Rose614a8652012-09-05 22:56:19 +00002813 if (success) {
2814 // Get the fix string from the fixed format specifier
2815 SmallString<16> buf;
2816 llvm::raw_svector_ostream os(buf);
2817 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002818
Jordan Roseec087352012-09-05 22:56:26 +00002819 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
2820
Jordan Rose2cd34402012-12-05 18:44:49 +00002821 if (IntendedTy == ExprTy) {
2822 // In this case, the specifier is wrong and should be changed to match
2823 // the argument.
2824 EmitFormatDiagnostic(
2825 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2826 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
2827 << E->getSourceRange(),
2828 E->getLocStart(),
2829 /*IsStringLocation*/false,
2830 SpecRange,
2831 FixItHint::CreateReplacement(SpecRange, os.str()));
2832
2833 } else {
Jordan Roseec087352012-09-05 22:56:26 +00002834 // The canonical type for formatting this value is different from the
2835 // actual type of the expression. (This occurs, for example, with Darwin's
2836 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
2837 // should be printed as 'long' for 64-bit compatibility.)
2838 // Rather than emitting a normal format/argument mismatch, we want to
2839 // add a cast to the recommended type (and correct the format string
2840 // if necessary).
2841 SmallString<16> CastBuf;
2842 llvm::raw_svector_ostream CastFix(CastBuf);
2843 CastFix << "(";
2844 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
2845 CastFix << ")";
2846
2847 SmallVector<FixItHint,4> Hints;
2848 if (!AT.matchesType(S.Context, IntendedTy))
2849 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
2850
2851 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
2852 // If there's already a cast present, just replace it.
2853 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
2854 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
2855
2856 } else if (!requiresParensToAddCast(E)) {
2857 // If the expression has high enough precedence,
2858 // just write the C-style cast.
2859 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2860 CastFix.str()));
2861 } else {
2862 // Otherwise, add parens around the expression as well as the cast.
2863 CastFix << "(";
2864 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2865 CastFix.str()));
2866
2867 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
2868 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
2869 }
2870
Jordan Rose2cd34402012-12-05 18:44:49 +00002871 if (ShouldNotPrintDirectly) {
2872 // The expression has a type that should not be printed directly.
2873 // We extract the name from the typedef because we don't want to show
2874 // the underlying type in the diagnostic.
2875 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseec087352012-09-05 22:56:26 +00002876
Jordan Rose2cd34402012-12-05 18:44:49 +00002877 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
2878 << Name << IntendedTy
2879 << E->getSourceRange(),
2880 E->getLocStart(), /*IsStringLocation=*/false,
2881 SpecRange, Hints);
2882 } else {
2883 // In this case, the expression could be printed using a different
2884 // specifier, but we've decided that the specifier is probably correct
2885 // and we should cast instead. Just use the normal warning message.
2886 EmitFormatDiagnostic(
2887 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2888 << AT.getRepresentativeTypeName(S.Context) << ExprTy
2889 << E->getSourceRange(),
2890 E->getLocStart(), /*IsStringLocation*/false,
2891 SpecRange, Hints);
2892 }
Jordan Roseec087352012-09-05 22:56:26 +00002893 }
Jordan Rose614a8652012-09-05 22:56:19 +00002894 } else {
2895 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
2896 SpecifierLen);
2897 // Since the warning for passing non-POD types to variadic functions
2898 // was deferred until now, we emit a warning for non-POD
2899 // arguments here.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002900 if (S.isValidVarArgType(ExprTy) == Sema::VAK_Invalid) {
Jordan Rose614a8652012-09-05 22:56:19 +00002901 unsigned DiagKind;
Jordan Rose448ac3e2012-12-05 18:44:40 +00002902 if (ExprTy->isObjCObjectType())
Jordan Rose614a8652012-09-05 22:56:19 +00002903 DiagKind = diag::err_cannot_pass_objc_interface_to_vararg_format;
2904 else
2905 DiagKind = diag::warn_non_pod_vararg_with_format_string;
2906
2907 EmitFormatDiagnostic(
2908 S.PDiag(DiagKind)
2909 << S.getLangOpts().CPlusPlus0x
Jordan Rose448ac3e2012-12-05 18:44:40 +00002910 << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00002911 << CallType
2912 << AT.getRepresentativeTypeName(S.Context)
2913 << CSR
2914 << E->getSourceRange(),
2915 E->getLocStart(), /*IsStringLocation*/false, CSR);
2916
2917 checkForCStrMembers(AT, E, CSR);
2918 } else
Richard Trieu55733de2011-10-28 00:41:25 +00002919 EmitFormatDiagnostic(
2920 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Jordan Rose448ac3e2012-12-05 18:44:40 +00002921 << AT.getRepresentativeTypeName(S.Context) << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00002922 << CSR
Richard Smith831421f2012-06-25 20:30:08 +00002923 << E->getSourceRange(),
Jordan Rose614a8652012-09-05 22:56:19 +00002924 E->getLocStart(), /*IsStringLocation*/false, CSR);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002925 }
2926
Ted Kremeneke0e53132010-01-28 23:39:18 +00002927 return true;
2928}
2929
Ted Kremenek826a3452010-07-16 02:11:22 +00002930//===--- CHECK: Scanf format string checking ------------------------------===//
2931
2932namespace {
2933class CheckScanfHandler : public CheckFormatHandler {
2934public:
2935 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2936 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002937 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002938 Expr **Args, unsigned NumArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002939 unsigned formatIdx, bool inFunctionCall,
2940 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002941 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002942 numDataArgs, beg, hasVAListArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002943 Args, NumArgs, formatIdx, inFunctionCall, CallType)
2944 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002945
2946 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2947 const char *startSpecifier,
2948 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002949
2950 bool HandleInvalidScanfConversionSpecifier(
2951 const analyze_scanf::ScanfSpecifier &FS,
2952 const char *startSpecifier,
2953 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002954
2955 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002956};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002957}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002958
Ted Kremenekb7c21012010-07-16 18:28:03 +00002959void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2960 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002961 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2962 getLocationOfByte(end), /*IsStringLocation*/true,
2963 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002964}
2965
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002966bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2967 const analyze_scanf::ScanfSpecifier &FS,
2968 const char *startSpecifier,
2969 unsigned specifierLen) {
2970
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002971 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002972 FS.getConversionSpecifier();
2973
2974 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2975 getLocationOfByte(CS.getStart()),
2976 startSpecifier, specifierLen,
2977 CS.getStart(), CS.getLength());
2978}
2979
Ted Kremenek826a3452010-07-16 02:11:22 +00002980bool CheckScanfHandler::HandleScanfSpecifier(
2981 const analyze_scanf::ScanfSpecifier &FS,
2982 const char *startSpecifier,
2983 unsigned specifierLen) {
2984
2985 using namespace analyze_scanf;
2986 using namespace analyze_format_string;
2987
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002988 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002989
Ted Kremenekbaa40062010-07-19 22:01:06 +00002990 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2991 // be used to decide if we are using positional arguments consistently.
2992 if (FS.consumesDataArgument()) {
2993 if (atFirstArg) {
2994 atFirstArg = false;
2995 usesPositionalArgs = FS.usesPositionalArg();
2996 }
2997 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002998 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2999 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003000 return false;
3001 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003002 }
3003
3004 // Check if the field with is non-zero.
3005 const OptionalAmount &Amt = FS.getFieldWidth();
3006 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3007 if (Amt.getConstantAmount() == 0) {
3008 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3009 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00003010 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3011 getLocationOfByte(Amt.getStart()),
3012 /*IsStringLocation*/true, R,
3013 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00003014 }
3015 }
3016
3017 if (!FS.consumesDataArgument()) {
3018 // FIXME: Technically specifying a precision or field width here
3019 // makes no sense. Worth issuing a warning at some point.
3020 return true;
3021 }
3022
3023 // Consume the argument.
3024 unsigned argIndex = FS.getArgIndex();
3025 if (argIndex < NumDataArgs) {
3026 // The check to see if the argIndex is valid will come later.
3027 // We set the bit here because we may exit early from this
3028 // function if we encounter some other error.
3029 CoveredArgs.set(argIndex);
3030 }
3031
Ted Kremenek1e51c202010-07-20 20:04:47 +00003032 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003033 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003034 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3035 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003036 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003037 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003038 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003039 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3040 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00003041
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003042 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3043 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3044
Ted Kremenek826a3452010-07-16 02:11:22 +00003045 // The remaining checks depend on the data arguments.
3046 if (HasVAListArg)
3047 return true;
3048
Ted Kremenek666a1972010-07-26 19:45:42 +00003049 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00003050 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00003051
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003052 // Check that the argument type matches the format specifier.
3053 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00003054 if (!Ex)
3055 return true;
3056
Hans Wennborg58e1e542012-08-07 08:59:46 +00003057 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3058 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003059 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00003060 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00003061 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003062
3063 if (success) {
3064 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003065 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003066 llvm::raw_svector_ostream os(buf);
3067 fixedFS.toString(os);
3068
3069 EmitFormatDiagnostic(
3070 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003071 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003072 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003073 Ex->getLocStart(),
3074 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003075 getSpecifierRange(startSpecifier, specifierLen),
3076 FixItHint::CreateReplacement(
3077 getSpecifierRange(startSpecifier, specifierLen),
3078 os.str()));
3079 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003080 EmitFormatDiagnostic(
3081 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003082 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003083 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003084 Ex->getLocStart(),
3085 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003086 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003087 }
3088 }
3089
Ted Kremenek826a3452010-07-16 02:11:22 +00003090 return true;
3091}
3092
3093void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003094 const Expr *OrigFormatExpr,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003095 Expr **Args, unsigned NumArgs,
3096 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003097 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003098 bool inFunctionCall, VariadicCallType CallType) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003099
Ted Kremeneke0e53132010-01-28 23:39:18 +00003100 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00003101 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003102 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003103 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003104 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3105 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003106 return;
3107 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003108
Ted Kremeneke0e53132010-01-28 23:39:18 +00003109 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00003110 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003111 const char *Str = StrRef.data();
3112 unsigned StrLen = StrRef.size();
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003113 const unsigned numDataArgs = NumArgs - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00003114
Ted Kremeneke0e53132010-01-28 23:39:18 +00003115 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00003116 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00003117 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003118 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003119 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3120 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003121 return;
3122 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003123
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003124 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003125 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003126 numDataArgs, (Type == FST_NSString),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003127 Str, HasVAListArg, Args, NumArgs, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003128 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003129
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003130 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003131 getLangOpts(),
3132 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003133 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003134 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00003135 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003136 Str, HasVAListArg, Args, NumArgs, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003137 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003138
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003139 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003140 getLangOpts(),
3141 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003142 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003143 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00003144}
3145
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003146//===--- CHECK: Standard memory functions ---------------------------------===//
3147
Douglas Gregor2a053a32011-05-03 20:05:22 +00003148/// \brief Determine whether the given type is a dynamic class type (e.g.,
3149/// whether it has a vtable).
3150static bool isDynamicClassType(QualType T) {
3151 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3152 if (CXXRecordDecl *Definition = Record->getDefinition())
3153 if (Definition->isDynamicClass())
3154 return true;
3155
3156 return false;
3157}
3158
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003159/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00003160/// otherwise returns NULL.
3161static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00003162 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00003163 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3164 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3165 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003166
Chandler Carruth000d4282011-06-16 09:09:40 +00003167 return 0;
3168}
3169
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003170/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00003171static QualType getSizeOfArgType(const Expr* E) {
3172 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3173 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3174 if (SizeOf->getKind() == clang::UETT_SizeOf)
3175 return SizeOf->getTypeOfArgument();
3176
3177 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00003178}
3179
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003180/// \brief Check for dangerous or invalid arguments to memset().
3181///
Chandler Carruth929f0132011-06-03 06:23:57 +00003182/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003183/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3184/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003185///
3186/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003187void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00003188 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003189 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00003190 assert(BId != 0);
3191
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003192 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00003193 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00003194 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00003195 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003196 return;
3197
Anna Zaks0a151a12012-01-17 00:37:07 +00003198 unsigned LastArg = (BId == Builtin::BImemset ||
3199 BId == Builtin::BIstrndup ? 1 : 2);
3200 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00003201 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00003202
3203 // We have special checking when the length is a sizeof expression.
3204 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3205 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3206 llvm::FoldingSetNodeID SizeOfArgID;
3207
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003208 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3209 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003210 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003211
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003212 QualType DestTy = Dest->getType();
3213 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3214 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00003215
Chandler Carruth000d4282011-06-16 09:09:40 +00003216 // Never warn about void type pointers. This can be used to suppress
3217 // false positives.
3218 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003219 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003220
Chandler Carruth000d4282011-06-16 09:09:40 +00003221 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3222 // actually comparing the expressions for equality. Because computing the
3223 // expression IDs can be expensive, we only do this if the diagnostic is
3224 // enabled.
3225 if (SizeOfArg &&
3226 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3227 SizeOfArg->getExprLoc())) {
3228 // We only compute IDs for expressions if the warning is enabled, and
3229 // cache the sizeof arg's ID.
3230 if (SizeOfArgID == llvm::FoldingSetNodeID())
3231 SizeOfArg->Profile(SizeOfArgID, Context, true);
3232 llvm::FoldingSetNodeID DestID;
3233 Dest->Profile(DestID, Context, true);
3234 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00003235 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3236 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00003237 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003238 StringRef ReadableName = FnName->getName();
3239
Chandler Carruth000d4282011-06-16 09:09:40 +00003240 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00003241 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00003242 ActionIdx = 1; // If its an address-of operator, just remove it.
3243 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
3244 ActionIdx = 2; // If the pointee's size is sizeof(char),
3245 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003246
3247 // If the function is defined as a builtin macro, do not show macro
3248 // expansion.
3249 SourceLocation SL = SizeOfArg->getExprLoc();
3250 SourceRange DSR = Dest->getSourceRange();
3251 SourceRange SSR = SizeOfArg->getSourceRange();
3252 SourceManager &SM = PP.getSourceManager();
3253
3254 if (SM.isMacroArgExpansion(SL)) {
3255 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3256 SL = SM.getSpellingLoc(SL);
3257 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3258 SM.getSpellingLoc(DSR.getEnd()));
3259 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3260 SM.getSpellingLoc(SSR.getEnd()));
3261 }
3262
Anna Zaks90c78322012-05-30 23:14:52 +00003263 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00003264 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00003265 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00003266 << PointeeTy
3267 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00003268 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00003269 << SSR);
3270 DiagRuntimeBehavior(SL, SizeOfArg,
3271 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3272 << ActionIdx
3273 << SSR);
3274
Chandler Carruth000d4282011-06-16 09:09:40 +00003275 break;
3276 }
3277 }
3278
3279 // Also check for cases where the sizeof argument is the exact same
3280 // type as the memory argument, and where it points to a user-defined
3281 // record type.
3282 if (SizeOfArgTy != QualType()) {
3283 if (PointeeTy->isRecordType() &&
3284 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3285 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3286 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3287 << FnName << SizeOfArgTy << ArgIdx
3288 << PointeeTy << Dest->getSourceRange()
3289 << LenExpr->getSourceRange());
3290 break;
3291 }
Nico Webere4a1c642011-06-14 16:14:58 +00003292 }
3293
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003294 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00003295 if (isDynamicClassType(PointeeTy)) {
3296
3297 unsigned OperationType = 0;
3298 // "overwritten" if we're warning about the destination for any call
3299 // but memcmp; otherwise a verb appropriate to the call.
3300 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3301 if (BId == Builtin::BImemcpy)
3302 OperationType = 1;
3303 else if(BId == Builtin::BImemmove)
3304 OperationType = 2;
3305 else if (BId == Builtin::BImemcmp)
3306 OperationType = 3;
3307 }
3308
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003309 DiagRuntimeBehavior(
3310 Dest->getExprLoc(), Dest,
3311 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003312 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003313 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003314 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003315 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003316 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3317 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003318 DiagRuntimeBehavior(
3319 Dest->getExprLoc(), Dest,
3320 PDiag(diag::warn_arc_object_memaccess)
3321 << ArgIdx << FnName << PointeeTy
3322 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003323 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003324 continue;
John McCallf85e1932011-06-15 23:02:42 +00003325
3326 DiagRuntimeBehavior(
3327 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003328 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003329 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3330 break;
3331 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003332 }
3333}
3334
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003335// A little helper routine: ignore addition and subtraction of integer literals.
3336// This intentionally does not ignore all integer constant expressions because
3337// we don't want to remove sizeof().
3338static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3339 Ex = Ex->IgnoreParenCasts();
3340
3341 for (;;) {
3342 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3343 if (!BO || !BO->isAdditiveOp())
3344 break;
3345
3346 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3347 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3348
3349 if (isa<IntegerLiteral>(RHS))
3350 Ex = LHS;
3351 else if (isa<IntegerLiteral>(LHS))
3352 Ex = RHS;
3353 else
3354 break;
3355 }
3356
3357 return Ex;
3358}
3359
Anna Zaks0f38ace2012-08-08 21:42:23 +00003360static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3361 ASTContext &Context) {
3362 // Only handle constant-sized or VLAs, but not flexible members.
3363 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3364 // Only issue the FIXIT for arrays of size > 1.
3365 if (CAT->getSize().getSExtValue() <= 1)
3366 return false;
3367 } else if (!Ty->isVariableArrayType()) {
3368 return false;
3369 }
3370 return true;
3371}
3372
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003373// Warn if the user has made the 'size' argument to strlcpy or strlcat
3374// be the size of the source, instead of the destination.
3375void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3376 IdentifierInfo *FnName) {
3377
3378 // Don't crash if the user has the wrong number of arguments
3379 if (Call->getNumArgs() != 3)
3380 return;
3381
3382 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3383 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3384 const Expr *CompareWithSrc = NULL;
3385
3386 // Look for 'strlcpy(dst, x, sizeof(x))'
3387 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3388 CompareWithSrc = Ex;
3389 else {
3390 // Look for 'strlcpy(dst, x, strlen(x))'
3391 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003392 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003393 && SizeCall->getNumArgs() == 1)
3394 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3395 }
3396 }
3397
3398 if (!CompareWithSrc)
3399 return;
3400
3401 // Determine if the argument to sizeof/strlen is equal to the source
3402 // argument. In principle there's all kinds of things you could do
3403 // here, for instance creating an == expression and evaluating it with
3404 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3405 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3406 if (!SrcArgDRE)
3407 return;
3408
3409 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3410 if (!CompareWithSrcDRE ||
3411 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3412 return;
3413
3414 const Expr *OriginalSizeArg = Call->getArg(2);
3415 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3416 << OriginalSizeArg->getSourceRange() << FnName;
3417
3418 // Output a FIXIT hint if the destination is an array (rather than a
3419 // pointer to an array). This could be enhanced to handle some
3420 // pointers if we know the actual size, like if DstArg is 'array+2'
3421 // we could say 'sizeof(array)-2'.
3422 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00003423 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00003424 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00003425
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003426 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003427 llvm::raw_svector_ostream OS(sizeString);
3428 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003429 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003430 OS << ")";
3431
3432 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3433 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3434 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003435}
3436
Anna Zaksc36bedc2012-02-01 19:08:57 +00003437/// Check if two expressions refer to the same declaration.
3438static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3439 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3440 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3441 return D1->getDecl() == D2->getDecl();
3442 return false;
3443}
3444
3445static const Expr *getStrlenExprArg(const Expr *E) {
3446 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3447 const FunctionDecl *FD = CE->getDirectCallee();
3448 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3449 return 0;
3450 return CE->getArg(0)->IgnoreParenCasts();
3451 }
3452 return 0;
3453}
3454
3455// Warn on anti-patterns as the 'size' argument to strncat.
3456// The correct size argument should look like following:
3457// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3458void Sema::CheckStrncatArguments(const CallExpr *CE,
3459 IdentifierInfo *FnName) {
3460 // Don't crash if the user has the wrong number of arguments.
3461 if (CE->getNumArgs() < 3)
3462 return;
3463 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3464 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3465 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3466
3467 // Identify common expressions, which are wrongly used as the size argument
3468 // to strncat and may lead to buffer overflows.
3469 unsigned PatternType = 0;
3470 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3471 // - sizeof(dst)
3472 if (referToTheSameDecl(SizeOfArg, DstArg))
3473 PatternType = 1;
3474 // - sizeof(src)
3475 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3476 PatternType = 2;
3477 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3478 if (BE->getOpcode() == BO_Sub) {
3479 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3480 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3481 // - sizeof(dst) - strlen(dst)
3482 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3483 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3484 PatternType = 1;
3485 // - sizeof(src) - (anything)
3486 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3487 PatternType = 2;
3488 }
3489 }
3490
3491 if (PatternType == 0)
3492 return;
3493
Anna Zaksafdb0412012-02-03 01:27:37 +00003494 // Generate the diagnostic.
3495 SourceLocation SL = LenArg->getLocStart();
3496 SourceRange SR = LenArg->getSourceRange();
3497 SourceManager &SM = PP.getSourceManager();
3498
3499 // If the function is defined as a builtin macro, do not show macro expansion.
3500 if (SM.isMacroArgExpansion(SL)) {
3501 SL = SM.getSpellingLoc(SL);
3502 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3503 SM.getSpellingLoc(SR.getEnd()));
3504 }
3505
Anna Zaks0f38ace2012-08-08 21:42:23 +00003506 // Check if the destination is an array (rather than a pointer to an array).
3507 QualType DstTy = DstArg->getType();
3508 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3509 Context);
3510 if (!isKnownSizeArray) {
3511 if (PatternType == 1)
3512 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3513 else
3514 Diag(SL, diag::warn_strncat_src_size) << SR;
3515 return;
3516 }
3517
Anna Zaksc36bedc2012-02-01 19:08:57 +00003518 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003519 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003520 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003521 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003522
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003523 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003524 llvm::raw_svector_ostream OS(sizeString);
3525 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003526 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003527 OS << ") - ";
3528 OS << "strlen(";
Richard Smithd1420c62012-08-16 03:56:14 +00003529 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003530 OS << ") - 1";
3531
Anna Zaksafdb0412012-02-03 01:27:37 +00003532 Diag(SL, diag::note_strncat_wrong_size)
3533 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003534}
3535
Ted Kremenek06de2762007-08-17 16:46:58 +00003536//===--- CHECK: Return Address of Stack Variable --------------------------===//
3537
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003538static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3539 Decl *ParentDecl);
3540static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3541 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003542
3543/// CheckReturnStackAddr - Check if a return statement returns the address
3544/// of a stack variable.
3545void
3546Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3547 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003548
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003549 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003550 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003551
3552 // Perform checking for returned stack addresses, local blocks,
3553 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003554 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003555 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003556 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003557 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003558 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003559 }
3560
3561 if (stackE == 0)
3562 return; // Nothing suspicious was found.
3563
3564 SourceLocation diagLoc;
3565 SourceRange diagRange;
3566 if (refVars.empty()) {
3567 diagLoc = stackE->getLocStart();
3568 diagRange = stackE->getSourceRange();
3569 } else {
3570 // We followed through a reference variable. 'stackE' contains the
3571 // problematic expression but we will warn at the return statement pointing
3572 // at the reference variable. We will later display the "trail" of
3573 // reference variables using notes.
3574 diagLoc = refVars[0]->getLocStart();
3575 diagRange = refVars[0]->getSourceRange();
3576 }
3577
3578 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3579 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3580 : diag::warn_ret_stack_addr)
3581 << DR->getDecl()->getDeclName() << diagRange;
3582 } else if (isa<BlockExpr>(stackE)) { // local block.
3583 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3584 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3585 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3586 } else { // local temporary.
3587 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3588 : diag::warn_ret_local_temp_addr)
3589 << diagRange;
3590 }
3591
3592 // Display the "trail" of reference variables that we followed until we
3593 // found the problematic expression using notes.
3594 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3595 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3596 // If this var binds to another reference var, show the range of the next
3597 // var, otherwise the var binds to the problematic expression, in which case
3598 // show the range of the expression.
3599 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3600 : stackE->getSourceRange();
3601 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3602 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003603 }
3604}
3605
3606/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3607/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003608/// to a location on the stack, a local block, an address of a label, or a
3609/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003610/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003611/// encounter a subexpression that (1) clearly does not lead to one of the
3612/// above problematic expressions (2) is something we cannot determine leads to
3613/// a problematic expression based on such local checking.
3614///
3615/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3616/// the expression that they point to. Such variables are added to the
3617/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003618///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003619/// EvalAddr processes expressions that are pointers that are used as
3620/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003621/// At the base case of the recursion is a check for the above problematic
3622/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00003623///
3624/// This implementation handles:
3625///
3626/// * pointer-to-pointer casts
3627/// * implicit conversions from array references to pointers
3628/// * taking the address of fields
3629/// * arbitrary interplay between "&" and "*" operators
3630/// * pointer arithmetic from an address of a stack variable
3631/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003632static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3633 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003634 if (E->isTypeDependent())
3635 return NULL;
3636
Ted Kremenek06de2762007-08-17 16:46:58 +00003637 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00003638 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00003639 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003640 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003641 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00003642
Peter Collingbournef111d932011-04-15 00:35:48 +00003643 E = E->IgnoreParens();
3644
Ted Kremenek06de2762007-08-17 16:46:58 +00003645 // Our "symbolic interpreter" is just a dispatch off the currently
3646 // viewed AST node. We then recursively traverse the AST by calling
3647 // EvalAddr and EvalVal appropriately.
3648 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003649 case Stmt::DeclRefExprClass: {
3650 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3651
3652 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3653 // If this is a reference variable, follow through to the expression that
3654 // it points to.
3655 if (V->hasLocalStorage() &&
3656 V->getType()->isReferenceType() && V->hasInit()) {
3657 // Add the reference variable to the "trail".
3658 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003659 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003660 }
3661
3662 return NULL;
3663 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003664
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003665 case Stmt::UnaryOperatorClass: {
3666 // The only unary operator that make sense to handle here
3667 // is AddrOf. All others don't make sense as pointers.
3668 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003669
John McCall2de56d12010-08-25 11:45:40 +00003670 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003671 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003672 else
Ted Kremenek06de2762007-08-17 16:46:58 +00003673 return NULL;
3674 }
Mike Stump1eb44332009-09-09 15:08:12 +00003675
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003676 case Stmt::BinaryOperatorClass: {
3677 // Handle pointer arithmetic. All other binary operators are not valid
3678 // in this context.
3679 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00003680 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00003681
John McCall2de56d12010-08-25 11:45:40 +00003682 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003683 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00003684
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003685 Expr *Base = B->getLHS();
3686
3687 // Determine which argument is the real pointer base. It could be
3688 // the RHS argument instead of the LHS.
3689 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00003690
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003691 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003692 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003693 }
Steve Naroff61f40a22008-09-10 19:17:48 +00003694
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003695 // For conditional operators we need to see if either the LHS or RHS are
3696 // valid DeclRefExpr*s. If one of them is valid, we return it.
3697 case Stmt::ConditionalOperatorClass: {
3698 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003699
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003700 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003701 if (Expr *lhsExpr = C->getLHS()) {
3702 // In C++, we can have a throw-expression, which has 'void' type.
3703 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003704 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003705 return LHS;
3706 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003707
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003708 // In C++, we can have a throw-expression, which has 'void' type.
3709 if (C->getRHS()->getType()->isVoidType())
3710 return NULL;
3711
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003712 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003713 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003714
3715 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00003716 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003717 return E; // local block.
3718 return NULL;
3719
3720 case Stmt::AddrLabelExprClass:
3721 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00003722
John McCall80ee6e82011-11-10 05:35:25 +00003723 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003724 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
3725 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003726
Ted Kremenek54b52742008-08-07 00:49:01 +00003727 // For casts, we need to handle conversions from arrays to
3728 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00003729 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003730 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003731 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00003732 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00003733 case Stmt::CXXStaticCastExprClass:
3734 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00003735 case Stmt::CXXConstCastExprClass:
3736 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00003737 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3738 switch (cast<CastExpr>(E)->getCastKind()) {
3739 case CK_BitCast:
3740 case CK_LValueToRValue:
3741 case CK_NoOp:
3742 case CK_BaseToDerived:
3743 case CK_DerivedToBase:
3744 case CK_UncheckedDerivedToBase:
3745 case CK_Dynamic:
3746 case CK_CPointerToObjCPointerCast:
3747 case CK_BlockPointerToObjCPointerCast:
3748 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003749 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003750
3751 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003752 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003753
3754 default:
3755 return 0;
3756 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003757 }
Mike Stump1eb44332009-09-09 15:08:12 +00003758
Douglas Gregor03e80032011-06-21 17:03:29 +00003759 case Stmt::MaterializeTemporaryExprClass:
3760 if (Expr *Result = EvalAddr(
3761 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003762 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003763 return Result;
3764
3765 return E;
3766
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003767 // Everything else: we simply don't reason about them.
3768 default:
3769 return NULL;
3770 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003771}
Mike Stump1eb44332009-09-09 15:08:12 +00003772
Ted Kremenek06de2762007-08-17 16:46:58 +00003773
3774/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3775/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003776static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3777 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003778do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003779 // We should only be called for evaluating non-pointer expressions, or
3780 // expressions with a pointer type that are not used as references but instead
3781 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00003782
Ted Kremenek06de2762007-08-17 16:46:58 +00003783 // Our "symbolic interpreter" is just a dispatch off the currently
3784 // viewed AST node. We then recursively traverse the AST by calling
3785 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00003786
3787 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00003788 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003789 case Stmt::ImplicitCastExprClass: {
3790 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00003791 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003792 E = IE->getSubExpr();
3793 continue;
3794 }
3795 return NULL;
3796 }
3797
John McCall80ee6e82011-11-10 05:35:25 +00003798 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003799 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003800
Douglas Gregora2813ce2009-10-23 18:54:35 +00003801 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003802 // When we hit a DeclRefExpr we are looking at code that refers to a
3803 // variable's name. If it's not a reference variable we check if it has
3804 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00003805 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003806
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003807 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
3808 // Check if it refers to itself, e.g. "int& i = i;".
3809 if (V == ParentDecl)
3810 return DR;
3811
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003812 if (V->hasLocalStorage()) {
3813 if (!V->getType()->isReferenceType())
3814 return DR;
3815
3816 // Reference variable, follow through to the expression that
3817 // it points to.
3818 if (V->hasInit()) {
3819 // Add the reference variable to the "trail".
3820 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003821 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003822 }
3823 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003824 }
Mike Stump1eb44332009-09-09 15:08:12 +00003825
Ted Kremenek06de2762007-08-17 16:46:58 +00003826 return NULL;
3827 }
Mike Stump1eb44332009-09-09 15:08:12 +00003828
Ted Kremenek06de2762007-08-17 16:46:58 +00003829 case Stmt::UnaryOperatorClass: {
3830 // The only unary operator that make sense to handle here
3831 // is Deref. All others don't resolve to a "name." This includes
3832 // handling all sorts of rvalues passed to a unary operator.
3833 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003834
John McCall2de56d12010-08-25 11:45:40 +00003835 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003836 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003837
3838 return NULL;
3839 }
Mike Stump1eb44332009-09-09 15:08:12 +00003840
Ted Kremenek06de2762007-08-17 16:46:58 +00003841 case Stmt::ArraySubscriptExprClass: {
3842 // Array subscripts are potential references to data on the stack. We
3843 // retrieve the DeclRefExpr* for the array variable if it indeed
3844 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003845 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003846 }
Mike Stump1eb44332009-09-09 15:08:12 +00003847
Ted Kremenek06de2762007-08-17 16:46:58 +00003848 case Stmt::ConditionalOperatorClass: {
3849 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003850 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003851 ConditionalOperator *C = cast<ConditionalOperator>(E);
3852
Anders Carlsson39073232007-11-30 19:04:31 +00003853 // Handle the GNU extension for missing LHS.
3854 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003855 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00003856 return LHS;
3857
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003858 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003859 }
Mike Stump1eb44332009-09-09 15:08:12 +00003860
Ted Kremenek06de2762007-08-17 16:46:58 +00003861 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003862 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003863 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003864
Ted Kremenek06de2762007-08-17 16:46:58 +00003865 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003866 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003867 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003868
3869 // Check whether the member type is itself a reference, in which case
3870 // we're not going to refer to the member, but to what the member refers to.
3871 if (M->getMemberDecl()->getType()->isReferenceType())
3872 return NULL;
3873
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003874 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003875 }
Mike Stump1eb44332009-09-09 15:08:12 +00003876
Douglas Gregor03e80032011-06-21 17:03:29 +00003877 case Stmt::MaterializeTemporaryExprClass:
3878 if (Expr *Result = EvalVal(
3879 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003880 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003881 return Result;
3882
3883 return E;
3884
Ted Kremenek06de2762007-08-17 16:46:58 +00003885 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003886 // Check that we don't return or take the address of a reference to a
3887 // temporary. This is only useful in C++.
3888 if (!E->isTypeDependent() && E->isRValue())
3889 return E;
3890
3891 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003892 return NULL;
3893 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003894} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003895}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003896
3897//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3898
3899/// Check for comparisons of floating point operands using != and ==.
3900/// Issue a warning if these are no self-comparisons, as they are not likely
3901/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003902void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00003903 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3904 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003905
3906 // Special case: check for x == x (which is OK).
3907 // Do not emit warnings for such cases.
3908 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3909 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3910 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00003911 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003912
3913
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003914 // Special case: check for comparisons against literals that can be exactly
3915 // represented by APFloat. In such cases, do not emit a warning. This
3916 // is a heuristic: often comparison against such literals are used to
3917 // detect if a value in a variable has not changed. This clearly can
3918 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00003919 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3920 if (FLL->isExact())
3921 return;
3922 } else
3923 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
3924 if (FLR->isExact())
3925 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003926
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003927 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00003928 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
3929 if (CL->isBuiltinCall())
3930 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003931
David Blaikie980343b2012-07-16 20:47:22 +00003932 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
3933 if (CR->isBuiltinCall())
3934 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003935
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003936 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00003937 Diag(Loc, diag::warn_floatingpoint_eq)
3938 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003939}
John McCallba26e582010-01-04 23:21:16 +00003940
John McCallf2370c92010-01-06 05:24:50 +00003941//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3942//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003943
John McCallf2370c92010-01-06 05:24:50 +00003944namespace {
John McCallba26e582010-01-04 23:21:16 +00003945
John McCallf2370c92010-01-06 05:24:50 +00003946/// Structure recording the 'active' range of an integer-valued
3947/// expression.
3948struct IntRange {
3949 /// The number of bits active in the int.
3950 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003951
John McCallf2370c92010-01-06 05:24:50 +00003952 /// True if the int is known not to have negative values.
3953 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003954
John McCallf2370c92010-01-06 05:24:50 +00003955 IntRange(unsigned Width, bool NonNegative)
3956 : Width(Width), NonNegative(NonNegative)
3957 {}
John McCallba26e582010-01-04 23:21:16 +00003958
John McCall1844a6e2010-11-10 23:38:19 +00003959 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00003960 static IntRange forBoolType() {
3961 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00003962 }
3963
John McCall1844a6e2010-11-10 23:38:19 +00003964 /// Returns the range of an opaque value of the given integral type.
3965 static IntRange forValueOfType(ASTContext &C, QualType T) {
3966 return forValueOfCanonicalType(C,
3967 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00003968 }
3969
John McCall1844a6e2010-11-10 23:38:19 +00003970 /// Returns the range of an opaque value of a canonical integral type.
3971 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00003972 assert(T->isCanonicalUnqualified());
3973
3974 if (const VectorType *VT = dyn_cast<VectorType>(T))
3975 T = VT->getElementType().getTypePtr();
3976 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3977 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00003978
John McCall091f23f2010-11-09 22:22:12 +00003979 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00003980 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3981 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00003982 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00003983 return IntRange(C.getIntWidth(QualType(T, 0)), false);
3984
John McCall323ed742010-05-06 08:58:33 +00003985 unsigned NumPositive = Enum->getNumPositiveBits();
3986 unsigned NumNegative = Enum->getNumNegativeBits();
3987
Richard Trieu8f50b242012-11-16 01:32:40 +00003988 if (NumNegative == 0)
3989 return IntRange(NumPositive, true/*NonNegative*/);
3990 else
3991 return IntRange(std::max(NumPositive + 1, NumNegative),
3992 false/*NonNegative*/);
John McCall323ed742010-05-06 08:58:33 +00003993 }
John McCallf2370c92010-01-06 05:24:50 +00003994
3995 const BuiltinType *BT = cast<BuiltinType>(T);
3996 assert(BT->isInteger());
3997
3998 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3999 }
4000
John McCall1844a6e2010-11-10 23:38:19 +00004001 /// Returns the "target" range of a canonical integral type, i.e.
4002 /// the range of values expressible in the type.
4003 ///
4004 /// This matches forValueOfCanonicalType except that enums have the
4005 /// full range of their type, not the range of their enumerators.
4006 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4007 assert(T->isCanonicalUnqualified());
4008
4009 if (const VectorType *VT = dyn_cast<VectorType>(T))
4010 T = VT->getElementType().getTypePtr();
4011 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4012 T = CT->getElementType().getTypePtr();
4013 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00004014 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00004015
4016 const BuiltinType *BT = cast<BuiltinType>(T);
4017 assert(BT->isInteger());
4018
4019 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4020 }
4021
4022 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004023 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00004024 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00004025 L.NonNegative && R.NonNegative);
4026 }
4027
John McCall1844a6e2010-11-10 23:38:19 +00004028 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004029 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00004030 return IntRange(std::min(L.Width, R.Width),
4031 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00004032 }
4033};
4034
Ted Kremenek0692a192012-01-31 05:37:37 +00004035static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4036 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004037 if (value.isSigned() && value.isNegative())
4038 return IntRange(value.getMinSignedBits(), false);
4039
4040 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00004041 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004042
4043 // isNonNegative() just checks the sign bit without considering
4044 // signedness.
4045 return IntRange(value.getActiveBits(), true);
4046}
4047
Ted Kremenek0692a192012-01-31 05:37:37 +00004048static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4049 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004050 if (result.isInt())
4051 return GetValueRange(C, result.getInt(), MaxWidth);
4052
4053 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00004054 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4055 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4056 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4057 R = IntRange::join(R, El);
4058 }
John McCallf2370c92010-01-06 05:24:50 +00004059 return R;
4060 }
4061
4062 if (result.isComplexInt()) {
4063 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4064 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4065 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00004066 }
4067
4068 // This can happen with lossless casts to intptr_t of "based" lvalues.
4069 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00004070 // FIXME: The only reason we need to pass the type in here is to get
4071 // the sign right on this one case. It would be nice if APValue
4072 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00004073 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004074 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00004075}
John McCallf2370c92010-01-06 05:24:50 +00004076
4077/// Pseudo-evaluate the given integer expression, estimating the
4078/// range of values it might take.
4079///
4080/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00004081static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004082 E = E->IgnoreParens();
4083
4084 // Try a full evaluation first.
4085 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004086 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00004087 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004088
4089 // I think we only want to look through implicit casts here; if the
4090 // user has an explicit widening cast, we should treat the value as
4091 // being of the new, wider type.
4092 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00004093 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00004094 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4095
John McCall1844a6e2010-11-10 23:38:19 +00004096 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00004097
John McCall2de56d12010-08-25 11:45:40 +00004098 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00004099
John McCallf2370c92010-01-06 05:24:50 +00004100 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00004101 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00004102 return OutputTypeRange;
4103
4104 IntRange SubRange
4105 = GetExprRange(C, CE->getSubExpr(),
4106 std::min(MaxWidth, OutputTypeRange.Width));
4107
4108 // Bail out if the subexpr's range is as wide as the cast type.
4109 if (SubRange.Width >= OutputTypeRange.Width)
4110 return OutputTypeRange;
4111
4112 // Otherwise, we take the smaller width, and we're non-negative if
4113 // either the output type or the subexpr is.
4114 return IntRange(SubRange.Width,
4115 SubRange.NonNegative || OutputTypeRange.NonNegative);
4116 }
4117
4118 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4119 // If we can fold the condition, just take that operand.
4120 bool CondResult;
4121 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4122 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4123 : CO->getFalseExpr(),
4124 MaxWidth);
4125
4126 // Otherwise, conservatively merge.
4127 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4128 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4129 return IntRange::join(L, R);
4130 }
4131
4132 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4133 switch (BO->getOpcode()) {
4134
4135 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00004136 case BO_LAnd:
4137 case BO_LOr:
4138 case BO_LT:
4139 case BO_GT:
4140 case BO_LE:
4141 case BO_GE:
4142 case BO_EQ:
4143 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00004144 return IntRange::forBoolType();
4145
John McCall862ff872011-07-13 06:35:24 +00004146 // The type of the assignments is the type of the LHS, so the RHS
4147 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00004148 case BO_MulAssign:
4149 case BO_DivAssign:
4150 case BO_RemAssign:
4151 case BO_AddAssign:
4152 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00004153 case BO_XorAssign:
4154 case BO_OrAssign:
4155 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00004156 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00004157
John McCall862ff872011-07-13 06:35:24 +00004158 // Simple assignments just pass through the RHS, which will have
4159 // been coerced to the LHS type.
4160 case BO_Assign:
4161 // TODO: bitfields?
4162 return GetExprRange(C, BO->getRHS(), MaxWidth);
4163
John McCallf2370c92010-01-06 05:24:50 +00004164 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004165 case BO_PtrMemD:
4166 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00004167 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004168
John McCall60fad452010-01-06 22:07:33 +00004169 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00004170 case BO_And:
4171 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00004172 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4173 GetExprRange(C, BO->getRHS(), MaxWidth));
4174
John McCallf2370c92010-01-06 05:24:50 +00004175 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00004176 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00004177 // ...except that we want to treat '1 << (blah)' as logically
4178 // positive. It's an important idiom.
4179 if (IntegerLiteral *I
4180 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4181 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00004182 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00004183 return IntRange(R.Width, /*NonNegative*/ true);
4184 }
4185 }
4186 // fallthrough
4187
John McCall2de56d12010-08-25 11:45:40 +00004188 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00004189 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004190
John McCall60fad452010-01-06 22:07:33 +00004191 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00004192 case BO_Shr:
4193 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00004194 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4195
4196 // If the shift amount is a positive constant, drop the width by
4197 // that much.
4198 llvm::APSInt shift;
4199 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4200 shift.isNonNegative()) {
4201 unsigned zext = shift.getZExtValue();
4202 if (zext >= L.Width)
4203 L.Width = (L.NonNegative ? 0 : 1);
4204 else
4205 L.Width -= zext;
4206 }
4207
4208 return L;
4209 }
4210
4211 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00004212 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00004213 return GetExprRange(C, BO->getRHS(), MaxWidth);
4214
John McCall60fad452010-01-06 22:07:33 +00004215 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00004216 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00004217 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00004218 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00004219 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00004220
John McCall00fe7612011-07-14 22:39:48 +00004221 // The width of a division result is mostly determined by the size
4222 // of the LHS.
4223 case BO_Div: {
4224 // Don't 'pre-truncate' the operands.
4225 unsigned opWidth = C.getIntWidth(E->getType());
4226 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4227
4228 // If the divisor is constant, use that.
4229 llvm::APSInt divisor;
4230 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4231 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4232 if (log2 >= L.Width)
4233 L.Width = (L.NonNegative ? 0 : 1);
4234 else
4235 L.Width = std::min(L.Width - log2, MaxWidth);
4236 return L;
4237 }
4238
4239 // Otherwise, just use the LHS's width.
4240 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4241 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4242 }
4243
4244 // The result of a remainder can't be larger than the result of
4245 // either side.
4246 case BO_Rem: {
4247 // Don't 'pre-truncate' the operands.
4248 unsigned opWidth = C.getIntWidth(E->getType());
4249 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4250 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4251
4252 IntRange meet = IntRange::meet(L, R);
4253 meet.Width = std::min(meet.Width, MaxWidth);
4254 return meet;
4255 }
4256
4257 // The default behavior is okay for these.
4258 case BO_Mul:
4259 case BO_Add:
4260 case BO_Xor:
4261 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00004262 break;
4263 }
4264
John McCall00fe7612011-07-14 22:39:48 +00004265 // The default case is to treat the operation as if it were closed
4266 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004267 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4268 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4269 return IntRange::join(L, R);
4270 }
4271
4272 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4273 switch (UO->getOpcode()) {
4274 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004275 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004276 return IntRange::forBoolType();
4277
4278 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004279 case UO_Deref:
4280 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00004281 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004282
4283 default:
4284 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4285 }
4286 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004287
4288 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00004289 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004290 }
John McCallf2370c92010-01-06 05:24:50 +00004291
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004292 if (FieldDecl *BitField = E->getBitField())
4293 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004294 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004295
John McCall1844a6e2010-11-10 23:38:19 +00004296 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004297}
John McCall51313c32010-01-04 23:31:57 +00004298
Ted Kremenek0692a192012-01-31 05:37:37 +00004299static IntRange GetExprRange(ASTContext &C, Expr *E) {
John McCall323ed742010-05-06 08:58:33 +00004300 return GetExprRange(C, E, C.getIntWidth(E->getType()));
4301}
4302
John McCall51313c32010-01-04 23:31:57 +00004303/// Checks whether the given value, which currently has the given
4304/// source semantics, has the same value when coerced through the
4305/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004306static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4307 const llvm::fltSemantics &Src,
4308 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004309 llvm::APFloat truncated = value;
4310
4311 bool ignored;
4312 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4313 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4314
4315 return truncated.bitwiseIsEqual(value);
4316}
4317
4318/// Checks whether the given value, which currently has the given
4319/// source semantics, has the same value when coerced through the
4320/// target semantics.
4321///
4322/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004323static bool IsSameFloatAfterCast(const APValue &value,
4324 const llvm::fltSemantics &Src,
4325 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004326 if (value.isFloat())
4327 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4328
4329 if (value.isVector()) {
4330 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4331 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4332 return false;
4333 return true;
4334 }
4335
4336 assert(value.isComplexFloat());
4337 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4338 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4339}
4340
Ted Kremenek0692a192012-01-31 05:37:37 +00004341static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004342
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004343static bool IsZero(Sema &S, Expr *E) {
4344 // Suppress cases where we are comparing against an enum constant.
4345 if (const DeclRefExpr *DR =
4346 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4347 if (isa<EnumConstantDecl>(DR->getDecl()))
4348 return false;
4349
4350 // Suppress cases where the '0' value is expanded from a macro.
4351 if (E->getLocStart().isMacroID())
4352 return false;
4353
John McCall323ed742010-05-06 08:58:33 +00004354 llvm::APSInt Value;
4355 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4356}
4357
John McCall372e1032010-10-06 00:25:24 +00004358static bool HasEnumType(Expr *E) {
4359 // Strip off implicit integral promotions.
4360 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004361 if (ICE->getCastKind() != CK_IntegralCast &&
4362 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004363 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004364 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004365 }
4366
4367 return E->getType()->isEnumeralType();
4368}
4369
Ted Kremenek0692a192012-01-31 05:37:37 +00004370static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004371 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004372 if (E->isValueDependent())
4373 return;
4374
John McCall2de56d12010-08-25 11:45:40 +00004375 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004376 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004377 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004378 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004379 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004380 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004381 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004382 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004383 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004384 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004385 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004386 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004387 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004388 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004389 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004390 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4391 }
4392}
4393
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004394static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004395 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004396 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004397 bool RhsConstant) {
Richard Trieu526e6272012-11-14 22:50:24 +00004398 // 0 values are handled later by CheckTrivialUnsignedComparison().
4399 if (Value == 0)
4400 return;
4401
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004402 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004403 QualType OtherT = Other->getType();
4404 QualType ConstantT = Constant->getType();
Richard Trieu526e6272012-11-14 22:50:24 +00004405 QualType CommonT = E->getLHS()->getType();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004406 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004407 return;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004408 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004409 && "comparison with non-integer type");
Richard Trieu526e6272012-11-14 22:50:24 +00004410
4411 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu526e6272012-11-14 22:50:24 +00004412 bool CommonSigned = CommonT->isSignedIntegerType();
4413
4414 bool EqualityOnly = false;
4415
4416 // TODO: Investigate using GetExprRange() to get tighter bounds on
4417 // on the bit ranges.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004418 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu526e6272012-11-14 22:50:24 +00004419 unsigned OtherWidth = OtherRange.Width;
4420
4421 if (CommonSigned) {
4422 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedmand87de7b2012-11-30 23:09:29 +00004423 if (!OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004424 // Check that the constant is representable in type OtherT.
4425 if (ConstantSigned) {
4426 if (OtherWidth >= Value.getMinSignedBits())
4427 return;
4428 } else { // !ConstantSigned
4429 if (OtherWidth >= Value.getActiveBits() + 1)
4430 return;
4431 }
4432 } else { // !OtherSigned
4433 // Check that the constant is representable in type OtherT.
4434 // Negative values are out of range.
4435 if (ConstantSigned) {
4436 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4437 return;
4438 } else { // !ConstantSigned
4439 if (OtherWidth >= Value.getActiveBits())
4440 return;
4441 }
4442 }
4443 } else { // !CommonSigned
Eli Friedmand87de7b2012-11-30 23:09:29 +00004444 if (OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004445 if (OtherWidth >= Value.getActiveBits())
4446 return;
Eli Friedmand87de7b2012-11-30 23:09:29 +00004447 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu526e6272012-11-14 22:50:24 +00004448 // Check to see if the constant is representable in OtherT.
4449 if (OtherWidth > Value.getActiveBits())
4450 return;
4451 // Check to see if the constant is equivalent to a negative value
4452 // cast to CommonT.
4453 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu5d1cf4f2012-11-15 03:43:50 +00004454 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu526e6272012-11-14 22:50:24 +00004455 return;
4456 // The constant value rests between values that OtherT can represent after
4457 // conversion. Relational comparison still works, but equality
4458 // comparisons will be tautological.
4459 EqualityOnly = true;
4460 } else { // OtherSigned && ConstantSigned
4461 assert(0 && "Two signed types converted to unsigned types.");
4462 }
4463 }
4464
4465 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4466
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004467 bool IsTrue = true;
Richard Trieu526e6272012-11-14 22:50:24 +00004468 if (op == BO_EQ || op == BO_NE) {
4469 IsTrue = op == BO_NE;
4470 } else if (EqualityOnly) {
4471 return;
4472 } else if (RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004473 if (op == BO_GT || op == BO_GE)
Richard Trieu526e6272012-11-14 22:50:24 +00004474 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004475 else // op == BO_LT || op == BO_LE
Richard Trieu526e6272012-11-14 22:50:24 +00004476 IsTrue = PositiveConstant;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004477 } else {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004478 if (op == BO_LT || op == BO_LE)
Richard Trieu526e6272012-11-14 22:50:24 +00004479 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004480 else // op == BO_GT || op == BO_GE
Richard Trieu526e6272012-11-14 22:50:24 +00004481 IsTrue = PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004482 }
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004483 SmallString<16> PrettySourceValue(Value.toString(10));
4484 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
Richard Trieu526e6272012-11-14 22:50:24 +00004485 << PrettySourceValue << OtherT << IsTrue
4486 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004487}
4488
John McCall323ed742010-05-06 08:58:33 +00004489/// Analyze the operands of the given comparison. Implements the
4490/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004491static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004492 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4493 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004494}
John McCall51313c32010-01-04 23:31:57 +00004495
John McCallba26e582010-01-04 23:21:16 +00004496/// \brief Implements -Wsign-compare.
4497///
Richard Trieudd225092011-09-15 21:56:47 +00004498/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004499static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004500 // The type the comparison is being performed in.
4501 QualType T = E->getLHS()->getType();
4502 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4503 && "comparison with mismatched types");
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00004504 if (E->isValueDependent())
4505 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004506
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004507 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4508 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004509
4510 bool IsComparisonConstant = false;
4511
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004512 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004513 // of 'true' or 'false'.
4514 if (T->isIntegralType(S.Context)) {
4515 llvm::APSInt RHSValue;
4516 bool IsRHSIntegralLiteral =
4517 RHS->isIntegerConstantExpr(RHSValue, S.Context);
4518 llvm::APSInt LHSValue;
4519 bool IsLHSIntegralLiteral =
4520 LHS->isIntegerConstantExpr(LHSValue, S.Context);
4521 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4522 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4523 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4524 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4525 else
4526 IsComparisonConstant =
4527 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004528 } else if (!T->hasUnsignedIntegerRepresentation())
4529 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004530
John McCall323ed742010-05-06 08:58:33 +00004531 // We don't do anything special if this isn't an unsigned integral
4532 // comparison: we're only interested in integral comparisons, and
4533 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004534 //
4535 // We also don't care about value-dependent expressions or expressions
4536 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004537 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00004538 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004539
John McCall323ed742010-05-06 08:58:33 +00004540 // Check to see if one of the (unmodified) operands is of different
4541 // signedness.
4542 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004543 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4544 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004545 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004546 signedOperand = LHS;
4547 unsignedOperand = RHS;
4548 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4549 signedOperand = RHS;
4550 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004551 } else {
John McCall323ed742010-05-06 08:58:33 +00004552 CheckTrivialUnsignedComparison(S, E);
4553 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004554 }
4555
John McCall323ed742010-05-06 08:58:33 +00004556 // Otherwise, calculate the effective range of the signed operand.
4557 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004558
John McCall323ed742010-05-06 08:58:33 +00004559 // Go ahead and analyze implicit conversions in the operands. Note
4560 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004561 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4562 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004563
John McCall323ed742010-05-06 08:58:33 +00004564 // If the signed range is non-negative, -Wsign-compare won't fire,
4565 // but we should still check for comparisons which are always true
4566 // or false.
4567 if (signedRange.NonNegative)
4568 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004569
4570 // For (in)equality comparisons, if the unsigned operand is a
4571 // constant which cannot collide with a overflowed signed operand,
4572 // then reinterpreting the signed operand as unsigned will not
4573 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00004574 if (E->isEqualityOp()) {
4575 unsigned comparisonWidth = S.Context.getIntWidth(T);
4576 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00004577
John McCall323ed742010-05-06 08:58:33 +00004578 // We should never be unable to prove that the unsigned operand is
4579 // non-negative.
4580 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
4581
4582 if (unsignedRange.Width < comparisonWidth)
4583 return;
4584 }
4585
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00004586 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4587 S.PDiag(diag::warn_mixed_sign_comparison)
4588 << LHS->getType() << RHS->getType()
4589 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00004590}
4591
John McCall15d7d122010-11-11 03:21:53 +00004592/// Analyzes an attempt to assign the given value to a bitfield.
4593///
4594/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00004595static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4596 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00004597 assert(Bitfield->isBitField());
4598 if (Bitfield->isInvalidDecl())
4599 return false;
4600
John McCall91b60142010-11-11 05:33:51 +00004601 // White-list bool bitfields.
4602 if (Bitfield->getType()->isBooleanType())
4603 return false;
4604
Douglas Gregor46ff3032011-02-04 13:09:01 +00004605 // Ignore value- or type-dependent expressions.
4606 if (Bitfield->getBitWidth()->isValueDependent() ||
4607 Bitfield->getBitWidth()->isTypeDependent() ||
4608 Init->isValueDependent() ||
4609 Init->isTypeDependent())
4610 return false;
4611
John McCall15d7d122010-11-11 03:21:53 +00004612 Expr *OriginalInit = Init->IgnoreParenImpCasts();
4613
Richard Smith80d4b552011-12-28 19:48:30 +00004614 llvm::APSInt Value;
4615 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00004616 return false;
4617
John McCall15d7d122010-11-11 03:21:53 +00004618 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004619 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00004620
4621 if (OriginalWidth <= FieldWidth)
4622 return false;
4623
Eli Friedman3a643af2012-01-26 23:11:39 +00004624 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004625 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00004626 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00004627
Eli Friedman3a643af2012-01-26 23:11:39 +00004628 // Check whether the stored value is equal to the original value.
4629 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00004630 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00004631 return false;
4632
Eli Friedman3a643af2012-01-26 23:11:39 +00004633 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00004634 // therefore don't strictly fit into a signed bitfield of width 1.
4635 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00004636 return false;
4637
John McCall15d7d122010-11-11 03:21:53 +00004638 std::string PrettyValue = Value.toString(10);
4639 std::string PrettyTrunc = TruncatedValue.toString(10);
4640
4641 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4642 << PrettyValue << PrettyTrunc << OriginalInit->getType()
4643 << Init->getSourceRange();
4644
4645 return true;
4646}
4647
John McCallbeb22aa2010-11-09 23:24:47 +00004648/// Analyze the given simple or compound assignment for warning-worthy
4649/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00004650static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00004651 // Just recurse on the LHS.
4652 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4653
4654 // We want to recurse on the RHS as normal unless we're assigning to
4655 // a bitfield.
4656 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00004657 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
4658 E->getOperatorLoc())) {
4659 // Recurse, ignoring any implicit conversions on the RHS.
4660 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
4661 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00004662 }
4663 }
4664
4665 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4666}
4667
John McCall51313c32010-01-04 23:31:57 +00004668/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004669static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004670 SourceLocation CContext, unsigned diag,
4671 bool pruneControlFlow = false) {
4672 if (pruneControlFlow) {
4673 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4674 S.PDiag(diag)
4675 << SourceType << T << E->getSourceRange()
4676 << SourceRange(CContext));
4677 return;
4678 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004679 S.Diag(E->getExprLoc(), diag)
4680 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
4681}
4682
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004683/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004684static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004685 SourceLocation CContext, unsigned diag,
4686 bool pruneControlFlow = false) {
4687 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004688}
4689
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004690/// Diagnose an implicit cast from a literal expression. Does not warn when the
4691/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004692void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
4693 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004694 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004695 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004696 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00004697 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
4698 T->hasUnsignedIntegerRepresentation());
4699 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00004700 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004701 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00004702 return;
4703
David Blaikiebe0ee872012-05-15 16:56:36 +00004704 SmallString<16> PrettySourceValue;
4705 Value.toString(PrettySourceValue);
David Blaikiede7e7b82012-05-15 17:18:27 +00004706 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00004707 if (T->isSpecificBuiltinType(BuiltinType::Bool))
4708 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
4709 else
David Blaikiede7e7b82012-05-15 17:18:27 +00004710 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00004711
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004712 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00004713 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
4714 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00004715}
4716
John McCall091f23f2010-11-09 22:22:12 +00004717std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
4718 if (!Range.Width) return "0";
4719
4720 llvm::APSInt ValueInRange = Value;
4721 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00004722 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00004723 return ValueInRange.toString(10);
4724}
4725
Hans Wennborg88617a22012-08-28 15:44:30 +00004726static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
4727 if (!isa<ImplicitCastExpr>(Ex))
4728 return false;
4729
4730 Expr *InnerE = Ex->IgnoreParenImpCasts();
4731 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
4732 const Type *Source =
4733 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4734 if (Target->isDependentType())
4735 return false;
4736
4737 const BuiltinType *FloatCandidateBT =
4738 dyn_cast<BuiltinType>(ToBool ? Source : Target);
4739 const Type *BoolCandidateType = ToBool ? Target : Source;
4740
4741 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
4742 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
4743}
4744
4745void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
4746 SourceLocation CC) {
4747 unsigned NumArgs = TheCall->getNumArgs();
4748 for (unsigned i = 0; i < NumArgs; ++i) {
4749 Expr *CurrA = TheCall->getArg(i);
4750 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
4751 continue;
4752
4753 bool IsSwapped = ((i > 0) &&
4754 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
4755 IsSwapped |= ((i < (NumArgs - 1)) &&
4756 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
4757 if (IsSwapped) {
4758 // Warn on this floating-point to bool conversion.
4759 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
4760 CurrA->getType(), CC,
4761 diag::warn_impcast_floating_point_to_bool);
4762 }
4763 }
4764}
4765
John McCall323ed742010-05-06 08:58:33 +00004766void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004767 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00004768 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00004769
John McCall323ed742010-05-06 08:58:33 +00004770 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
4771 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
4772 if (Source == Target) return;
4773 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00004774
Chandler Carruth108f7562011-07-26 05:40:03 +00004775 // If the conversion context location is invalid don't complain. We also
4776 // don't want to emit a warning if the issue occurs from the expansion of
4777 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
4778 // delay this check as long as possible. Once we detect we are in that
4779 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00004780 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00004781 return;
4782
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004783 // Diagnose implicit casts to bool.
4784 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
4785 if (isa<StringLiteral>(E))
4786 // Warn on string literal to bool. Checks for string literals in logical
4787 // expressions, for instances, assert(0 && "error here"), is prevented
4788 // by a check in AnalyzeImplicitConversions().
4789 return DiagnoseImpCast(S, E, T, CC,
4790 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00004791 if (Source->isFunctionType()) {
4792 // Warn on function to bool. Checks free functions and static member
4793 // functions. Weakly imported functions are excluded from the check,
4794 // since it's common to test their value to check whether the linker
4795 // found a definition for them.
4796 ValueDecl *D = 0;
4797 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
4798 D = R->getDecl();
4799 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
4800 D = M->getMemberDecl();
4801 }
4802
4803 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00004804 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
4805 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
4806 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00004807 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
4808 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
4809 QualType ReturnType;
4810 UnresolvedSet<4> NonTemplateOverloads;
4811 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
4812 if (!ReturnType.isNull()
4813 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
4814 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
4815 << FixItHint::CreateInsertion(
4816 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00004817 return;
4818 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00004819 }
4820 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004821 }
John McCall51313c32010-01-04 23:31:57 +00004822
4823 // Strip vector types.
4824 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004825 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004826 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004827 return;
John McCallb4eb64d2010-10-08 02:01:28 +00004828 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004829 }
Chris Lattnerb792b302011-06-14 04:51:15 +00004830
4831 // If the vector cast is cast between two vectors of the same size, it is
4832 // a bitcast, not a conversion.
4833 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4834 return;
John McCall51313c32010-01-04 23:31:57 +00004835
4836 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4837 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4838 }
4839
4840 // Strip complex types.
4841 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004842 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004843 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004844 return;
4845
John McCallb4eb64d2010-10-08 02:01:28 +00004846 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004847 }
John McCall51313c32010-01-04 23:31:57 +00004848
4849 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4850 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4851 }
4852
4853 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4854 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4855
4856 // If the source is floating point...
4857 if (SourceBT && SourceBT->isFloatingPoint()) {
4858 // ...and the target is floating point...
4859 if (TargetBT && TargetBT->isFloatingPoint()) {
4860 // ...then warn if we're dropping FP rank.
4861
4862 // Builtin FP kinds are ordered by increasing FP rank.
4863 if (SourceBT->getKind() > TargetBT->getKind()) {
4864 // Don't warn about float constants that are precisely
4865 // representable in the target type.
4866 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004867 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00004868 // Value might be a float, a float vector, or a float complex.
4869 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00004870 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4871 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00004872 return;
4873 }
4874
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004875 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004876 return;
4877
John McCallb4eb64d2010-10-08 02:01:28 +00004878 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00004879 }
4880 return;
4881 }
4882
Ted Kremenekef9ff882011-03-10 20:03:42 +00004883 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00004884 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004885 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004886 return;
4887
Chandler Carrutha5b93322011-02-17 11:05:49 +00004888 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00004889 // We also want to warn on, e.g., "int i = -1.234"
4890 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4891 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4892 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
4893
Chandler Carruthf65076e2011-04-10 08:36:24 +00004894 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4895 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00004896 } else {
4897 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4898 }
4899 }
John McCall51313c32010-01-04 23:31:57 +00004900
Hans Wennborg88617a22012-08-28 15:44:30 +00004901 // If the target is bool, warn if expr is a function or method call.
4902 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
4903 isa<CallExpr>(E)) {
4904 // Check last argument of function call to see if it is an
4905 // implicit cast from a type matching the type the result
4906 // is being cast to.
4907 CallExpr *CEx = cast<CallExpr>(E);
4908 unsigned NumArgs = CEx->getNumArgs();
4909 if (NumArgs > 0) {
4910 Expr *LastA = CEx->getArg(NumArgs - 1);
4911 Expr *InnerE = LastA->IgnoreParenImpCasts();
4912 const Type *InnerType =
4913 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4914 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
4915 // Warn on this floating-point to bool conversion
4916 DiagnoseImpCast(S, E, T, CC,
4917 diag::warn_impcast_floating_point_to_bool);
4918 }
4919 }
4920 }
John McCall51313c32010-01-04 23:31:57 +00004921 return;
4922 }
4923
Richard Trieu1838ca52011-05-29 19:59:02 +00004924 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00004925 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiee81b43b2012-11-08 00:41:20 +00004926 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
4927 && Target->isScalarType()) {
David Blaikieb1360492012-03-16 20:30:12 +00004928 SourceLocation Loc = E->getSourceRange().getBegin();
4929 if (Loc.isMacroID())
4930 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00004931 if (!Loc.isMacroID() || CC.isMacroID())
4932 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
4933 << T << clang::SourceRange(CC)
4934 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
Richard Trieu1838ca52011-05-29 19:59:02 +00004935 }
4936
David Blaikieb26331b2012-06-19 21:19:06 +00004937 if (!Source->isIntegerType() || !Target->isIntegerType())
4938 return;
4939
David Blaikiebe0ee872012-05-15 16:56:36 +00004940 // TODO: remove this early return once the false positives for constant->bool
4941 // in templates, macros, etc, are reduced or removed.
4942 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
4943 return;
4944
John McCall323ed742010-05-06 08:58:33 +00004945 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00004946 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00004947
4948 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00004949 // If the source is a constant, use a default-on diagnostic.
4950 // TODO: this should happen for bitfield stores, too.
4951 llvm::APSInt Value(32);
4952 if (E->isIntegerConstantExpr(Value, S.Context)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004953 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004954 return;
4955
John McCall091f23f2010-11-09 22:22:12 +00004956 std::string PrettySourceValue = Value.toString(10);
4957 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
4958
Ted Kremenek5e745da2011-10-22 02:37:33 +00004959 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4960 S.PDiag(diag::warn_impcast_integer_precision_constant)
4961 << PrettySourceValue << PrettyTargetValue
4962 << E->getType() << T << E->getSourceRange()
4963 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00004964 return;
4965 }
4966
Chris Lattnerb792b302011-06-14 04:51:15 +00004967 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004968 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004969 return;
David Blaikie0c5d0052012-11-19 23:12:51 +00004970
David Blaikie37050842012-04-12 22:40:54 +00004971 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00004972 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
4973 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00004974 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00004975 }
4976
4977 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
4978 (!TargetRange.NonNegative && SourceRange.NonNegative &&
4979 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004980
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004981 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004982 return;
4983
John McCall323ed742010-05-06 08:58:33 +00004984 unsigned DiagID = diag::warn_impcast_integer_sign;
4985
4986 // Traditionally, gcc has warned about this under -Wsign-compare.
4987 // We also want to warn about it in -Wconversion.
4988 // So if -Wconversion is off, use a completely identical diagnostic
4989 // in the sign-compare group.
4990 // The conditional-checking code will
4991 if (ICContext) {
4992 DiagID = diag::warn_impcast_integer_sign_conditional;
4993 *ICContext = true;
4994 }
4995
John McCallb4eb64d2010-10-08 02:01:28 +00004996 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00004997 }
4998
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004999 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005000 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5001 // type, to give us better diagnostics.
5002 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00005003 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005004 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5005 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5006 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5007 SourceType = S.Context.getTypeDeclType(Enum);
5008 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5009 }
5010 }
5011
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005012 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5013 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
5014 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00005015 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005016 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00005017 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00005018 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005019 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005020 return;
5021
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005022 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005023 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005024 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005025
John McCall51313c32010-01-04 23:31:57 +00005026 return;
5027}
5028
David Blaikie9fb1ac52012-05-15 21:57:38 +00005029void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5030 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00005031
5032void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00005033 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00005034 E = E->IgnoreParenImpCasts();
5035
5036 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00005037 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00005038
John McCallb4eb64d2010-10-08 02:01:28 +00005039 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005040 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005041 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00005042 return;
5043}
5044
David Blaikie9fb1ac52012-05-15 21:57:38 +00005045void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5046 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00005047 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00005048
5049 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00005050 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5051 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005052
5053 // If -Wconversion would have warned about either of the candidates
5054 // for a signedness conversion to the context type...
5055 if (!Suspicious) return;
5056
5057 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005058 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5059 CC))
John McCall323ed742010-05-06 08:58:33 +00005060 return;
5061
John McCall323ed742010-05-06 08:58:33 +00005062 // ...then check whether it would have warned about either of the
5063 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00005064 if (E->getType() == T) return;
5065
5066 Suspicious = false;
5067 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5068 E->getType(), CC, &Suspicious);
5069 if (!Suspicious)
5070 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00005071 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005072}
5073
5074/// AnalyzeImplicitConversions - Find and report any interesting
5075/// implicit conversions in the given expression. There are a couple
5076/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005077void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005078 QualType T = OrigE->getType();
5079 Expr *E = OrigE->IgnoreParenImpCasts();
5080
Douglas Gregorf8b6e152011-10-10 17:38:18 +00005081 if (E->isTypeDependent() || E->isValueDependent())
5082 return;
5083
John McCall323ed742010-05-06 08:58:33 +00005084 // For conditional operators, we analyze the arguments as if they
5085 // were being fed directly into the output.
5086 if (isa<ConditionalOperator>(E)) {
5087 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00005088 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00005089 return;
5090 }
5091
Hans Wennborg88617a22012-08-28 15:44:30 +00005092 // Check implicit argument conversions for function calls.
5093 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5094 CheckImplicitArgumentConversions(S, Call, CC);
5095
John McCall323ed742010-05-06 08:58:33 +00005096 // Go ahead and check any implicit conversions we might have skipped.
5097 // The non-canonical typecheck is just an optimization;
5098 // CheckImplicitConversion will filter out dead implicit conversions.
5099 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005100 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00005101
5102 // Now continue drilling into this expression.
5103
5104 // Skip past explicit casts.
5105 if (isa<ExplicitCastExpr>(E)) {
5106 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00005107 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005108 }
5109
John McCallbeb22aa2010-11-09 23:24:47 +00005110 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5111 // Do a somewhat different check with comparison operators.
5112 if (BO->isComparisonOp())
5113 return AnalyzeComparison(S, BO);
5114
Eli Friedman0fa06382012-01-26 23:34:06 +00005115 // And with simple assignments.
5116 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00005117 return AnalyzeAssignment(S, BO);
5118 }
John McCall323ed742010-05-06 08:58:33 +00005119
5120 // These break the otherwise-useful invariant below. Fortunately,
5121 // we don't really need to recurse into them, because any internal
5122 // expressions should have been analyzed already when they were
5123 // built into statements.
5124 if (isa<StmtExpr>(E)) return;
5125
5126 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005127 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00005128
5129 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00005130 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005131 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5132 bool IsLogicalOperator = BO && BO->isLogicalOp();
5133 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00005134 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00005135 if (!ChildExpr)
5136 continue;
5137
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005138 if (IsLogicalOperator &&
5139 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5140 // Ignore checking string literals that are in logical operators.
5141 continue;
5142 AnalyzeImplicitConversions(S, ChildExpr, CC);
5143 }
John McCall323ed742010-05-06 08:58:33 +00005144}
5145
5146} // end anonymous namespace
5147
5148/// Diagnoses "dangerous" implicit conversions within the given
5149/// expression (which is a full expression). Implements -Wconversion
5150/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005151///
5152/// \param CC the "context" location of the implicit conversion, i.e.
5153/// the most location of the syntactic entity requiring the implicit
5154/// conversion
5155void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005156 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00005157 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00005158 return;
5159
5160 // Don't diagnose for value- or type-dependent expressions.
5161 if (E->isTypeDependent() || E->isValueDependent())
5162 return;
5163
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005164 // Check for array bounds violations in cases where the check isn't triggered
5165 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5166 // ArraySubscriptExpr is on the RHS of a variable initialization.
5167 CheckArrayAccess(E);
5168
John McCallb4eb64d2010-10-08 02:01:28 +00005169 // This is not the right CC for (e.g.) a variable initialization.
5170 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005171}
5172
John McCall15d7d122010-11-11 03:21:53 +00005173void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
5174 FieldDecl *BitField,
5175 Expr *Init) {
5176 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
5177}
5178
Mike Stumpf8c49212010-01-21 03:59:47 +00005179/// CheckParmsForFunctionDef - Check that the parameters of the given
5180/// function are appropriate for the definition of a function. This
5181/// takes care of any checks that cannot be performed on the
5182/// declaration itself, e.g., that the types of each of the function
5183/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00005184bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
5185 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005186 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00005187 for (; P != PEnd; ++P) {
5188 ParmVarDecl *Param = *P;
5189
Mike Stumpf8c49212010-01-21 03:59:47 +00005190 // C99 6.7.5.3p4: the parameters in a parameter type list in a
5191 // function declarator that is part of a function definition of
5192 // that function shall not have incomplete type.
5193 //
5194 // This is also C++ [dcl.fct]p6.
5195 if (!Param->isInvalidDecl() &&
5196 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00005197 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005198 Param->setInvalidDecl();
5199 HasInvalidParm = true;
5200 }
5201
5202 // C99 6.9.1p5: If the declarator includes a parameter type list, the
5203 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00005204 if (CheckParameterNames &&
5205 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00005206 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005207 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00005208 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00005209
5210 // C99 6.7.5.3p12:
5211 // If the function declarator is not part of a definition of that
5212 // function, parameters may have incomplete type and may use the [*]
5213 // notation in their sequences of declarator specifiers to specify
5214 // variable length array types.
5215 QualType PType = Param->getOriginalType();
5216 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
5217 if (AT->getSizeModifier() == ArrayType::Star) {
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00005218 // FIXME: This diagnosic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00005219 // information is added for it.
5220 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
5221 }
5222 }
Mike Stumpf8c49212010-01-21 03:59:47 +00005223 }
5224
5225 return HasInvalidParm;
5226}
John McCallb7f4ffe2010-08-12 21:44:57 +00005227
5228/// CheckCastAlign - Implements -Wcast-align, which warns when a
5229/// pointer cast increases the alignment requirements.
5230void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
5231 // This is actually a lot of work to potentially be doing on every
5232 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005233 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
5234 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00005235 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00005236 return;
5237
5238 // Ignore dependent types.
5239 if (T->isDependentType() || Op->getType()->isDependentType())
5240 return;
5241
5242 // Require that the destination be a pointer type.
5243 const PointerType *DestPtr = T->getAs<PointerType>();
5244 if (!DestPtr) return;
5245
5246 // If the destination has alignment 1, we're done.
5247 QualType DestPointee = DestPtr->getPointeeType();
5248 if (DestPointee->isIncompleteType()) return;
5249 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
5250 if (DestAlign.isOne()) return;
5251
5252 // Require that the source be a pointer type.
5253 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
5254 if (!SrcPtr) return;
5255 QualType SrcPointee = SrcPtr->getPointeeType();
5256
5257 // Whitelist casts from cv void*. We already implicitly
5258 // whitelisted casts to cv void*, since they have alignment 1.
5259 // Also whitelist casts involving incomplete types, which implicitly
5260 // includes 'void'.
5261 if (SrcPointee->isIncompleteType()) return;
5262
5263 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
5264 if (SrcAlign >= DestAlign) return;
5265
5266 Diag(TRange.getBegin(), diag::warn_cast_align)
5267 << Op->getType() << T
5268 << static_cast<unsigned>(SrcAlign.getQuantity())
5269 << static_cast<unsigned>(DestAlign.getQuantity())
5270 << TRange << Op->getSourceRange();
5271}
5272
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005273static const Type* getElementType(const Expr *BaseExpr) {
5274 const Type* EltType = BaseExpr->getType().getTypePtr();
5275 if (EltType->isAnyPointerType())
5276 return EltType->getPointeeType().getTypePtr();
5277 else if (EltType->isArrayType())
5278 return EltType->getBaseElementTypeUnsafe();
5279 return EltType;
5280}
5281
Chandler Carruthc2684342011-08-05 09:10:50 +00005282/// \brief Check whether this array fits the idiom of a size-one tail padded
5283/// array member of a struct.
5284///
5285/// We avoid emitting out-of-bounds access warnings for such arrays as they are
5286/// commonly used to emulate flexible arrays in C89 code.
5287static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
5288 const NamedDecl *ND) {
5289 if (Size != 1 || !ND) return false;
5290
5291 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
5292 if (!FD) return false;
5293
5294 // Don't consider sizes resulting from macro expansions or template argument
5295 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00005296
5297 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005298 while (TInfo) {
5299 TypeLoc TL = TInfo->getTypeLoc();
5300 // Look through typedefs.
5301 const TypedefTypeLoc *TTL = dyn_cast<TypedefTypeLoc>(&TL);
5302 if (TTL) {
5303 const TypedefNameDecl *TDL = TTL->getTypedefNameDecl();
5304 TInfo = TDL->getTypeSourceInfo();
5305 continue;
5306 }
5307 ConstantArrayTypeLoc CTL = cast<ConstantArrayTypeLoc>(TL);
5308 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Sean Callanand2cf3482012-05-04 18:22:53 +00005309 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
5310 return false;
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005311 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00005312 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005313
5314 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00005315 if (!RD) return false;
5316 if (RD->isUnion()) return false;
5317 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
5318 if (!CRD->isStandardLayout()) return false;
5319 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005320
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00005321 // See if this is the last field decl in the record.
5322 const Decl *D = FD;
5323 while ((D = D->getNextDeclInContext()))
5324 if (isa<FieldDecl>(D))
5325 return false;
5326 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00005327}
5328
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005329void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005330 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00005331 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00005332 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005333 if (IndexExpr->isValueDependent())
5334 return;
5335
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00005336 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005337 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00005338 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005339 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00005340 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00005341 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00005342
Chandler Carruth34064582011-02-17 20:55:08 +00005343 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005344 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00005345 return;
Richard Smith25b009a2011-12-16 19:31:14 +00005346 if (IndexNegated)
5347 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00005348
Chandler Carruthba447122011-08-05 08:07:29 +00005349 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00005350 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5351 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00005352 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00005353 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00005354
Ted Kremenek9e060ca2011-02-23 23:06:04 +00005355 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00005356 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00005357 if (!size.isStrictlyPositive())
5358 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005359
5360 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00005361 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005362 // Make sure we're comparing apples to apples when comparing index to size
5363 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
5364 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00005365 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00005366 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005367 if (ptrarith_typesize != array_typesize) {
5368 // There's a cast to a different size type involved
5369 uint64_t ratio = array_typesize / ptrarith_typesize;
5370 // TODO: Be smarter about handling cases where array_typesize is not a
5371 // multiple of ptrarith_typesize
5372 if (ptrarith_typesize * ratio == array_typesize)
5373 size *= llvm::APInt(size.getBitWidth(), ratio);
5374 }
5375 }
5376
Chandler Carruth34064582011-02-17 20:55:08 +00005377 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005378 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005379 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005380 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005381
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005382 // For array subscripting the index must be less than size, but for pointer
5383 // arithmetic also allow the index (offset) to be equal to size since
5384 // computing the next address after the end of the array is legal and
5385 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00005386 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00005387 return;
5388
5389 // Also don't warn for arrays of size 1 which are members of some
5390 // structure. These are often used to approximate flexible arrays in C89
5391 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005392 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00005393 return;
Chandler Carruth34064582011-02-17 20:55:08 +00005394
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005395 // Suppress the warning if the subscript expression (as identified by the
5396 // ']' location) and the index expression are both from macro expansions
5397 // within a system header.
5398 if (ASE) {
5399 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
5400 ASE->getRBracketLoc());
5401 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
5402 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
5403 IndexExpr->getLocStart());
5404 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
5405 return;
5406 }
5407 }
5408
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005409 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005410 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005411 DiagID = diag::warn_array_index_exceeds_bounds;
5412
5413 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
5414 PDiag(DiagID) << index.toString(10, true)
5415 << size.toString(10, true)
5416 << (unsigned)size.getLimitedValue(~0U)
5417 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00005418 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005419 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005420 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005421 DiagID = diag::warn_ptr_arith_precedes_bounds;
5422 if (index.isNegative()) index = -index;
5423 }
5424
5425 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
5426 PDiag(DiagID) << index.toString(10, true)
5427 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00005428 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00005429
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00005430 if (!ND) {
5431 // Try harder to find a NamedDecl to point at in the note.
5432 while (const ArraySubscriptExpr *ASE =
5433 dyn_cast<ArraySubscriptExpr>(BaseExpr))
5434 BaseExpr = ASE->getBase()->IgnoreParenCasts();
5435 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5436 ND = dyn_cast<NamedDecl>(DRE->getDecl());
5437 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
5438 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
5439 }
5440
Chandler Carruth35001ca2011-02-17 21:10:52 +00005441 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005442 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
5443 PDiag(diag::note_array_index_out_of_bounds)
5444 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00005445}
5446
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005447void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005448 int AllowOnePastEnd = 0;
5449 while (expr) {
5450 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005451 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005452 case Stmt::ArraySubscriptExprClass: {
5453 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005454 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005455 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005456 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005457 }
5458 case Stmt::UnaryOperatorClass: {
5459 // Only unwrap the * and & unary operators
5460 const UnaryOperator *UO = cast<UnaryOperator>(expr);
5461 expr = UO->getSubExpr();
5462 switch (UO->getOpcode()) {
5463 case UO_AddrOf:
5464 AllowOnePastEnd++;
5465 break;
5466 case UO_Deref:
5467 AllowOnePastEnd--;
5468 break;
5469 default:
5470 return;
5471 }
5472 break;
5473 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005474 case Stmt::ConditionalOperatorClass: {
5475 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
5476 if (const Expr *lhs = cond->getLHS())
5477 CheckArrayAccess(lhs);
5478 if (const Expr *rhs = cond->getRHS())
5479 CheckArrayAccess(rhs);
5480 return;
5481 }
5482 default:
5483 return;
5484 }
Peter Collingbournef111d932011-04-15 00:35:48 +00005485 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005486}
John McCallf85e1932011-06-15 23:02:42 +00005487
5488//===--- CHECK: Objective-C retain cycles ----------------------------------//
5489
5490namespace {
5491 struct RetainCycleOwner {
5492 RetainCycleOwner() : Variable(0), Indirect(false) {}
5493 VarDecl *Variable;
5494 SourceRange Range;
5495 SourceLocation Loc;
5496 bool Indirect;
5497
5498 void setLocsFrom(Expr *e) {
5499 Loc = e->getExprLoc();
5500 Range = e->getSourceRange();
5501 }
5502 };
5503}
5504
5505/// Consider whether capturing the given variable can possibly lead to
5506/// a retain cycle.
5507static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00005508 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00005509 // lifetime. In MRR, it's captured strongly if the variable is
5510 // __block and has an appropriate type.
5511 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
5512 return false;
5513
5514 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00005515 if (ref)
5516 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00005517 return true;
5518}
5519
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005520static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00005521 while (true) {
5522 e = e->IgnoreParens();
5523 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
5524 switch (cast->getCastKind()) {
5525 case CK_BitCast:
5526 case CK_LValueBitCast:
5527 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00005528 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00005529 e = cast->getSubExpr();
5530 continue;
5531
John McCallf85e1932011-06-15 23:02:42 +00005532 default:
5533 return false;
5534 }
5535 }
5536
5537 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
5538 ObjCIvarDecl *ivar = ref->getDecl();
5539 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
5540 return false;
5541
5542 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005543 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00005544 return false;
5545
5546 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
5547 owner.Indirect = true;
5548 return true;
5549 }
5550
5551 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
5552 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
5553 if (!var) return false;
5554 return considerVariable(var, ref, owner);
5555 }
5556
John McCallf85e1932011-06-15 23:02:42 +00005557 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
5558 if (member->isArrow()) return false;
5559
5560 // Don't count this as an indirect ownership.
5561 e = member->getBase();
5562 continue;
5563 }
5564
John McCall4b9c2d22011-11-06 09:01:30 +00005565 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
5566 // Only pay attention to pseudo-objects on property references.
5567 ObjCPropertyRefExpr *pre
5568 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
5569 ->IgnoreParens());
5570 if (!pre) return false;
5571 if (pre->isImplicitProperty()) return false;
5572 ObjCPropertyDecl *property = pre->getExplicitProperty();
5573 if (!property->isRetaining() &&
5574 !(property->getPropertyIvarDecl() &&
5575 property->getPropertyIvarDecl()->getType()
5576 .getObjCLifetime() == Qualifiers::OCL_Strong))
5577 return false;
5578
5579 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005580 if (pre->isSuperReceiver()) {
5581 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
5582 if (!owner.Variable)
5583 return false;
5584 owner.Loc = pre->getLocation();
5585 owner.Range = pre->getSourceRange();
5586 return true;
5587 }
John McCall4b9c2d22011-11-06 09:01:30 +00005588 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
5589 ->getSourceExpr());
5590 continue;
5591 }
5592
John McCallf85e1932011-06-15 23:02:42 +00005593 // Array ivars?
5594
5595 return false;
5596 }
5597}
5598
5599namespace {
5600 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
5601 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
5602 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
5603 Variable(variable), Capturer(0) {}
5604
5605 VarDecl *Variable;
5606 Expr *Capturer;
5607
5608 void VisitDeclRefExpr(DeclRefExpr *ref) {
5609 if (ref->getDecl() == Variable && !Capturer)
5610 Capturer = ref;
5611 }
5612
John McCallf85e1932011-06-15 23:02:42 +00005613 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
5614 if (Capturer) return;
5615 Visit(ref->getBase());
5616 if (Capturer && ref->isFreeIvar())
5617 Capturer = ref;
5618 }
5619
5620 void VisitBlockExpr(BlockExpr *block) {
5621 // Look inside nested blocks
5622 if (block->getBlockDecl()->capturesVariable(Variable))
5623 Visit(block->getBlockDecl()->getBody());
5624 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00005625
5626 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
5627 if (Capturer) return;
5628 if (OVE->getSourceExpr())
5629 Visit(OVE->getSourceExpr());
5630 }
John McCallf85e1932011-06-15 23:02:42 +00005631 };
5632}
5633
5634/// Check whether the given argument is a block which captures a
5635/// variable.
5636static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
5637 assert(owner.Variable && owner.Loc.isValid());
5638
5639 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00005640
5641 // Look through [^{...} copy] and Block_copy(^{...}).
5642 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
5643 Selector Cmd = ME->getSelector();
5644 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
5645 e = ME->getInstanceReceiver();
5646 if (!e)
5647 return 0;
5648 e = e->IgnoreParenCasts();
5649 }
5650 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
5651 if (CE->getNumArgs() == 1) {
5652 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00005653 if (Fn) {
5654 const IdentifierInfo *FnI = Fn->getIdentifier();
5655 if (FnI && FnI->isStr("_Block_copy")) {
5656 e = CE->getArg(0)->IgnoreParenCasts();
5657 }
5658 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00005659 }
5660 }
5661
John McCallf85e1932011-06-15 23:02:42 +00005662 BlockExpr *block = dyn_cast<BlockExpr>(e);
5663 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
5664 return 0;
5665
5666 FindCaptureVisitor visitor(S.Context, owner.Variable);
5667 visitor.Visit(block->getBlockDecl()->getBody());
5668 return visitor.Capturer;
5669}
5670
5671static void diagnoseRetainCycle(Sema &S, Expr *capturer,
5672 RetainCycleOwner &owner) {
5673 assert(capturer);
5674 assert(owner.Variable && owner.Loc.isValid());
5675
5676 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
5677 << owner.Variable << capturer->getSourceRange();
5678 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
5679 << owner.Indirect << owner.Range;
5680}
5681
5682/// Check for a keyword selector that starts with the word 'add' or
5683/// 'set'.
5684static bool isSetterLikeSelector(Selector sel) {
5685 if (sel.isUnarySelector()) return false;
5686
Chris Lattner5f9e2722011-07-23 10:55:15 +00005687 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00005688 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00005689 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00005690 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00005691 else if (str.startswith("add")) {
5692 // Specially whitelist 'addOperationWithBlock:'.
5693 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
5694 return false;
5695 str = str.substr(3);
5696 }
John McCallf85e1932011-06-15 23:02:42 +00005697 else
5698 return false;
5699
5700 if (str.empty()) return true;
5701 return !islower(str.front());
5702}
5703
5704/// Check a message send to see if it's likely to cause a retain cycle.
5705void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
5706 // Only check instance methods whose selector looks like a setter.
5707 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
5708 return;
5709
5710 // Try to find a variable that the receiver is strongly owned by.
5711 RetainCycleOwner owner;
5712 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005713 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00005714 return;
5715 } else {
5716 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
5717 owner.Variable = getCurMethodDecl()->getSelfDecl();
5718 owner.Loc = msg->getSuperLoc();
5719 owner.Range = msg->getSuperLoc();
5720 }
5721
5722 // Check whether the receiver is captured by any of the arguments.
5723 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
5724 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
5725 return diagnoseRetainCycle(*this, capturer, owner);
5726}
5727
5728/// Check a property assign to see if it's likely to cause a retain cycle.
5729void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
5730 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005731 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00005732 return;
5733
5734 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
5735 diagnoseRetainCycle(*this, capturer, owner);
5736}
5737
Jordan Rosee10f4d32012-09-15 02:48:31 +00005738void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
5739 RetainCycleOwner Owner;
5740 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
5741 return;
5742
5743 // Because we don't have an expression for the variable, we have to set the
5744 // location explicitly here.
5745 Owner.Loc = Var->getLocation();
5746 Owner.Range = Var->getSourceRange();
5747
5748 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
5749 diagnoseRetainCycle(*this, Capturer, Owner);
5750}
5751
Ted Kremenekb1ea5102012-12-21 08:04:20 +00005752static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
5753 Qualifiers::ObjCLifetime LT,
5754 Expr *RHS, bool isProperty) {
5755 // Strip off any implicit cast added to get to the one ARC-specific.
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005756 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005757 if (cast->getCastKind() == CK_ARCConsumeObject) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00005758 S.Diag(Loc, diag::warn_arc_retained_assign)
5759 << (LT == Qualifiers::OCL_ExplicitNone)
5760 << (isProperty ? 0 : 1)
John McCallf85e1932011-06-15 23:02:42 +00005761 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005762 return true;
5763 }
5764 RHS = cast->getSubExpr();
5765 }
5766 return false;
John McCallf85e1932011-06-15 23:02:42 +00005767}
5768
Ted Kremenek9d084012012-12-21 08:04:28 +00005769static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
5770 Expr *RHS, bool isProperty) {
5771 // Check if RHS is an Objective-C object literal, which also can get
5772 // immediately zapped in a weak reference. Note that we explicitly
5773 // allow ObjCStringLiterals, since those are designed to never really die.
5774 RHS = RHS->IgnoreParenImpCasts();
5775 unsigned kind = 4;
5776 switch (RHS->getStmtClass()) {
5777 default:
5778 break;
5779 case Stmt::ObjCDictionaryLiteralClass:
5780 kind = 0;
5781 break;
5782 case Stmt::ObjCArrayLiteralClass:
5783 kind = 1;
5784 break;
5785 case Stmt::BlockExprClass:
5786 kind = 2;
5787 break;
5788 case Stmt::ObjCBoxedExprClass:
5789 kind = 3;
5790 break;
5791 }
5792 if (kind < 4) {
5793 S.Diag(Loc, diag::warn_arc_literal_assign)
5794 << kind
5795 << (isProperty ? 0 : 1)
5796 << RHS->getSourceRange();
5797 return true;
5798 }
5799 return false;
5800}
5801
Ted Kremenekb1ea5102012-12-21 08:04:20 +00005802bool Sema::checkUnsafeAssigns(SourceLocation Loc,
5803 QualType LHS, Expr *RHS) {
5804 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
5805
5806 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
5807 return false;
5808
5809 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
5810 return true;
5811
Ted Kremenek9d084012012-12-21 08:04:28 +00005812 if (LT == Qualifiers::OCL_Weak &&
5813 checkUnsafeAssignLiteral(*this, Loc, RHS, false))
5814 return true;
5815
Ted Kremenekb1ea5102012-12-21 08:04:20 +00005816 return false;
5817}
5818
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005819void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
5820 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005821 QualType LHSType;
5822 // PropertyRef on LHS type need be directly obtained from
5823 // its declaration as it has a PsuedoType.
5824 ObjCPropertyRefExpr *PRE
5825 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
5826 if (PRE && !PRE->isImplicitProperty()) {
5827 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5828 if (PD)
5829 LHSType = PD->getType();
5830 }
5831
5832 if (LHSType.isNull())
5833 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00005834
5835 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
5836
5837 if (LT == Qualifiers::OCL_Weak) {
5838 DiagnosticsEngine::Level Level =
5839 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
5840 if (Level != DiagnosticsEngine::Ignored)
5841 getCurFunction()->markSafeWeakUse(LHS);
5842 }
5843
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005844 if (checkUnsafeAssigns(Loc, LHSType, RHS))
5845 return;
Jordan Rose7a270482012-09-28 22:21:35 +00005846
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005847 // FIXME. Check for other life times.
5848 if (LT != Qualifiers::OCL_None)
5849 return;
5850
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005851 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005852 if (PRE->isImplicitProperty())
5853 return;
5854 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5855 if (!PD)
5856 return;
5857
Bill Wendlingad017fa2012-12-20 19:22:21 +00005858 unsigned Attributes = PD->getPropertyAttributes();
5859 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005860 // when 'assign' attribute was not explicitly specified
5861 // by user, ignore it and rely on property type itself
5862 // for lifetime info.
5863 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
5864 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
5865 LHSType->isObjCRetainableType())
5866 return;
5867
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005868 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005869 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005870 Diag(Loc, diag::warn_arc_retained_property_assign)
5871 << RHS->getSourceRange();
5872 return;
5873 }
5874 RHS = cast->getSubExpr();
5875 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005876 }
Bill Wendlingad017fa2012-12-20 19:22:21 +00005877 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00005878 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
5879 return;
Ted Kremenek9d084012012-12-21 08:04:28 +00005880 if (checkUnsafeAssignLiteral(*this, Loc, RHS, true))
5881 return;
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00005882 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005883 }
5884}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00005885
5886//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
5887
5888namespace {
5889bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
5890 SourceLocation StmtLoc,
5891 const NullStmt *Body) {
5892 // Do not warn if the body is a macro that expands to nothing, e.g:
5893 //
5894 // #define CALL(x)
5895 // if (condition)
5896 // CALL(0);
5897 //
5898 if (Body->hasLeadingEmptyMacro())
5899 return false;
5900
5901 // Get line numbers of statement and body.
5902 bool StmtLineInvalid;
5903 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
5904 &StmtLineInvalid);
5905 if (StmtLineInvalid)
5906 return false;
5907
5908 bool BodyLineInvalid;
5909 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
5910 &BodyLineInvalid);
5911 if (BodyLineInvalid)
5912 return false;
5913
5914 // Warn if null statement and body are on the same line.
5915 if (StmtLine != BodyLine)
5916 return false;
5917
5918 return true;
5919}
5920} // Unnamed namespace
5921
5922void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
5923 const Stmt *Body,
5924 unsigned DiagID) {
5925 // Since this is a syntactic check, don't emit diagnostic for template
5926 // instantiations, this just adds noise.
5927 if (CurrentInstantiationScope)
5928 return;
5929
5930 // The body should be a null statement.
5931 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5932 if (!NBody)
5933 return;
5934
5935 // Do the usual checks.
5936 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5937 return;
5938
5939 Diag(NBody->getSemiLoc(), DiagID);
5940 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5941}
5942
5943void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
5944 const Stmt *PossibleBody) {
5945 assert(!CurrentInstantiationScope); // Ensured by caller
5946
5947 SourceLocation StmtLoc;
5948 const Stmt *Body;
5949 unsigned DiagID;
5950 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
5951 StmtLoc = FS->getRParenLoc();
5952 Body = FS->getBody();
5953 DiagID = diag::warn_empty_for_body;
5954 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
5955 StmtLoc = WS->getCond()->getSourceRange().getEnd();
5956 Body = WS->getBody();
5957 DiagID = diag::warn_empty_while_body;
5958 } else
5959 return; // Neither `for' nor `while'.
5960
5961 // The body should be a null statement.
5962 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5963 if (!NBody)
5964 return;
5965
5966 // Skip expensive checks if diagnostic is disabled.
5967 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
5968 DiagnosticsEngine::Ignored)
5969 return;
5970
5971 // Do the usual checks.
5972 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5973 return;
5974
5975 // `for(...);' and `while(...);' are popular idioms, so in order to keep
5976 // noise level low, emit diagnostics only if for/while is followed by a
5977 // CompoundStmt, e.g.:
5978 // for (int i = 0; i < n; i++);
5979 // {
5980 // a(i);
5981 // }
5982 // or if for/while is followed by a statement with more indentation
5983 // than for/while itself:
5984 // for (int i = 0; i < n; i++);
5985 // a(i);
5986 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
5987 if (!ProbableTypo) {
5988 bool BodyColInvalid;
5989 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
5990 PossibleBody->getLocStart(),
5991 &BodyColInvalid);
5992 if (BodyColInvalid)
5993 return;
5994
5995 bool StmtColInvalid;
5996 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
5997 S->getLocStart(),
5998 &StmtColInvalid);
5999 if (StmtColInvalid)
6000 return;
6001
6002 if (BodyCol > StmtCol)
6003 ProbableTypo = true;
6004 }
6005
6006 if (ProbableTypo) {
6007 Diag(NBody->getSemiLoc(), DiagID);
6008 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6009 }
6010}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006011
6012//===--- Layout compatibility ----------------------------------------------//
6013
6014namespace {
6015
6016bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
6017
6018/// \brief Check if two enumeration types are layout-compatible.
6019bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
6020 // C++11 [dcl.enum] p8:
6021 // Two enumeration types are layout-compatible if they have the same
6022 // underlying type.
6023 return ED1->isComplete() && ED2->isComplete() &&
6024 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
6025}
6026
6027/// \brief Check if two fields are layout-compatible.
6028bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
6029 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
6030 return false;
6031
6032 if (Field1->isBitField() != Field2->isBitField())
6033 return false;
6034
6035 if (Field1->isBitField()) {
6036 // Make sure that the bit-fields are the same length.
6037 unsigned Bits1 = Field1->getBitWidthValue(C);
6038 unsigned Bits2 = Field2->getBitWidthValue(C);
6039
6040 if (Bits1 != Bits2)
6041 return false;
6042 }
6043
6044 return true;
6045}
6046
6047/// \brief Check if two standard-layout structs are layout-compatible.
6048/// (C++11 [class.mem] p17)
6049bool isLayoutCompatibleStruct(ASTContext &C,
6050 RecordDecl *RD1,
6051 RecordDecl *RD2) {
6052 // If both records are C++ classes, check that base classes match.
6053 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
6054 // If one of records is a CXXRecordDecl we are in C++ mode,
6055 // thus the other one is a CXXRecordDecl, too.
6056 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
6057 // Check number of base classes.
6058 if (D1CXX->getNumBases() != D2CXX->getNumBases())
6059 return false;
6060
6061 // Check the base classes.
6062 for (CXXRecordDecl::base_class_const_iterator
6063 Base1 = D1CXX->bases_begin(),
6064 BaseEnd1 = D1CXX->bases_end(),
6065 Base2 = D2CXX->bases_begin();
6066 Base1 != BaseEnd1;
6067 ++Base1, ++Base2) {
6068 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
6069 return false;
6070 }
6071 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
6072 // If only RD2 is a C++ class, it should have zero base classes.
6073 if (D2CXX->getNumBases() > 0)
6074 return false;
6075 }
6076
6077 // Check the fields.
6078 RecordDecl::field_iterator Field2 = RD2->field_begin(),
6079 Field2End = RD2->field_end(),
6080 Field1 = RD1->field_begin(),
6081 Field1End = RD1->field_end();
6082 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
6083 if (!isLayoutCompatible(C, *Field1, *Field2))
6084 return false;
6085 }
6086 if (Field1 != Field1End || Field2 != Field2End)
6087 return false;
6088
6089 return true;
6090}
6091
6092/// \brief Check if two standard-layout unions are layout-compatible.
6093/// (C++11 [class.mem] p18)
6094bool isLayoutCompatibleUnion(ASTContext &C,
6095 RecordDecl *RD1,
6096 RecordDecl *RD2) {
6097 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
6098 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
6099 Field2End = RD2->field_end();
6100 Field2 != Field2End; ++Field2) {
6101 UnmatchedFields.insert(*Field2);
6102 }
6103
6104 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
6105 Field1End = RD1->field_end();
6106 Field1 != Field1End; ++Field1) {
6107 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
6108 I = UnmatchedFields.begin(),
6109 E = UnmatchedFields.end();
6110
6111 for ( ; I != E; ++I) {
6112 if (isLayoutCompatible(C, *Field1, *I)) {
6113 bool Result = UnmatchedFields.erase(*I);
6114 (void) Result;
6115 assert(Result);
6116 break;
6117 }
6118 }
6119 if (I == E)
6120 return false;
6121 }
6122
6123 return UnmatchedFields.empty();
6124}
6125
6126bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
6127 if (RD1->isUnion() != RD2->isUnion())
6128 return false;
6129
6130 if (RD1->isUnion())
6131 return isLayoutCompatibleUnion(C, RD1, RD2);
6132 else
6133 return isLayoutCompatibleStruct(C, RD1, RD2);
6134}
6135
6136/// \brief Check if two types are layout-compatible in C++11 sense.
6137bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
6138 if (T1.isNull() || T2.isNull())
6139 return false;
6140
6141 // C++11 [basic.types] p11:
6142 // If two types T1 and T2 are the same type, then T1 and T2 are
6143 // layout-compatible types.
6144 if (C.hasSameType(T1, T2))
6145 return true;
6146
6147 T1 = T1.getCanonicalType().getUnqualifiedType();
6148 T2 = T2.getCanonicalType().getUnqualifiedType();
6149
6150 const Type::TypeClass TC1 = T1->getTypeClass();
6151 const Type::TypeClass TC2 = T2->getTypeClass();
6152
6153 if (TC1 != TC2)
6154 return false;
6155
6156 if (TC1 == Type::Enum) {
6157 return isLayoutCompatible(C,
6158 cast<EnumType>(T1)->getDecl(),
6159 cast<EnumType>(T2)->getDecl());
6160 } else if (TC1 == Type::Record) {
6161 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
6162 return false;
6163
6164 return isLayoutCompatible(C,
6165 cast<RecordType>(T1)->getDecl(),
6166 cast<RecordType>(T2)->getDecl());
6167 }
6168
6169 return false;
6170}
6171}
6172
6173//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
6174
6175namespace {
6176/// \brief Given a type tag expression find the type tag itself.
6177///
6178/// \param TypeExpr Type tag expression, as it appears in user's code.
6179///
6180/// \param VD Declaration of an identifier that appears in a type tag.
6181///
6182/// \param MagicValue Type tag magic value.
6183bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
6184 const ValueDecl **VD, uint64_t *MagicValue) {
6185 while(true) {
6186 if (!TypeExpr)
6187 return false;
6188
6189 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
6190
6191 switch (TypeExpr->getStmtClass()) {
6192 case Stmt::UnaryOperatorClass: {
6193 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
6194 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
6195 TypeExpr = UO->getSubExpr();
6196 continue;
6197 }
6198 return false;
6199 }
6200
6201 case Stmt::DeclRefExprClass: {
6202 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
6203 *VD = DRE->getDecl();
6204 return true;
6205 }
6206
6207 case Stmt::IntegerLiteralClass: {
6208 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
6209 llvm::APInt MagicValueAPInt = IL->getValue();
6210 if (MagicValueAPInt.getActiveBits() <= 64) {
6211 *MagicValue = MagicValueAPInt.getZExtValue();
6212 return true;
6213 } else
6214 return false;
6215 }
6216
6217 case Stmt::BinaryConditionalOperatorClass:
6218 case Stmt::ConditionalOperatorClass: {
6219 const AbstractConditionalOperator *ACO =
6220 cast<AbstractConditionalOperator>(TypeExpr);
6221 bool Result;
6222 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
6223 if (Result)
6224 TypeExpr = ACO->getTrueExpr();
6225 else
6226 TypeExpr = ACO->getFalseExpr();
6227 continue;
6228 }
6229 return false;
6230 }
6231
6232 case Stmt::BinaryOperatorClass: {
6233 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
6234 if (BO->getOpcode() == BO_Comma) {
6235 TypeExpr = BO->getRHS();
6236 continue;
6237 }
6238 return false;
6239 }
6240
6241 default:
6242 return false;
6243 }
6244 }
6245}
6246
6247/// \brief Retrieve the C type corresponding to type tag TypeExpr.
6248///
6249/// \param TypeExpr Expression that specifies a type tag.
6250///
6251/// \param MagicValues Registered magic values.
6252///
6253/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
6254/// kind.
6255///
6256/// \param TypeInfo Information about the corresponding C type.
6257///
6258/// \returns true if the corresponding C type was found.
6259bool GetMatchingCType(
6260 const IdentifierInfo *ArgumentKind,
6261 const Expr *TypeExpr, const ASTContext &Ctx,
6262 const llvm::DenseMap<Sema::TypeTagMagicValue,
6263 Sema::TypeTagData> *MagicValues,
6264 bool &FoundWrongKind,
6265 Sema::TypeTagData &TypeInfo) {
6266 FoundWrongKind = false;
6267
6268 // Variable declaration that has type_tag_for_datatype attribute.
6269 const ValueDecl *VD = NULL;
6270
6271 uint64_t MagicValue;
6272
6273 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
6274 return false;
6275
6276 if (VD) {
6277 for (specific_attr_iterator<TypeTagForDatatypeAttr>
6278 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
6279 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
6280 I != E; ++I) {
6281 if (I->getArgumentKind() != ArgumentKind) {
6282 FoundWrongKind = true;
6283 return false;
6284 }
6285 TypeInfo.Type = I->getMatchingCType();
6286 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
6287 TypeInfo.MustBeNull = I->getMustBeNull();
6288 return true;
6289 }
6290 return false;
6291 }
6292
6293 if (!MagicValues)
6294 return false;
6295
6296 llvm::DenseMap<Sema::TypeTagMagicValue,
6297 Sema::TypeTagData>::const_iterator I =
6298 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
6299 if (I == MagicValues->end())
6300 return false;
6301
6302 TypeInfo = I->second;
6303 return true;
6304}
6305} // unnamed namespace
6306
6307void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
6308 uint64_t MagicValue, QualType Type,
6309 bool LayoutCompatible,
6310 bool MustBeNull) {
6311 if (!TypeTagForDatatypeMagicValues)
6312 TypeTagForDatatypeMagicValues.reset(
6313 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
6314
6315 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
6316 (*TypeTagForDatatypeMagicValues)[Magic] =
6317 TypeTagData(Type, LayoutCompatible, MustBeNull);
6318}
6319
6320namespace {
6321bool IsSameCharType(QualType T1, QualType T2) {
6322 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
6323 if (!BT1)
6324 return false;
6325
6326 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
6327 if (!BT2)
6328 return false;
6329
6330 BuiltinType::Kind T1Kind = BT1->getKind();
6331 BuiltinType::Kind T2Kind = BT2->getKind();
6332
6333 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
6334 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
6335 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
6336 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
6337}
6338} // unnamed namespace
6339
6340void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
6341 const Expr * const *ExprArgs) {
6342 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
6343 bool IsPointerAttr = Attr->getIsPointer();
6344
6345 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
6346 bool FoundWrongKind;
6347 TypeTagData TypeInfo;
6348 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
6349 TypeTagForDatatypeMagicValues.get(),
6350 FoundWrongKind, TypeInfo)) {
6351 if (FoundWrongKind)
6352 Diag(TypeTagExpr->getExprLoc(),
6353 diag::warn_type_tag_for_datatype_wrong_kind)
6354 << TypeTagExpr->getSourceRange();
6355 return;
6356 }
6357
6358 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
6359 if (IsPointerAttr) {
6360 // Skip implicit cast of pointer to `void *' (as a function argument).
6361 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5a249802012-11-03 16:07:49 +00006362 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkob57ce4e2012-11-03 22:10:18 +00006363 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006364 ArgumentExpr = ICE->getSubExpr();
6365 }
6366 QualType ArgumentType = ArgumentExpr->getType();
6367
6368 // Passing a `void*' pointer shouldn't trigger a warning.
6369 if (IsPointerAttr && ArgumentType->isVoidPointerType())
6370 return;
6371
6372 if (TypeInfo.MustBeNull) {
6373 // Type tag with matching void type requires a null pointer.
6374 if (!ArgumentExpr->isNullPointerConstant(Context,
6375 Expr::NPC_ValueDependentIsNotNull)) {
6376 Diag(ArgumentExpr->getExprLoc(),
6377 diag::warn_type_safety_null_pointer_required)
6378 << ArgumentKind->getName()
6379 << ArgumentExpr->getSourceRange()
6380 << TypeTagExpr->getSourceRange();
6381 }
6382 return;
6383 }
6384
6385 QualType RequiredType = TypeInfo.Type;
6386 if (IsPointerAttr)
6387 RequiredType = Context.getPointerType(RequiredType);
6388
6389 bool mismatch = false;
6390 if (!TypeInfo.LayoutCompatible) {
6391 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
6392
6393 // C++11 [basic.fundamental] p1:
6394 // Plain char, signed char, and unsigned char are three distinct types.
6395 //
6396 // But we treat plain `char' as equivalent to `signed char' or `unsigned
6397 // char' depending on the current char signedness mode.
6398 if (mismatch)
6399 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
6400 RequiredType->getPointeeType())) ||
6401 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
6402 mismatch = false;
6403 } else
6404 if (IsPointerAttr)
6405 mismatch = !isLayoutCompatible(Context,
6406 ArgumentType->getPointeeType(),
6407 RequiredType->getPointeeType());
6408 else
6409 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
6410
6411 if (mismatch)
6412 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
6413 << ArgumentType << ArgumentKind->getName()
6414 << TypeInfo.LayoutCompatible << RequiredType
6415 << ArgumentExpr->getSourceRange()
6416 << TypeTagExpr->getSourceRange();
6417}