blob: a58e9049e48c9201d1828e7ae251f805a0d71612 [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 McCall5f8d6042011-08-27 01:09:30 +000015#include "clang/Sema/Initialization.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Sema.h"
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Eli Friedman276b0612011-10-11 02:20:01 +000018#include "clang/Sema/Initialization.h"
Richard Smith831421f2012-06-25 20:30:08 +000019#include "clang/Sema/Lookup.h"
John McCall781472f2010-08-25 08:40:02 +000020#include "clang/Sema/ScopeInfo.h"
Ted Kremenek826a3452010-07-16 02:11:22 +000021#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000022#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000023#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000024#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000025#include "clang/AST/DeclObjC.h"
David Blaikiebe0ee872012-05-15 16:56:36 +000026#include "clang/AST/Expr.h"
Ted Kremenek23245122007-08-20 16:18:38 +000027#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000028#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000029#include "clang/AST/EvaluatedExprVisitor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000030#include "clang/AST/DeclObjC.h"
31#include "clang/AST/StmtCXX.h"
32#include "clang/AST/StmtObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000033#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000034#include "llvm/ADT/BitVector.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000035#include "llvm/ADT/SmallString.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000036#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000037#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000038#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000039#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000040#include "clang/Basic/ConvertUTF.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:
Chandler Carruthd2014572010-07-09 18:59:35 +0000269 return SemaBuiltinAtomicOverloaded(move(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: \
273 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::AO##ID);
274#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
302 return move(TheCallResult);
303}
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
Nate Begeman0d15c532010-06-13 04:47:52 +0000358 unsigned 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);
376 if ((TV > 63) || (mask & (1 << 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;
440 };
441
442 // We can't check the value of a dependent argument.
443 if (TheCall->getArg(i)->isTypeDependent() ||
444 TheCall->getArg(i)->isValueDependent())
445 return false;
446
447 // Check that the immediate argument is actually a constant.
448 llvm::APSInt Result;
449 if (SemaBuiltinConstantArg(TheCall, i, Result))
450 return true;
451
452 // Range check against the upper/lower values for this instruction.
453 unsigned Val = Result.getZExtValue();
454 if (Val < l || Val > u)
455 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
456 << l << u << TheCall->getArg(i)->getSourceRange();
457
458 return false;
459}
460
Richard Smith831421f2012-06-25 20:30:08 +0000461/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
462/// parameter with the FormatAttr's correct format_idx and firstDataArg.
463/// Returns true when the format fits the function and the FormatStringInfo has
464/// been populated.
465bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
466 FormatStringInfo *FSI) {
467 FSI->HasVAListArg = Format->getFirstArg() == 0;
468 FSI->FormatIdx = Format->getFormatIdx() - 1;
469 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssond406bf02009-08-16 01:56:34 +0000470
Richard Smith831421f2012-06-25 20:30:08 +0000471 // The way the format attribute works in GCC, the implicit this argument
472 // of member functions is counted. However, it doesn't appear in our own
473 // lists, so decrement format_idx in that case.
474 if (IsCXXMember) {
475 if(FSI->FormatIdx == 0)
476 return false;
477 --FSI->FormatIdx;
478 if (FSI->FirstDataArg != 0)
479 --FSI->FirstDataArg;
480 }
481 return true;
482}
Mike Stump1eb44332009-09-09 15:08:12 +0000483
Richard Smith831421f2012-06-25 20:30:08 +0000484/// Handles the checks for format strings, non-POD arguments to vararg
485/// functions, and NULL arguments passed to non-NULL parameters.
486void Sema::checkCall(NamedDecl *FDecl, Expr **Args,
487 unsigned NumArgs,
488 unsigned NumProtoArgs,
489 bool IsMemberFunction,
490 SourceLocation Loc,
491 SourceRange Range,
492 VariadicCallType CallType) {
Daniel Dunbarde454282008-10-02 18:44:07 +0000493 // FIXME: This mechanism should be abstracted to be less fragile and
494 // more efficient. For example, just map function ids to custom
495 // handlers.
496
Ted Kremenekc82faca2010-09-09 04:33:05 +0000497 // Printf and scanf checking.
Richard Smith831421f2012-06-25 20:30:08 +0000498 bool HandledFormatString = false;
Ted Kremenekc82faca2010-09-09 04:33:05 +0000499 for (specific_attr_iterator<FormatAttr>
Richard Smith831421f2012-06-25 20:30:08 +0000500 I = FDecl->specific_attr_begin<FormatAttr>(),
501 E = FDecl->specific_attr_end<FormatAttr>(); I != E ; ++I)
Jordan Roseddcfbc92012-07-19 18:10:23 +0000502 if (CheckFormatArguments(*I, Args, NumArgs, IsMemberFunction, CallType,
503 Loc, Range))
Richard Smith831421f2012-06-25 20:30:08 +0000504 HandledFormatString = true;
505
506 // Refuse POD arguments that weren't caught by the format string
507 // checks above.
508 if (!HandledFormatString && CallType != VariadicDoesNotApply)
509 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < NumArgs; ++ArgIdx)
510 variadicArgumentPODCheck(Args[ArgIdx], CallType);
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Ted Kremenekc82faca2010-09-09 04:33:05 +0000512 for (specific_attr_iterator<NonNullAttr>
Richard Smith831421f2012-06-25 20:30:08 +0000513 I = FDecl->specific_attr_begin<NonNullAttr>(),
514 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
515 CheckNonNullArguments(*I, Args, Loc);
516}
517
518/// CheckConstructorCall - Check a constructor call for correctness and safety
519/// properties not enforced by the C type system.
520void Sema::CheckConstructorCall(FunctionDecl *FDecl, Expr **Args,
521 unsigned NumArgs,
522 const FunctionProtoType *Proto,
523 SourceLocation Loc) {
524 VariadicCallType CallType =
525 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
526 checkCall(FDecl, Args, NumArgs, Proto->getNumArgs(),
527 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
528}
529
530/// CheckFunctionCall - Check a direct function call for various correctness
531/// and safety properties not strictly enforced by the C type system.
532bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
533 const FunctionProtoType *Proto) {
534 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall);
535 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
536 TheCall->getCallee());
537 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
538 checkCall(FDecl, TheCall->getArgs(), TheCall->getNumArgs(), NumProtoArgs,
539 IsMemberFunction, TheCall->getRParenLoc(),
540 TheCall->getCallee()->getSourceRange(), CallType);
541
542 IdentifierInfo *FnInfo = FDecl->getIdentifier();
543 // None of the checks below are needed for functions that don't have
544 // simple names (e.g., C++ conversion functions).
545 if (!FnInfo)
546 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +0000547
Anna Zaks0a151a12012-01-17 00:37:07 +0000548 unsigned CMId = FDecl->getMemoryFunctionKind();
549 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000550 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000551
Anna Zaksd9b859a2012-01-13 21:52:01 +0000552 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000553 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000554 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000555 else if (CMId == Builtin::BIstrncat)
556 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000557 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000558 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000559
Anders Carlssond406bf02009-08-16 01:56:34 +0000560 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000561}
562
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000563bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
564 Expr **Args, unsigned NumArgs) {
Richard Smith831421f2012-06-25 20:30:08 +0000565 VariadicCallType CallType =
566 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000567
Richard Smith831421f2012-06-25 20:30:08 +0000568 checkCall(Method, Args, NumArgs, Method->param_size(),
569 /*IsMemberFunction=*/false,
570 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000571
572 return false;
573}
574
Richard Smith831421f2012-06-25 20:30:08 +0000575bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall,
576 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000577 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
578 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000579 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000580
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000581 QualType Ty = V->getType();
582 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000583 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000584
Richard Smith831421f2012-06-25 20:30:08 +0000585 VariadicCallType CallType =
586 Proto && Proto->isVariadic() ? VariadicBlock : VariadicDoesNotApply ;
587 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000588
Richard Smith831421f2012-06-25 20:30:08 +0000589 checkCall(NDecl, TheCall->getArgs(), TheCall->getNumArgs(),
590 NumProtoArgs, /*IsMemberFunction=*/false,
591 TheCall->getRParenLoc(),
592 TheCall->getCallee()->getSourceRange(), CallType);
593
Anders Carlssond406bf02009-08-16 01:56:34 +0000594 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000595}
596
Richard Smithff34d402012-04-12 05:08:17 +0000597ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
598 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000599 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
600 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000601
Richard Smithff34d402012-04-12 05:08:17 +0000602 // All these operations take one of the following forms:
603 enum {
604 // C __c11_atomic_init(A *, C)
605 Init,
606 // C __c11_atomic_load(A *, int)
607 Load,
608 // void __atomic_load(A *, CP, int)
609 Copy,
610 // C __c11_atomic_add(A *, M, int)
611 Arithmetic,
612 // C __atomic_exchange_n(A *, CP, int)
613 Xchg,
614 // void __atomic_exchange(A *, C *, CP, int)
615 GNUXchg,
616 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
617 C11CmpXchg,
618 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
619 GNUCmpXchg
620 } Form = Init;
621 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
622 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
623 // where:
624 // C is an appropriate type,
625 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
626 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
627 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
628 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000629
Richard Smithff34d402012-04-12 05:08:17 +0000630 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
631 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
632 && "need to update code for modified C11 atomics");
633 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
634 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
635 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
636 Op == AtomicExpr::AO__atomic_store_n ||
637 Op == AtomicExpr::AO__atomic_exchange_n ||
638 Op == AtomicExpr::AO__atomic_compare_exchange_n;
639 bool IsAddSub = false;
640
641 switch (Op) {
642 case AtomicExpr::AO__c11_atomic_init:
643 Form = Init;
644 break;
645
646 case AtomicExpr::AO__c11_atomic_load:
647 case AtomicExpr::AO__atomic_load_n:
648 Form = Load;
649 break;
650
651 case AtomicExpr::AO__c11_atomic_store:
652 case AtomicExpr::AO__atomic_load:
653 case AtomicExpr::AO__atomic_store:
654 case AtomicExpr::AO__atomic_store_n:
655 Form = Copy;
656 break;
657
658 case AtomicExpr::AO__c11_atomic_fetch_add:
659 case AtomicExpr::AO__c11_atomic_fetch_sub:
660 case AtomicExpr::AO__atomic_fetch_add:
661 case AtomicExpr::AO__atomic_fetch_sub:
662 case AtomicExpr::AO__atomic_add_fetch:
663 case AtomicExpr::AO__atomic_sub_fetch:
664 IsAddSub = true;
665 // Fall through.
666 case AtomicExpr::AO__c11_atomic_fetch_and:
667 case AtomicExpr::AO__c11_atomic_fetch_or:
668 case AtomicExpr::AO__c11_atomic_fetch_xor:
669 case AtomicExpr::AO__atomic_fetch_and:
670 case AtomicExpr::AO__atomic_fetch_or:
671 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000672 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000673 case AtomicExpr::AO__atomic_and_fetch:
674 case AtomicExpr::AO__atomic_or_fetch:
675 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000676 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000677 Form = Arithmetic;
678 break;
679
680 case AtomicExpr::AO__c11_atomic_exchange:
681 case AtomicExpr::AO__atomic_exchange_n:
682 Form = Xchg;
683 break;
684
685 case AtomicExpr::AO__atomic_exchange:
686 Form = GNUXchg;
687 break;
688
689 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
690 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
691 Form = C11CmpXchg;
692 break;
693
694 case AtomicExpr::AO__atomic_compare_exchange:
695 case AtomicExpr::AO__atomic_compare_exchange_n:
696 Form = GNUCmpXchg;
697 break;
698 }
699
700 // Check we have the right number of arguments.
701 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000702 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000703 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000704 << TheCall->getCallee()->getSourceRange();
705 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000706 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
707 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000708 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000709 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000710 << TheCall->getCallee()->getSourceRange();
711 return ExprError();
712 }
713
Richard Smithff34d402012-04-12 05:08:17 +0000714 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000715 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000716 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
717 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
718 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +0000719 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +0000720 << Ptr->getType() << Ptr->getSourceRange();
721 return ExprError();
722 }
723
Richard Smithff34d402012-04-12 05:08:17 +0000724 // For a __c11 builtin, this should be a pointer to an _Atomic type.
725 QualType AtomTy = pointerType->getPointeeType(); // 'A'
726 QualType ValType = AtomTy; // 'C'
727 if (IsC11) {
728 if (!AtomTy->isAtomicType()) {
729 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
730 << Ptr->getType() << Ptr->getSourceRange();
731 return ExprError();
732 }
733 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +0000734 }
Eli Friedman276b0612011-10-11 02:20:01 +0000735
Richard Smithff34d402012-04-12 05:08:17 +0000736 // For an arithmetic operation, the implied arithmetic must be well-formed.
737 if (Form == Arithmetic) {
738 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
739 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
740 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
741 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
742 return ExprError();
743 }
744 if (!IsAddSub && !ValType->isIntegerType()) {
745 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
746 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
747 return ExprError();
748 }
749 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
750 // For __atomic_*_n operations, the value type must be a scalar integral or
751 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +0000752 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +0000753 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
754 return ExprError();
755 }
756
757 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
758 // For GNU atomics, require a trivially-copyable type. This is not part of
759 // the GNU atomics specification, but we enforce it for sanity.
760 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +0000761 << Ptr->getType() << Ptr->getSourceRange();
762 return ExprError();
763 }
764
Richard Smithff34d402012-04-12 05:08:17 +0000765 // FIXME: For any builtin other than a load, the ValType must not be
766 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +0000767
768 switch (ValType.getObjCLifetime()) {
769 case Qualifiers::OCL_None:
770 case Qualifiers::OCL_ExplicitNone:
771 // okay
772 break;
773
774 case Qualifiers::OCL_Weak:
775 case Qualifiers::OCL_Strong:
776 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +0000777 // FIXME: Can this happen? By this point, ValType should be known
778 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +0000779 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
780 << ValType << Ptr->getSourceRange();
781 return ExprError();
782 }
783
784 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +0000785 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000786 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +0000787 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +0000788 ResultType = Context.BoolTy;
789
Richard Smithff34d402012-04-12 05:08:17 +0000790 // The type of a parameter passed 'by value'. In the GNU atomics, such
791 // arguments are actually passed as pointers.
792 QualType ByValType = ValType; // 'CP'
793 if (!IsC11 && !IsN)
794 ByValType = Ptr->getType();
795
Eli Friedman276b0612011-10-11 02:20:01 +0000796 // The first argument --- the pointer --- has a fixed type; we
797 // deduce the types of the rest of the arguments accordingly. Walk
798 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +0000799 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +0000800 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +0000801 if (i < NumVals[Form] + 1) {
802 switch (i) {
803 case 1:
804 // The second argument is the non-atomic operand. For arithmetic, this
805 // is always passed by value, and for a compare_exchange it is always
806 // passed by address. For the rest, GNU uses by-address and C11 uses
807 // by-value.
808 assert(Form != Load);
809 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
810 Ty = ValType;
811 else if (Form == Copy || Form == Xchg)
812 Ty = ByValType;
813 else if (Form == Arithmetic)
814 Ty = Context.getPointerDiffType();
815 else
816 Ty = Context.getPointerType(ValType.getUnqualifiedType());
817 break;
818 case 2:
819 // The third argument to compare_exchange / GNU exchange is a
820 // (pointer to a) desired value.
821 Ty = ByValType;
822 break;
823 case 3:
824 // The fourth argument to GNU compare_exchange is a 'weak' flag.
825 Ty = Context.BoolTy;
826 break;
827 }
Eli Friedman276b0612011-10-11 02:20:01 +0000828 } else {
829 // The order(s) are always converted to int.
830 Ty = Context.IntTy;
831 }
Richard Smithff34d402012-04-12 05:08:17 +0000832
Eli Friedman276b0612011-10-11 02:20:01 +0000833 InitializedEntity Entity =
834 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +0000835 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +0000836 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
837 if (Arg.isInvalid())
838 return true;
839 TheCall->setArg(i, Arg.get());
840 }
841
Richard Smithff34d402012-04-12 05:08:17 +0000842 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000843 SmallVector<Expr*, 5> SubExprs;
844 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +0000845 switch (Form) {
846 case Init:
847 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +0000848 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000849 break;
850 case Load:
851 SubExprs.push_back(TheCall->getArg(1)); // Order
852 break;
853 case Copy:
854 case Arithmetic:
855 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000856 SubExprs.push_back(TheCall->getArg(2)); // Order
857 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000858 break;
859 case GNUXchg:
860 // Note, AtomicExpr::getVal2() has a special case for this atomic.
861 SubExprs.push_back(TheCall->getArg(3)); // Order
862 SubExprs.push_back(TheCall->getArg(1)); // Val1
863 SubExprs.push_back(TheCall->getArg(2)); // Val2
864 break;
865 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000866 SubExprs.push_back(TheCall->getArg(3)); // Order
867 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000868 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +0000869 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +0000870 break;
871 case GNUCmpXchg:
872 SubExprs.push_back(TheCall->getArg(4)); // Order
873 SubExprs.push_back(TheCall->getArg(1)); // Val1
874 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
875 SubExprs.push_back(TheCall->getArg(2)); // Val2
876 SubExprs.push_back(TheCall->getArg(3)); // Weak
877 break;
Eli Friedman276b0612011-10-11 02:20:01 +0000878 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000879
880 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
881 SubExprs.data(), SubExprs.size(),
882 ResultType, Op,
883 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000884}
885
886
John McCall5f8d6042011-08-27 01:09:30 +0000887/// checkBuiltinArgument - Given a call to a builtin function, perform
888/// normal type-checking on the given argument, updating the call in
889/// place. This is useful when a builtin function requires custom
890/// type-checking for some of its arguments but not necessarily all of
891/// them.
892///
893/// Returns true on error.
894static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
895 FunctionDecl *Fn = E->getDirectCallee();
896 assert(Fn && "builtin call without direct callee!");
897
898 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
899 InitializedEntity Entity =
900 InitializedEntity::InitializeParameter(S.Context, Param);
901
902 ExprResult Arg = E->getArg(0);
903 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
904 if (Arg.isInvalid())
905 return true;
906
907 E->setArg(ArgIndex, Arg.take());
908 return false;
909}
910
Chris Lattner5caa3702009-05-08 06:58:22 +0000911/// SemaBuiltinAtomicOverloaded - We have a call to a function like
912/// __sync_fetch_and_add, which is an overloaded function based on the pointer
913/// type of its first argument. The main ActOnCallExpr routines have already
914/// promoted the types of arguments because all of these calls are prototyped as
915/// void(...).
916///
917/// This function goes through and does final semantic checking for these
918/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000919ExprResult
920Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000921 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000922 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
923 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
924
925 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000926 if (TheCall->getNumArgs() < 1) {
927 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
928 << 0 << 1 << TheCall->getNumArgs()
929 << TheCall->getCallee()->getSourceRange();
930 return ExprError();
931 }
Mike Stump1eb44332009-09-09 15:08:12 +0000932
Chris Lattner5caa3702009-05-08 06:58:22 +0000933 // Inspect the first argument of the atomic builtin. This should always be
934 // a pointer type, whose element is an integral scalar or pointer type.
935 // Because it is a pointer type, we don't have to worry about any implicit
936 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000937 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000938 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +0000939 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
940 if (FirstArgResult.isInvalid())
941 return ExprError();
942 FirstArg = FirstArgResult.take();
943 TheCall->setArg(0, FirstArg);
944
John McCallf85e1932011-06-15 23:02:42 +0000945 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
946 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000947 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
948 << FirstArg->getType() << FirstArg->getSourceRange();
949 return ExprError();
950 }
Mike Stump1eb44332009-09-09 15:08:12 +0000951
John McCallf85e1932011-06-15 23:02:42 +0000952 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000953 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000954 !ValType->isBlockPointerType()) {
955 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
956 << FirstArg->getType() << FirstArg->getSourceRange();
957 return ExprError();
958 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000959
John McCallf85e1932011-06-15 23:02:42 +0000960 switch (ValType.getObjCLifetime()) {
961 case Qualifiers::OCL_None:
962 case Qualifiers::OCL_ExplicitNone:
963 // okay
964 break;
965
966 case Qualifiers::OCL_Weak:
967 case Qualifiers::OCL_Strong:
968 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000969 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000970 << ValType << FirstArg->getSourceRange();
971 return ExprError();
972 }
973
John McCallb45ae252011-10-05 07:41:44 +0000974 // Strip any qualifiers off ValType.
975 ValType = ValType.getUnqualifiedType();
976
Chandler Carruth8d13d222010-07-18 20:54:12 +0000977 // The majority of builtins return a value, but a few have special return
978 // types, so allow them to override appropriately below.
979 QualType ResultType = ValType;
980
Chris Lattner5caa3702009-05-08 06:58:22 +0000981 // We need to figure out which concrete builtin this maps onto. For example,
982 // __sync_fetch_and_add with a 2 byte object turns into
983 // __sync_fetch_and_add_2.
984#define BUILTIN_ROW(x) \
985 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
986 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000987
Chris Lattner5caa3702009-05-08 06:58:22 +0000988 static const unsigned BuiltinIndices[][5] = {
989 BUILTIN_ROW(__sync_fetch_and_add),
990 BUILTIN_ROW(__sync_fetch_and_sub),
991 BUILTIN_ROW(__sync_fetch_and_or),
992 BUILTIN_ROW(__sync_fetch_and_and),
993 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000994
Chris Lattner5caa3702009-05-08 06:58:22 +0000995 BUILTIN_ROW(__sync_add_and_fetch),
996 BUILTIN_ROW(__sync_sub_and_fetch),
997 BUILTIN_ROW(__sync_and_and_fetch),
998 BUILTIN_ROW(__sync_or_and_fetch),
999 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001000
Chris Lattner5caa3702009-05-08 06:58:22 +00001001 BUILTIN_ROW(__sync_val_compare_and_swap),
1002 BUILTIN_ROW(__sync_bool_compare_and_swap),
1003 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001004 BUILTIN_ROW(__sync_lock_release),
1005 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001006 };
Mike Stump1eb44332009-09-09 15:08:12 +00001007#undef BUILTIN_ROW
1008
Chris Lattner5caa3702009-05-08 06:58:22 +00001009 // Determine the index of the size.
1010 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001011 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001012 case 1: SizeIndex = 0; break;
1013 case 2: SizeIndex = 1; break;
1014 case 4: SizeIndex = 2; break;
1015 case 8: SizeIndex = 3; break;
1016 case 16: SizeIndex = 4; break;
1017 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001018 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1019 << FirstArg->getType() << FirstArg->getSourceRange();
1020 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001021 }
Mike Stump1eb44332009-09-09 15:08:12 +00001022
Chris Lattner5caa3702009-05-08 06:58:22 +00001023 // Each of these builtins has one pointer argument, followed by some number of
1024 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1025 // that we ignore. Find out which row of BuiltinIndices to read from as well
1026 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001027 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001028 unsigned BuiltinIndex, NumFixed = 1;
1029 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001030 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001031 case Builtin::BI__sync_fetch_and_add:
1032 case Builtin::BI__sync_fetch_and_add_1:
1033 case Builtin::BI__sync_fetch_and_add_2:
1034 case Builtin::BI__sync_fetch_and_add_4:
1035 case Builtin::BI__sync_fetch_and_add_8:
1036 case Builtin::BI__sync_fetch_and_add_16:
1037 BuiltinIndex = 0;
1038 break;
1039
1040 case Builtin::BI__sync_fetch_and_sub:
1041 case Builtin::BI__sync_fetch_and_sub_1:
1042 case Builtin::BI__sync_fetch_and_sub_2:
1043 case Builtin::BI__sync_fetch_and_sub_4:
1044 case Builtin::BI__sync_fetch_and_sub_8:
1045 case Builtin::BI__sync_fetch_and_sub_16:
1046 BuiltinIndex = 1;
1047 break;
1048
1049 case Builtin::BI__sync_fetch_and_or:
1050 case Builtin::BI__sync_fetch_and_or_1:
1051 case Builtin::BI__sync_fetch_and_or_2:
1052 case Builtin::BI__sync_fetch_and_or_4:
1053 case Builtin::BI__sync_fetch_and_or_8:
1054 case Builtin::BI__sync_fetch_and_or_16:
1055 BuiltinIndex = 2;
1056 break;
1057
1058 case Builtin::BI__sync_fetch_and_and:
1059 case Builtin::BI__sync_fetch_and_and_1:
1060 case Builtin::BI__sync_fetch_and_and_2:
1061 case Builtin::BI__sync_fetch_and_and_4:
1062 case Builtin::BI__sync_fetch_and_and_8:
1063 case Builtin::BI__sync_fetch_and_and_16:
1064 BuiltinIndex = 3;
1065 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001066
Douglas Gregora9766412011-11-28 16:30:08 +00001067 case Builtin::BI__sync_fetch_and_xor:
1068 case Builtin::BI__sync_fetch_and_xor_1:
1069 case Builtin::BI__sync_fetch_and_xor_2:
1070 case Builtin::BI__sync_fetch_and_xor_4:
1071 case Builtin::BI__sync_fetch_and_xor_8:
1072 case Builtin::BI__sync_fetch_and_xor_16:
1073 BuiltinIndex = 4;
1074 break;
1075
1076 case Builtin::BI__sync_add_and_fetch:
1077 case Builtin::BI__sync_add_and_fetch_1:
1078 case Builtin::BI__sync_add_and_fetch_2:
1079 case Builtin::BI__sync_add_and_fetch_4:
1080 case Builtin::BI__sync_add_and_fetch_8:
1081 case Builtin::BI__sync_add_and_fetch_16:
1082 BuiltinIndex = 5;
1083 break;
1084
1085 case Builtin::BI__sync_sub_and_fetch:
1086 case Builtin::BI__sync_sub_and_fetch_1:
1087 case Builtin::BI__sync_sub_and_fetch_2:
1088 case Builtin::BI__sync_sub_and_fetch_4:
1089 case Builtin::BI__sync_sub_and_fetch_8:
1090 case Builtin::BI__sync_sub_and_fetch_16:
1091 BuiltinIndex = 6;
1092 break;
1093
1094 case Builtin::BI__sync_and_and_fetch:
1095 case Builtin::BI__sync_and_and_fetch_1:
1096 case Builtin::BI__sync_and_and_fetch_2:
1097 case Builtin::BI__sync_and_and_fetch_4:
1098 case Builtin::BI__sync_and_and_fetch_8:
1099 case Builtin::BI__sync_and_and_fetch_16:
1100 BuiltinIndex = 7;
1101 break;
1102
1103 case Builtin::BI__sync_or_and_fetch:
1104 case Builtin::BI__sync_or_and_fetch_1:
1105 case Builtin::BI__sync_or_and_fetch_2:
1106 case Builtin::BI__sync_or_and_fetch_4:
1107 case Builtin::BI__sync_or_and_fetch_8:
1108 case Builtin::BI__sync_or_and_fetch_16:
1109 BuiltinIndex = 8;
1110 break;
1111
1112 case Builtin::BI__sync_xor_and_fetch:
1113 case Builtin::BI__sync_xor_and_fetch_1:
1114 case Builtin::BI__sync_xor_and_fetch_2:
1115 case Builtin::BI__sync_xor_and_fetch_4:
1116 case Builtin::BI__sync_xor_and_fetch_8:
1117 case Builtin::BI__sync_xor_and_fetch_16:
1118 BuiltinIndex = 9;
1119 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001120
Chris Lattner5caa3702009-05-08 06:58:22 +00001121 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001122 case Builtin::BI__sync_val_compare_and_swap_1:
1123 case Builtin::BI__sync_val_compare_and_swap_2:
1124 case Builtin::BI__sync_val_compare_and_swap_4:
1125 case Builtin::BI__sync_val_compare_and_swap_8:
1126 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001127 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001128 NumFixed = 2;
1129 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001130
Chris Lattner5caa3702009-05-08 06:58:22 +00001131 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001132 case Builtin::BI__sync_bool_compare_and_swap_1:
1133 case Builtin::BI__sync_bool_compare_and_swap_2:
1134 case Builtin::BI__sync_bool_compare_and_swap_4:
1135 case Builtin::BI__sync_bool_compare_and_swap_8:
1136 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001137 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001138 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001139 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001140 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001141
1142 case Builtin::BI__sync_lock_test_and_set:
1143 case Builtin::BI__sync_lock_test_and_set_1:
1144 case Builtin::BI__sync_lock_test_and_set_2:
1145 case Builtin::BI__sync_lock_test_and_set_4:
1146 case Builtin::BI__sync_lock_test_and_set_8:
1147 case Builtin::BI__sync_lock_test_and_set_16:
1148 BuiltinIndex = 12;
1149 break;
1150
Chris Lattner5caa3702009-05-08 06:58:22 +00001151 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001152 case Builtin::BI__sync_lock_release_1:
1153 case Builtin::BI__sync_lock_release_2:
1154 case Builtin::BI__sync_lock_release_4:
1155 case Builtin::BI__sync_lock_release_8:
1156 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001157 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001158 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001159 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001160 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001161
1162 case Builtin::BI__sync_swap:
1163 case Builtin::BI__sync_swap_1:
1164 case Builtin::BI__sync_swap_2:
1165 case Builtin::BI__sync_swap_4:
1166 case Builtin::BI__sync_swap_8:
1167 case Builtin::BI__sync_swap_16:
1168 BuiltinIndex = 14;
1169 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001170 }
Mike Stump1eb44332009-09-09 15:08:12 +00001171
Chris Lattner5caa3702009-05-08 06:58:22 +00001172 // Now that we know how many fixed arguments we expect, first check that we
1173 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001174 if (TheCall->getNumArgs() < 1+NumFixed) {
1175 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1176 << 0 << 1+NumFixed << TheCall->getNumArgs()
1177 << TheCall->getCallee()->getSourceRange();
1178 return ExprError();
1179 }
Mike Stump1eb44332009-09-09 15:08:12 +00001180
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001181 // Get the decl for the concrete builtin from this, we can tell what the
1182 // concrete integer type we should convert to is.
1183 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1184 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
1185 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +00001186 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001187 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
1188 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +00001189
John McCallf871d0c2010-08-07 06:22:56 +00001190 // The first argument --- the pointer --- has a fixed type; we
1191 // deduce the types of the rest of the arguments accordingly. Walk
1192 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001193 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001194 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001195
Chris Lattner5caa3702009-05-08 06:58:22 +00001196 // GCC does an implicit conversion to the pointer or integer ValType. This
1197 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001198 // Initialize the argument.
1199 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1200 ValType, /*consume*/ false);
1201 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001202 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001203 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001204
Chris Lattner5caa3702009-05-08 06:58:22 +00001205 // Okay, we have something that *can* be converted to the right type. Check
1206 // to see if there is a potentially weird extension going on here. This can
1207 // happen when you do an atomic operation on something like an char* and
1208 // pass in 42. The 42 gets converted to char. This is even more strange
1209 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001210 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001211 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001212 }
Mike Stump1eb44332009-09-09 15:08:12 +00001213
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001214 ASTContext& Context = this->getASTContext();
1215
1216 // Create a new DeclRefExpr to refer to the new decl.
1217 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1218 Context,
1219 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001220 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001221 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001222 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001223 DRE->getLocation(),
1224 NewBuiltinDecl->getType(),
1225 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Chris Lattner5caa3702009-05-08 06:58:22 +00001227 // Set the callee in the CallExpr.
1228 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001229 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley429bb272011-04-08 18:41:53 +00001230 if (PromotedCall.isInvalid())
1231 return ExprError();
1232 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001233
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001234 // Change the result type of the call to match the original value type. This
1235 // is arbitrary, but the codegen for these builtins ins design to handle it
1236 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001237 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001238
1239 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +00001240}
1241
Chris Lattner69039812009-02-18 06:01:06 +00001242/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001243/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001244/// Note: It might also make sense to do the UTF-16 conversion here (would
1245/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001246bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001247 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001248 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1249
Douglas Gregor5cee1192011-07-27 05:40:30 +00001250 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001251 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1252 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001253 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001254 }
Mike Stump1eb44332009-09-09 15:08:12 +00001255
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001256 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001257 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001258 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001259 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001260 const UTF8 *FromPtr = (UTF8 *)String.data();
1261 UTF16 *ToPtr = &ToBuf[0];
1262
1263 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1264 &ToPtr, ToPtr + NumBytes,
1265 strictConversion);
1266 // Check for conversion failure.
1267 if (Result != conversionOK)
1268 Diag(Arg->getLocStart(),
1269 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1270 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001271 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001272}
1273
Chris Lattnerc27c6652007-12-20 00:05:45 +00001274/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1275/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001276bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1277 Expr *Fn = TheCall->getCallee();
1278 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001279 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001280 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001281 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1282 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001283 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001284 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001285 return true;
1286 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001287
1288 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001289 return Diag(TheCall->getLocEnd(),
1290 diag::err_typecheck_call_too_few_args_at_least)
1291 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001292 }
1293
John McCall5f8d6042011-08-27 01:09:30 +00001294 // Type-check the first argument normally.
1295 if (checkBuiltinArgument(*this, TheCall, 0))
1296 return true;
1297
Chris Lattnerc27c6652007-12-20 00:05:45 +00001298 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001299 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001300 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001301 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001302 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001303 else if (FunctionDecl *FD = getCurFunctionDecl())
1304 isVariadic = FD->isVariadic();
1305 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001306 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001307
Chris Lattnerc27c6652007-12-20 00:05:45 +00001308 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001309 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1310 return true;
1311 }
Mike Stump1eb44332009-09-09 15:08:12 +00001312
Chris Lattner30ce3442007-12-19 23:59:04 +00001313 // Verify that the second argument to the builtin is the last argument of the
1314 // current function or method.
1315 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001316 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001317
Anders Carlsson88cf2262008-02-11 04:20:54 +00001318 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1319 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001320 // FIXME: This isn't correct for methods (results in bogus warning).
1321 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001322 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001323 if (CurBlock)
1324 LastArg = *(CurBlock->TheDecl->param_end()-1);
1325 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001326 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001327 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001328 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001329 SecondArgIsLastNamedArgument = PV == LastArg;
1330 }
1331 }
Mike Stump1eb44332009-09-09 15:08:12 +00001332
Chris Lattner30ce3442007-12-19 23:59:04 +00001333 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001334 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001335 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1336 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001337}
Chris Lattner30ce3442007-12-19 23:59:04 +00001338
Chris Lattner1b9a0792007-12-20 00:26:33 +00001339/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1340/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001341bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1342 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001343 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001344 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001345 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001346 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001347 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001348 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001349 << SourceRange(TheCall->getArg(2)->getLocStart(),
1350 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001351
John Wiegley429bb272011-04-08 18:41:53 +00001352 ExprResult OrigArg0 = TheCall->getArg(0);
1353 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001354
Chris Lattner1b9a0792007-12-20 00:26:33 +00001355 // Do standard promotions between the two arguments, returning their common
1356 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001357 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001358 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1359 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001360
1361 // Make sure any conversions are pushed back into the call; this is
1362 // type safe since unordered compare builtins are declared as "_Bool
1363 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001364 TheCall->setArg(0, OrigArg0.get());
1365 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001366
John Wiegley429bb272011-04-08 18:41:53 +00001367 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001368 return false;
1369
Chris Lattner1b9a0792007-12-20 00:26:33 +00001370 // If the common type isn't a real floating type, then the arguments were
1371 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001372 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001373 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001374 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001375 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1376 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001377
Chris Lattner1b9a0792007-12-20 00:26:33 +00001378 return false;
1379}
1380
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001381/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1382/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001383/// to check everything. We expect the last argument to be a floating point
1384/// value.
1385bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1386 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001387 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001388 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001389 if (TheCall->getNumArgs() > NumArgs)
1390 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001391 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001392 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001393 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001394 (*(TheCall->arg_end()-1))->getLocEnd());
1395
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001396 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001397
Eli Friedman9ac6f622009-08-31 20:06:00 +00001398 if (OrigArg->isTypeDependent())
1399 return false;
1400
Chris Lattner81368fb2010-05-06 05:50:07 +00001401 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001402 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001403 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001404 diag::err_typecheck_call_invalid_unary_fp)
1405 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001406
Chris Lattner81368fb2010-05-06 05:50:07 +00001407 // If this is an implicit conversion from float -> double, remove it.
1408 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1409 Expr *CastArg = Cast->getSubExpr();
1410 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1411 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1412 "promotion from float to double is the only expected cast here");
1413 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001414 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001415 }
1416 }
1417
Eli Friedman9ac6f622009-08-31 20:06:00 +00001418 return false;
1419}
1420
Eli Friedmand38617c2008-05-14 19:38:39 +00001421/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1422// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001423ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001424 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001425 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001426 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001427 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001428 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001429
Nate Begeman37b6a572010-06-08 00:16:34 +00001430 // Determine which of the following types of shufflevector we're checking:
1431 // 1) unary, vector mask: (lhs, mask)
1432 // 2) binary, vector mask: (lhs, rhs, mask)
1433 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1434 QualType resType = TheCall->getArg(0)->getType();
1435 unsigned numElements = 0;
1436
Douglas Gregorcde01732009-05-19 22:10:17 +00001437 if (!TheCall->getArg(0)->isTypeDependent() &&
1438 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001439 QualType LHSType = TheCall->getArg(0)->getType();
1440 QualType RHSType = TheCall->getArg(1)->getType();
1441
1442 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001443 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001444 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001445 TheCall->getArg(1)->getLocEnd());
1446 return ExprError();
1447 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001448
1449 numElements = LHSType->getAs<VectorType>()->getNumElements();
1450 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001451
Nate Begeman37b6a572010-06-08 00:16:34 +00001452 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1453 // with mask. If so, verify that RHS is an integer vector type with the
1454 // same number of elts as lhs.
1455 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001456 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001457 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1458 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1459 << SourceRange(TheCall->getArg(1)->getLocStart(),
1460 TheCall->getArg(1)->getLocEnd());
1461 numResElements = numElements;
1462 }
1463 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001464 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001465 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001466 TheCall->getArg(1)->getLocEnd());
1467 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001468 } else if (numElements != numResElements) {
1469 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001470 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001471 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001472 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001473 }
1474
1475 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001476 if (TheCall->getArg(i)->isTypeDependent() ||
1477 TheCall->getArg(i)->isValueDependent())
1478 continue;
1479
Nate Begeman37b6a572010-06-08 00:16:34 +00001480 llvm::APSInt Result(32);
1481 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1482 return ExprError(Diag(TheCall->getLocStart(),
1483 diag::err_shufflevector_nonconstant_argument)
1484 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001485
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001486 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001487 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001488 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001489 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001490 }
1491
Chris Lattner5f9e2722011-07-23 10:55:15 +00001492 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001493
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001494 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001495 exprs.push_back(TheCall->getArg(i));
1496 TheCall->setArg(i, 0);
1497 }
1498
Nate Begemana88dc302009-08-12 02:10:25 +00001499 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +00001500 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001501 TheCall->getCallee()->getLocStart(),
1502 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001503}
Chris Lattner30ce3442007-12-19 23:59:04 +00001504
Daniel Dunbar4493f792008-07-21 22:59:13 +00001505/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1506// This is declared to take (const void*, ...) and can take two
1507// optional constant int args.
1508bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001509 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001510
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001511 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001512 return Diag(TheCall->getLocEnd(),
1513 diag::err_typecheck_call_too_many_args_at_most)
1514 << 0 /*function call*/ << 3 << NumArgs
1515 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001516
1517 // Argument 0 is checked for us and the remaining arguments must be
1518 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001519 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001520 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001521
1522 // We can't check the value of a dependent argument.
1523 if (Arg->isTypeDependent() || Arg->isValueDependent())
1524 continue;
1525
Eli Friedman9aef7262009-12-04 00:30:06 +00001526 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001527 if (SemaBuiltinConstantArg(TheCall, i, Result))
1528 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001529
Daniel Dunbar4493f792008-07-21 22:59:13 +00001530 // FIXME: gcc issues a warning and rewrites these to 0. These
1531 // seems especially odd for the third argument since the default
1532 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001533 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001534 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001535 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001536 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001537 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001538 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001539 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001540 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001541 }
1542 }
1543
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001544 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001545}
1546
Eric Christopher691ebc32010-04-17 02:26:23 +00001547/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1548/// TheCall is a constant expression.
1549bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1550 llvm::APSInt &Result) {
1551 Expr *Arg = TheCall->getArg(ArgNum);
1552 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1553 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1554
1555 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1556
1557 if (!Arg->isIntegerConstantExpr(Result, Context))
1558 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001559 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001560
Chris Lattner21fb98e2009-09-23 06:06:36 +00001561 return false;
1562}
1563
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001564/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1565/// int type). This simply type checks that type is one of the defined
1566/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001567// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001568bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001569 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001570
1571 // We can't check the value of a dependent argument.
1572 if (TheCall->getArg(1)->isTypeDependent() ||
1573 TheCall->getArg(1)->isValueDependent())
1574 return false;
1575
Eric Christopher691ebc32010-04-17 02:26:23 +00001576 // Check constant-ness first.
1577 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1578 return true;
1579
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001580 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001581 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001582 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1583 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001584 }
1585
1586 return false;
1587}
1588
Eli Friedman586d6a82009-05-03 06:04:26 +00001589/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001590/// This checks that val is a constant 1.
1591bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1592 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001593 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001594
Eric Christopher691ebc32010-04-17 02:26:23 +00001595 // TODO: This is less than ideal. Overload this to take a value.
1596 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1597 return true;
1598
1599 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001600 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1601 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1602
1603 return false;
1604}
1605
Richard Smith831421f2012-06-25 20:30:08 +00001606// Determine if an expression is a string literal or constant string.
1607// If this function returns false on the arguments to a function expecting a
1608// format string, we will usually need to emit a warning.
1609// True string literals are then checked by CheckFormatString.
1610Sema::StringLiteralCheckType
1611Sema::checkFormatStringExpr(const Expr *E, Expr **Args,
1612 unsigned NumArgs, bool HasVAListArg,
1613 unsigned format_idx, unsigned firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001614 FormatStringType Type, VariadicCallType CallType,
1615 bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001616 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001617 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001618 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001619
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001620 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001621
David Blaikiea73cdcb2012-02-10 21:07:25 +00001622 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1623 // Technically -Wformat-nonliteral does not warn about this case.
1624 // The behavior of printf and friends in this case is implementation
1625 // dependent. Ideally if the format string cannot be null then
1626 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith831421f2012-06-25 20:30:08 +00001627 return SLCT_CheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001628
Ted Kremenekd30ef872009-01-12 23:09:09 +00001629 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001630 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001631 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001632 // The expression is a literal if both sub-expressions were, and it was
1633 // completely checked only if both sub-expressions were checked.
1634 const AbstractConditionalOperator *C =
1635 cast<AbstractConditionalOperator>(E);
1636 StringLiteralCheckType Left =
1637 checkFormatStringExpr(C->getTrueExpr(), Args, NumArgs,
1638 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001639 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001640 if (Left == SLCT_NotALiteral)
1641 return SLCT_NotALiteral;
1642 StringLiteralCheckType Right =
1643 checkFormatStringExpr(C->getFalseExpr(), Args, NumArgs,
1644 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001645 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001646 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001647 }
1648
1649 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001650 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1651 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001652 }
1653
John McCall56ca35d2011-02-17 10:25:35 +00001654 case Stmt::OpaqueValueExprClass:
1655 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1656 E = src;
1657 goto tryAgain;
1658 }
Richard Smith831421f2012-06-25 20:30:08 +00001659 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00001660
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001661 case Stmt::PredefinedExprClass:
1662 // While __func__, etc., are technically not string literals, they
1663 // cannot contain format specifiers and thus are not a security
1664 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00001665 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001666
Ted Kremenek082d9362009-03-20 21:35:28 +00001667 case Stmt::DeclRefExprClass: {
1668 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001669
Ted Kremenek082d9362009-03-20 21:35:28 +00001670 // As an exception, do not flag errors for variables binding to
1671 // const string literals.
1672 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1673 bool isConstant = false;
1674 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001675
Ted Kremenek082d9362009-03-20 21:35:28 +00001676 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1677 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001678 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001679 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001680 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001681 } else if (T->isObjCObjectPointerType()) {
1682 // In ObjC, there is usually no "const ObjectPointer" type,
1683 // so don't check if the pointee type is constant.
1684 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001685 }
Mike Stump1eb44332009-09-09 15:08:12 +00001686
Ted Kremenek082d9362009-03-20 21:35:28 +00001687 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001688 if (const Expr *Init = VD->getAnyInitializer()) {
1689 // Look through initializers like const char c[] = { "foo" }
1690 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
1691 if (InitList->isStringLiteralInit())
1692 Init = InitList->getInit(0)->IgnoreParenImpCasts();
1693 }
Richard Smith831421f2012-06-25 20:30:08 +00001694 return checkFormatStringExpr(Init, Args, NumArgs,
1695 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001696 firstDataArg, Type, CallType,
Richard Smith831421f2012-06-25 20:30:08 +00001697 /*inFunctionCall*/false);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001698 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001699 }
Mike Stump1eb44332009-09-09 15:08:12 +00001700
Anders Carlssond966a552009-06-28 19:55:58 +00001701 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1702 // special check to see if the format string is a function parameter
1703 // of the function calling the printf function. If the function
1704 // has an attribute indicating it is a printf-like function, then we
1705 // should suppress warnings concerning non-literals being used in a call
1706 // to a vprintf function. For example:
1707 //
1708 // void
1709 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1710 // va_list ap;
1711 // va_start(ap, fmt);
1712 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1713 // ...
1714 //
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001715 if (HasVAListArg) {
1716 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1717 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1718 int PVIndex = PV->getFunctionScopeIndex() + 1;
1719 for (specific_attr_iterator<FormatAttr>
1720 i = ND->specific_attr_begin<FormatAttr>(),
1721 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1722 FormatAttr *PVFormat = *i;
1723 // adjust for implicit parameter
1724 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1725 if (MD->isInstance())
1726 ++PVIndex;
1727 // We also check if the formats are compatible.
1728 // We can't pass a 'scanf' string to a 'printf' function.
1729 if (PVIndex == PVFormat->getFormatIdx() &&
1730 Type == GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00001731 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001732 }
1733 }
1734 }
1735 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001736 }
Mike Stump1eb44332009-09-09 15:08:12 +00001737
Richard Smith831421f2012-06-25 20:30:08 +00001738 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00001739 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001740
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001741 case Stmt::CallExprClass:
1742 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001743 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001744 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1745 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1746 unsigned ArgIndex = FA->getFormatIdx();
1747 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1748 if (MD->isInstance())
1749 --ArgIndex;
1750 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001751
Richard Smith831421f2012-06-25 20:30:08 +00001752 return checkFormatStringExpr(Arg, Args, NumArgs,
1753 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001754 Type, CallType, inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001755 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1756 unsigned BuiltinID = FD->getBuiltinID();
1757 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
1758 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
1759 const Expr *Arg = CE->getArg(0);
Richard Smith831421f2012-06-25 20:30:08 +00001760 return checkFormatStringExpr(Arg, Args, NumArgs,
1761 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001762 firstDataArg, Type, CallType,
1763 inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001764 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00001765 }
1766 }
Mike Stump1eb44332009-09-09 15:08:12 +00001767
Richard Smith831421f2012-06-25 20:30:08 +00001768 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00001769 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001770 case Stmt::ObjCStringLiteralClass:
1771 case Stmt::StringLiteralClass: {
1772 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001773
Ted Kremenek082d9362009-03-20 21:35:28 +00001774 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001775 StrE = ObjCFExpr->getString();
1776 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001777 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Ted Kremenekd30ef872009-01-12 23:09:09 +00001779 if (StrE) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001780 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001781 firstDataArg, Type, inFunctionCall, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001782 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001783 }
Mike Stump1eb44332009-09-09 15:08:12 +00001784
Richard Smith831421f2012-06-25 20:30:08 +00001785 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001786 }
Mike Stump1eb44332009-09-09 15:08:12 +00001787
Ted Kremenek082d9362009-03-20 21:35:28 +00001788 default:
Richard Smith831421f2012-06-25 20:30:08 +00001789 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001790 }
1791}
1792
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001793void
Mike Stump1eb44332009-09-09 15:08:12 +00001794Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001795 const Expr * const *ExprArgs,
1796 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001797 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1798 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001799 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001800 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001801 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001802 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001803 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001804 }
1805}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001806
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001807Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1808 return llvm::StringSwitch<FormatStringType>(Format->getType())
1809 .Case("scanf", FST_Scanf)
1810 .Cases("printf", "printf0", FST_Printf)
1811 .Cases("NSString", "CFString", FST_NSString)
1812 .Case("strftime", FST_Strftime)
1813 .Case("strfmon", FST_Strfmon)
1814 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1815 .Default(FST_Unknown);
1816}
1817
Jordan Roseddcfbc92012-07-19 18:10:23 +00001818/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00001819/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00001820/// Returns true if a format string has been fully checked.
Richard Smith831421f2012-06-25 20:30:08 +00001821bool Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001822 unsigned NumArgs, bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001823 VariadicCallType CallType,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001824 SourceLocation Loc, SourceRange Range) {
Richard Smith831421f2012-06-25 20:30:08 +00001825 FormatStringInfo FSI;
1826 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
1827 return CheckFormatArguments(Args, NumArgs, FSI.HasVAListArg, FSI.FormatIdx,
1828 FSI.FirstDataArg, GetFormatStringType(Format),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001829 CallType, Loc, Range);
Richard Smith831421f2012-06-25 20:30:08 +00001830 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001831}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001832
Richard Smith831421f2012-06-25 20:30:08 +00001833bool Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001834 bool HasVAListArg, unsigned format_idx,
1835 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001836 VariadicCallType CallType,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001837 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001838 // CHECK: printf/scanf-like function is called with no format string.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001839 if (format_idx >= NumArgs) {
1840 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00001841 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00001842 }
Mike Stump1eb44332009-09-09 15:08:12 +00001843
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001844 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001845
Chris Lattner59907c42007-08-10 20:18:51 +00001846 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001847 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001848 // Dynamically generated format strings are difficult to
1849 // automatically vet at compile time. Requiring that format strings
1850 // are string literals: (1) permits the checking of format strings by
1851 // the compiler and thereby (2) can practically remove the source of
1852 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001853
Mike Stump1eb44332009-09-09 15:08:12 +00001854 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001855 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001856 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001857 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00001858 StringLiteralCheckType CT =
1859 checkFormatStringExpr(OrigFormatExpr, Args, NumArgs, HasVAListArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001860 format_idx, firstDataArg, Type, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001861 if (CT != SLCT_NotALiteral)
1862 // Literal format string found, check done!
1863 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001864
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001865 // Strftime is particular as it always uses a single 'time' argument,
1866 // so it is safe to pass a non-literal string.
1867 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00001868 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001869
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001870 // Do not emit diag when the string param is a macro expansion and the
1871 // format is either NSString or CFString. This is a hack to prevent
1872 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1873 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00001874 if (Type == FST_NSString &&
1875 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00001876 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001877
Chris Lattner655f1412009-04-29 04:59:47 +00001878 // If there are no arguments specified, warn with -Wformat-security, otherwise
1879 // warn only with -Wformat-nonliteral.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001880 if (NumArgs == format_idx+1)
1881 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001882 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001883 << OrigFormatExpr->getSourceRange();
1884 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001885 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001886 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001887 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00001888 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001889}
Ted Kremenek71895b92007-08-14 17:39:48 +00001890
Ted Kremeneke0e53132010-01-28 23:39:18 +00001891namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001892class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1893protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001894 Sema &S;
1895 const StringLiteral *FExpr;
1896 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001897 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001898 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001899 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001900 const bool HasVAListArg;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001901 const Expr * const *Args;
1902 const unsigned NumArgs;
Ted Kremenek0d277352010-01-29 01:06:55 +00001903 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001904 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001905 bool usesPositionalArgs;
1906 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001907 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00001908 Sema::VariadicCallType CallType;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001909public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001910 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001911 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00001912 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001913 Expr **args, unsigned numArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001914 unsigned formatIdx, bool inFunctionCall,
1915 Sema::VariadicCallType callType)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001916 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00001917 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
1918 Beg(beg), HasVAListArg(hasVAListArg),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001919 Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001920 usesPositionalArgs(false), atFirstArg(true),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001921 inFunctionCall(inFunctionCall), CallType(callType) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001922 CoveredArgs.resize(numDataArgs);
1923 CoveredArgs.reset();
1924 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001925
Ted Kremenek07d161f2010-01-29 01:50:07 +00001926 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001927
Ted Kremenek826a3452010-07-16 02:11:22 +00001928 void HandleIncompleteSpecifier(const char *startSpecifier,
1929 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00001930
1931 void HandleNonStandardLengthModifier(
1932 const analyze_format_string::LengthModifier &LM,
1933 const char *startSpecifier, unsigned specifierLen);
1934
1935 void HandleNonStandardConversionSpecifier(
1936 const analyze_format_string::ConversionSpecifier &CS,
1937 const char *startSpecifier, unsigned specifierLen);
1938
1939 void HandleNonStandardConversionSpecification(
1940 const analyze_format_string::LengthModifier &LM,
1941 const analyze_format_string::ConversionSpecifier &CS,
1942 const char *startSpecifier, unsigned specifierLen);
1943
Hans Wennborgf8562642012-03-09 10:10:54 +00001944 virtual void HandlePosition(const char *startPos, unsigned posLen);
1945
Ted Kremenekefaff192010-02-27 01:41:03 +00001946 virtual void HandleInvalidPosition(const char *startSpecifier,
1947 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001948 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001949
1950 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1951
Ted Kremeneke0e53132010-01-28 23:39:18 +00001952 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001953
Richard Trieu55733de2011-10-28 00:41:25 +00001954 template <typename Range>
1955 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1956 const Expr *ArgumentExpr,
1957 PartialDiagnostic PDiag,
1958 SourceLocation StringLoc,
1959 bool IsStringLocation, Range StringRange,
1960 FixItHint Fixit = FixItHint());
1961
Ted Kremenek826a3452010-07-16 02:11:22 +00001962protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001963 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1964 const char *startSpec,
1965 unsigned specifierLen,
1966 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00001967
1968 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1969 const char *startSpec,
1970 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001971
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001972 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001973 CharSourceRange getSpecifierRange(const char *startSpecifier,
1974 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001975 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001976
Ted Kremenek0d277352010-01-29 01:06:55 +00001977 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001978
1979 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1980 const analyze_format_string::ConversionSpecifier &CS,
1981 const char *startSpecifier, unsigned specifierLen,
1982 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00001983
1984 template <typename Range>
1985 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1986 bool IsStringLocation, Range StringRange,
1987 FixItHint Fixit = FixItHint());
1988
1989 void CheckPositionalAndNonpositionalArgs(
1990 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001991};
1992}
1993
Ted Kremenek826a3452010-07-16 02:11:22 +00001994SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001995 return OrigFormatExpr->getSourceRange();
1996}
1997
Ted Kremenek826a3452010-07-16 02:11:22 +00001998CharSourceRange CheckFormatHandler::
1999getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002000 SourceLocation Start = getLocationOfByte(startSpecifier);
2001 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2002
2003 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002004 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002005
2006 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002007}
2008
Ted Kremenek826a3452010-07-16 02:11:22 +00002009SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002010 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002011}
2012
Ted Kremenek826a3452010-07-16 02:11:22 +00002013void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2014 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002015 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2016 getLocationOfByte(startSpecifier),
2017 /*IsStringLocation*/true,
2018 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002019}
2020
Hans Wennborg76517422012-02-22 10:17:01 +00002021void CheckFormatHandler::HandleNonStandardLengthModifier(
2022 const analyze_format_string::LengthModifier &LM,
2023 const char *startSpecifier, unsigned specifierLen) {
2024 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << LM.toString()
Hans Wennborgf8562642012-03-09 10:10:54 +00002025 << 0,
Hans Wennborg76517422012-02-22 10:17:01 +00002026 getLocationOfByte(LM.getStart()),
2027 /*IsStringLocation*/true,
2028 getSpecifierRange(startSpecifier, specifierLen));
2029}
2030
2031void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2032 const analyze_format_string::ConversionSpecifier &CS,
2033 const char *startSpecifier, unsigned specifierLen) {
2034 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << CS.toString()
Hans Wennborgf8562642012-03-09 10:10:54 +00002035 << 1,
Hans Wennborg76517422012-02-22 10:17:01 +00002036 getLocationOfByte(CS.getStart()),
2037 /*IsStringLocation*/true,
2038 getSpecifierRange(startSpecifier, specifierLen));
2039}
2040
2041void CheckFormatHandler::HandleNonStandardConversionSpecification(
2042 const analyze_format_string::LengthModifier &LM,
2043 const analyze_format_string::ConversionSpecifier &CS,
2044 const char *startSpecifier, unsigned specifierLen) {
2045 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_conversion_spec)
2046 << LM.toString() << CS.toString(),
2047 getLocationOfByte(LM.getStart()),
2048 /*IsStringLocation*/true,
2049 getSpecifierRange(startSpecifier, specifierLen));
2050}
2051
Hans Wennborgf8562642012-03-09 10:10:54 +00002052void CheckFormatHandler::HandlePosition(const char *startPos,
2053 unsigned posLen) {
2054 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2055 getLocationOfByte(startPos),
2056 /*IsStringLocation*/true,
2057 getSpecifierRange(startPos, posLen));
2058}
2059
Ted Kremenekefaff192010-02-27 01:41:03 +00002060void
Ted Kremenek826a3452010-07-16 02:11:22 +00002061CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2062 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002063 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2064 << (unsigned) p,
2065 getLocationOfByte(startPos), /*IsStringLocation*/true,
2066 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002067}
2068
Ted Kremenek826a3452010-07-16 02:11:22 +00002069void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002070 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002071 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2072 getLocationOfByte(startPos),
2073 /*IsStringLocation*/true,
2074 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002075}
2076
Ted Kremenek826a3452010-07-16 02:11:22 +00002077void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002078 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002079 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002080 EmitFormatDiagnostic(
2081 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2082 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2083 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002084 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002085}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002086
Jordan Rose48716662012-07-19 18:10:08 +00002087// Note that this may return NULL if there was an error parsing or building
2088// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002089const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002090 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002091}
2092
2093void CheckFormatHandler::DoneProcessing() {
2094 // Does the number of data arguments exceed the number of
2095 // format conversions in the format string?
2096 if (!HasVAListArg) {
2097 // Find any arguments that weren't covered.
2098 CoveredArgs.flip();
2099 signed notCoveredArg = CoveredArgs.find_first();
2100 if (notCoveredArg >= 0) {
2101 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002102 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2103 SourceLocation Loc = E->getLocStart();
2104 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2105 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2106 Loc, /*IsStringLocation*/false,
2107 getFormatStringRange());
2108 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002109 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002110 }
2111 }
2112}
2113
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002114bool
2115CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2116 SourceLocation Loc,
2117 const char *startSpec,
2118 unsigned specifierLen,
2119 const char *csStart,
2120 unsigned csLen) {
2121
2122 bool keepGoing = true;
2123 if (argIndex < NumDataArgs) {
2124 // Consider the argument coverered, even though the specifier doesn't
2125 // make sense.
2126 CoveredArgs.set(argIndex);
2127 }
2128 else {
2129 // If argIndex exceeds the number of data arguments we
2130 // don't issue a warning because that is just a cascade of warnings (and
2131 // they may have intended '%%' anyway). We don't want to continue processing
2132 // the format string after this point, however, as we will like just get
2133 // gibberish when trying to match arguments.
2134 keepGoing = false;
2135 }
2136
Richard Trieu55733de2011-10-28 00:41:25 +00002137 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2138 << StringRef(csStart, csLen),
2139 Loc, /*IsStringLocation*/true,
2140 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002141
2142 return keepGoing;
2143}
2144
Richard Trieu55733de2011-10-28 00:41:25 +00002145void
2146CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2147 const char *startSpec,
2148 unsigned specifierLen) {
2149 EmitFormatDiagnostic(
2150 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2151 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2152}
2153
Ted Kremenek666a1972010-07-26 19:45:42 +00002154bool
2155CheckFormatHandler::CheckNumArgs(
2156 const analyze_format_string::FormatSpecifier &FS,
2157 const analyze_format_string::ConversionSpecifier &CS,
2158 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2159
2160 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002161 PartialDiagnostic PDiag = FS.usesPositionalArg()
2162 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2163 << (argIndex+1) << NumDataArgs)
2164 : S.PDiag(diag::warn_printf_insufficient_data_args);
2165 EmitFormatDiagnostic(
2166 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2167 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002168 return false;
2169 }
2170 return true;
2171}
2172
Richard Trieu55733de2011-10-28 00:41:25 +00002173template<typename Range>
2174void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2175 SourceLocation Loc,
2176 bool IsStringLocation,
2177 Range StringRange,
2178 FixItHint FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002179 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002180 Loc, IsStringLocation, StringRange, FixIt);
2181}
2182
2183/// \brief If the format string is not within the funcion call, emit a note
2184/// so that the function call and string are in diagnostic messages.
2185///
2186/// \param inFunctionCall if true, the format string is within the function
2187/// call and only one diagnostic message will be produced. Otherwise, an
2188/// extra note will be emitted pointing to location of the format string.
2189///
2190/// \param ArgumentExpr the expression that is passed as the format string
2191/// argument in the function call. Used for getting locations when two
2192/// diagnostics are emitted.
2193///
2194/// \param PDiag the callee should already have provided any strings for the
2195/// diagnostic message. This function only adds locations and fixits
2196/// to diagnostics.
2197///
2198/// \param Loc primary location for diagnostic. If two diagnostics are
2199/// required, one will be at Loc and a new SourceLocation will be created for
2200/// the other one.
2201///
2202/// \param IsStringLocation if true, Loc points to the format string should be
2203/// used for the note. Otherwise, Loc points to the argument list and will
2204/// be used with PDiag.
2205///
2206/// \param StringRange some or all of the string to highlight. This is
2207/// templated so it can accept either a CharSourceRange or a SourceRange.
2208///
2209/// \param Fixit optional fix it hint for the format string.
2210template<typename Range>
2211void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2212 const Expr *ArgumentExpr,
2213 PartialDiagnostic PDiag,
2214 SourceLocation Loc,
2215 bool IsStringLocation,
2216 Range StringRange,
2217 FixItHint FixIt) {
2218 if (InFunctionCall)
2219 S.Diag(Loc, PDiag) << StringRange << FixIt;
2220 else {
2221 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2222 << ArgumentExpr->getSourceRange();
2223 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2224 diag::note_format_string_defined)
2225 << StringRange << FixIt;
2226 }
2227}
2228
Ted Kremenek826a3452010-07-16 02:11:22 +00002229//===--- CHECK: Printf format string checking ------------------------------===//
2230
2231namespace {
2232class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002233 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002234public:
2235 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2236 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002237 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002238 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002239 Expr **Args, unsigned NumArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002240 unsigned formatIdx, bool inFunctionCall,
2241 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002242 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002243 numDataArgs, beg, hasVAListArg, Args, NumArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002244 formatIdx, inFunctionCall, CallType), ObjCContext(isObjC)
2245 {}
2246
Ted Kremenek826a3452010-07-16 02:11:22 +00002247
2248 bool HandleInvalidPrintfConversionSpecifier(
2249 const analyze_printf::PrintfSpecifier &FS,
2250 const char *startSpecifier,
2251 unsigned specifierLen);
2252
2253 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2254 const char *startSpecifier,
2255 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002256 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2257 const char *StartSpecifier,
2258 unsigned SpecifierLen,
2259 const Expr *E);
2260
Ted Kremenek826a3452010-07-16 02:11:22 +00002261 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2262 const char *startSpecifier, unsigned specifierLen);
2263 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2264 const analyze_printf::OptionalAmount &Amt,
2265 unsigned type,
2266 const char *startSpecifier, unsigned specifierLen);
2267 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2268 const analyze_printf::OptionalFlag &flag,
2269 const char *startSpecifier, unsigned specifierLen);
2270 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2271 const analyze_printf::OptionalFlag &ignoredFlag,
2272 const analyze_printf::OptionalFlag &flag,
2273 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002274 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith831421f2012-06-25 20:30:08 +00002275 const Expr *E, const CharSourceRange &CSR);
2276
Ted Kremenek826a3452010-07-16 02:11:22 +00002277};
2278}
2279
2280bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2281 const analyze_printf::PrintfSpecifier &FS,
2282 const char *startSpecifier,
2283 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002284 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002285 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002286
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002287 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2288 getLocationOfByte(CS.getStart()),
2289 startSpecifier, specifierLen,
2290 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002291}
2292
Ted Kremenek826a3452010-07-16 02:11:22 +00002293bool CheckPrintfHandler::HandleAmount(
2294 const analyze_format_string::OptionalAmount &Amt,
2295 unsigned k, const char *startSpecifier,
2296 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002297
2298 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002299 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002300 unsigned argIndex = Amt.getArgIndex();
2301 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002302 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2303 << k,
2304 getLocationOfByte(Amt.getStart()),
2305 /*IsStringLocation*/true,
2306 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002307 // Don't do any more checking. We will just emit
2308 // spurious errors.
2309 return false;
2310 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002311
Ted Kremenek0d277352010-01-29 01:06:55 +00002312 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002313 // Although not in conformance with C99, we also allow the argument to be
2314 // an 'unsigned int' as that is a reasonably safe case. GCC also
2315 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002316 CoveredArgs.set(argIndex);
2317 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002318 if (!Arg)
2319 return false;
2320
Ted Kremenek0d277352010-01-29 01:06:55 +00002321 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002322
Hans Wennborgf3749f42012-08-07 08:11:26 +00002323 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2324 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002325
Hans Wennborgf3749f42012-08-07 08:11:26 +00002326 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002327 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002328 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002329 << T << Arg->getSourceRange(),
2330 getLocationOfByte(Amt.getStart()),
2331 /*IsStringLocation*/true,
2332 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002333 // Don't do any more checking. We will just emit
2334 // spurious errors.
2335 return false;
2336 }
2337 }
2338 }
2339 return true;
2340}
Ted Kremenek0d277352010-01-29 01:06:55 +00002341
Tom Caree4ee9662010-06-17 19:00:27 +00002342void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002343 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002344 const analyze_printf::OptionalAmount &Amt,
2345 unsigned type,
2346 const char *startSpecifier,
2347 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002348 const analyze_printf::PrintfConversionSpecifier &CS =
2349 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002350
Richard Trieu55733de2011-10-28 00:41:25 +00002351 FixItHint fixit =
2352 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2353 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2354 Amt.getConstantLength()))
2355 : FixItHint();
2356
2357 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2358 << type << CS.toString(),
2359 getLocationOfByte(Amt.getStart()),
2360 /*IsStringLocation*/true,
2361 getSpecifierRange(startSpecifier, specifierLen),
2362 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002363}
2364
Ted Kremenek826a3452010-07-16 02:11:22 +00002365void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002366 const analyze_printf::OptionalFlag &flag,
2367 const char *startSpecifier,
2368 unsigned specifierLen) {
2369 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002370 const analyze_printf::PrintfConversionSpecifier &CS =
2371 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002372 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2373 << flag.toString() << CS.toString(),
2374 getLocationOfByte(flag.getPosition()),
2375 /*IsStringLocation*/true,
2376 getSpecifierRange(startSpecifier, specifierLen),
2377 FixItHint::CreateRemoval(
2378 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002379}
2380
2381void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002382 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002383 const analyze_printf::OptionalFlag &ignoredFlag,
2384 const analyze_printf::OptionalFlag &flag,
2385 const char *startSpecifier,
2386 unsigned specifierLen) {
2387 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002388 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2389 << ignoredFlag.toString() << flag.toString(),
2390 getLocationOfByte(ignoredFlag.getPosition()),
2391 /*IsStringLocation*/true,
2392 getSpecifierRange(startSpecifier, specifierLen),
2393 FixItHint::CreateRemoval(
2394 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002395}
2396
Richard Smith831421f2012-06-25 20:30:08 +00002397// Determines if the specified is a C++ class or struct containing
2398// a member with the specified name and kind (e.g. a CXXMethodDecl named
2399// "c_str()").
2400template<typename MemberKind>
2401static llvm::SmallPtrSet<MemberKind*, 1>
2402CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2403 const RecordType *RT = Ty->getAs<RecordType>();
2404 llvm::SmallPtrSet<MemberKind*, 1> Results;
2405
2406 if (!RT)
2407 return Results;
2408 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2409 if (!RD)
2410 return Results;
2411
2412 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2413 Sema::LookupMemberName);
2414
2415 // We just need to include all members of the right kind turned up by the
2416 // filter, at this point.
2417 if (S.LookupQualifiedName(R, RT->getDecl()))
2418 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2419 NamedDecl *decl = (*I)->getUnderlyingDecl();
2420 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2421 Results.insert(FK);
2422 }
2423 return Results;
2424}
2425
2426// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002427// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002428// Returns true when a c_str() conversion method is found.
2429bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgf3749f42012-08-07 08:11:26 +00002430 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith831421f2012-06-25 20:30:08 +00002431 const CharSourceRange &CSR) {
2432 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2433
2434 MethodSet Results =
2435 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2436
2437 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2438 MI != ME; ++MI) {
2439 const CXXMethodDecl *Method = *MI;
2440 if (Method->getNumParams() == 0 &&
Hans Wennborgf3749f42012-08-07 08:11:26 +00002441 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith831421f2012-06-25 20:30:08 +00002442 // FIXME: Suggest parens if the expression needs them.
2443 SourceLocation EndLoc =
2444 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2445 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2446 << "c_str()"
2447 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2448 return true;
2449 }
2450 }
2451
2452 return false;
2453}
2454
Ted Kremeneke0e53132010-01-28 23:39:18 +00002455bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002456CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002457 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002458 const char *startSpecifier,
2459 unsigned specifierLen) {
2460
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002461 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002462 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002463 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002464
Ted Kremenekbaa40062010-07-19 22:01:06 +00002465 if (FS.consumesDataArgument()) {
2466 if (atFirstArg) {
2467 atFirstArg = false;
2468 usesPositionalArgs = FS.usesPositionalArg();
2469 }
2470 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002471 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2472 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002473 return false;
2474 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002475 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002476
Ted Kremenekefaff192010-02-27 01:41:03 +00002477 // First check if the field width, precision, and conversion specifier
2478 // have matching data arguments.
2479 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2480 startSpecifier, specifierLen)) {
2481 return false;
2482 }
2483
2484 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2485 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002486 return false;
2487 }
2488
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002489 if (!CS.consumesDataArgument()) {
2490 // FIXME: Technically specifying a precision or field width here
2491 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002492 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002493 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002494
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002495 // Consume the argument.
2496 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002497 if (argIndex < NumDataArgs) {
2498 // The check to see if the argIndex is valid will come later.
2499 // We set the bit here because we may exit early from this
2500 // function if we encounter some other error.
2501 CoveredArgs.set(argIndex);
2502 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002503
2504 // Check for using an Objective-C specific conversion specifier
2505 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002506 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002507 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2508 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002509 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002510
Tom Caree4ee9662010-06-17 19:00:27 +00002511 // Check for invalid use of field width
2512 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002513 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002514 startSpecifier, specifierLen);
2515 }
2516
2517 // Check for invalid use of precision
2518 if (!FS.hasValidPrecision()) {
2519 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2520 startSpecifier, specifierLen);
2521 }
2522
2523 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002524 if (!FS.hasValidThousandsGroupingPrefix())
2525 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002526 if (!FS.hasValidLeadingZeros())
2527 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2528 if (!FS.hasValidPlusPrefix())
2529 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002530 if (!FS.hasValidSpacePrefix())
2531 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002532 if (!FS.hasValidAlternativeForm())
2533 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2534 if (!FS.hasValidLeftJustified())
2535 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2536
2537 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002538 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2539 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2540 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002541 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2542 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2543 startSpecifier, specifierLen);
2544
2545 // Check the length modifier is valid with the given conversion specifier.
2546 const LengthModifier &LM = FS.getLengthModifier();
2547 if (!FS.hasValidLengthModifier())
Richard Trieu55733de2011-10-28 00:41:25 +00002548 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2549 << LM.toString() << CS.toString(),
2550 getLocationOfByte(LM.getStart()),
2551 /*IsStringLocation*/true,
2552 getSpecifierRange(startSpecifier, specifierLen),
2553 FixItHint::CreateRemoval(
2554 getSpecifierRange(LM.getStart(),
2555 LM.getLength())));
Hans Wennborg76517422012-02-22 10:17:01 +00002556 if (!FS.hasStandardLengthModifier())
2557 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
David Blaikie4e4d0842012-03-11 07:00:24 +00002558 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
Hans Wennborg76517422012-02-22 10:17:01 +00002559 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2560 if (!FS.hasStandardLengthConversionCombination())
2561 HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
2562 specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002563
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002564 // The remaining checks depend on the data arguments.
2565 if (HasVAListArg)
2566 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002567
Ted Kremenek666a1972010-07-26 19:45:42 +00002568 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002569 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002570
Jordan Rose48716662012-07-19 18:10:08 +00002571 const Expr *Arg = getDataArg(argIndex);
2572 if (!Arg)
2573 return true;
2574
2575 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00002576}
2577
2578bool
2579CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2580 const char *StartSpecifier,
2581 unsigned SpecifierLen,
2582 const Expr *E) {
2583 using namespace analyze_format_string;
2584 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002585 // Now type check the data expression that matches the
2586 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00002587 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
2588 ObjCContext);
2589 if (AT.isValid() && !AT.matchesType(S.Context, E->getType())) {
Jordan Roseee0259d2012-06-04 22:48:57 +00002590 // Look through argument promotions for our error message's reported type.
2591 // This includes the integral and floating promotions, but excludes array
2592 // and function pointer decay; seeing that an argument intended to be a
2593 // string has type 'char [6]' is probably more confusing than 'char *'.
Richard Smith831421f2012-06-25 20:30:08 +00002594 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Jordan Roseee0259d2012-06-04 22:48:57 +00002595 if (ICE->getCastKind() == CK_IntegralCast ||
2596 ICE->getCastKind() == CK_FloatingCast) {
Richard Smith831421f2012-06-25 20:30:08 +00002597 E = ICE->getSubExpr();
Jordan Roseee0259d2012-06-04 22:48:57 +00002598
2599 // Check if we didn't match because of an implicit cast from a 'char'
2600 // or 'short' to an 'int'. This is done because printf is a varargs
2601 // function.
2602 if (ICE->getType() == S.Context.IntTy ||
2603 ICE->getType() == S.Context.UnsignedIntTy) {
2604 // All further checking is done on the subexpression.
Hans Wennborgf3749f42012-08-07 08:11:26 +00002605 if (AT.matchesType(S.Context, E->getType()))
Jordan Roseee0259d2012-06-04 22:48:57 +00002606 return true;
2607 }
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002608 }
Jordan Roseee0259d2012-06-04 22:48:57 +00002609 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002610
2611 // We may be able to offer a FixItHint if it is a supported type.
2612 PrintfSpecifier fixedFS = FS;
Richard Smith831421f2012-06-25 20:30:08 +00002613 bool success = fixedFS.fixType(E->getType(), S.getLangOpts(),
Jordan Rose50687312012-06-04 23:52:23 +00002614 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002615
2616 if (success) {
2617 // Get the fix string from the fixed format specifier
Jordan Roseee0259d2012-06-04 22:48:57 +00002618 SmallString<16> buf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002619 llvm::raw_svector_ostream os(buf);
2620 fixedFS.toString(os);
2621
Richard Trieu55733de2011-10-28 00:41:25 +00002622 EmitFormatDiagnostic(
2623 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002624 << AT.getRepresentativeTypeName(S.Context) << E->getType()
Richard Smith831421f2012-06-25 20:30:08 +00002625 << E->getSourceRange(),
2626 E->getLocStart(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00002627 /*IsStringLocation*/false,
Richard Smith831421f2012-06-25 20:30:08 +00002628 getSpecifierRange(StartSpecifier, SpecifierLen),
Richard Trieu55733de2011-10-28 00:41:25 +00002629 FixItHint::CreateReplacement(
Richard Smith831421f2012-06-25 20:30:08 +00002630 getSpecifierRange(StartSpecifier, SpecifierLen),
Richard Trieu55733de2011-10-28 00:41:25 +00002631 os.str()));
Richard Smith831421f2012-06-25 20:30:08 +00002632 } else {
2633 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
2634 SpecifierLen);
2635 // Since the warning for passing non-POD types to variadic functions
2636 // was deferred until now, we emit a warning for non-POD
2637 // arguments here.
2638 if (S.isValidVarArgType(E->getType()) == Sema::VAK_Invalid) {
Jordan Roseddcfbc92012-07-19 18:10:23 +00002639 unsigned DiagKind;
2640 if (E->getType()->isObjCObjectType())
2641 DiagKind = diag::err_cannot_pass_objc_interface_to_vararg_format;
2642 else
2643 DiagKind = diag::warn_non_pod_vararg_with_format_string;
2644
Richard Smith831421f2012-06-25 20:30:08 +00002645 EmitFormatDiagnostic(
Jordan Roseddcfbc92012-07-19 18:10:23 +00002646 S.PDiag(DiagKind)
Richard Smith831421f2012-06-25 20:30:08 +00002647 << S.getLangOpts().CPlusPlus0x
2648 << E->getType()
Jordan Roseddcfbc92012-07-19 18:10:23 +00002649 << CallType
Hans Wennborgf3749f42012-08-07 08:11:26 +00002650 << AT.getRepresentativeTypeName(S.Context)
Richard Smith831421f2012-06-25 20:30:08 +00002651 << CSR
2652 << E->getSourceRange(),
2653 E->getLocStart(), /*IsStringLocation*/false, CSR);
2654
Hans Wennborgf3749f42012-08-07 08:11:26 +00002655 checkForCStrMembers(AT, E, CSR);
Richard Smith831421f2012-06-25 20:30:08 +00002656 } else
2657 EmitFormatDiagnostic(
2658 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002659 << AT.getRepresentativeTypeName(S.Context) << E->getType()
Richard Smith831421f2012-06-25 20:30:08 +00002660 << CSR
2661 << E->getSourceRange(),
2662 E->getLocStart(), /*IsStringLocation*/false, CSR);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002663 }
2664 }
2665
Ted Kremeneke0e53132010-01-28 23:39:18 +00002666 return true;
2667}
2668
Ted Kremenek826a3452010-07-16 02:11:22 +00002669//===--- CHECK: Scanf format string checking ------------------------------===//
2670
2671namespace {
2672class CheckScanfHandler : public CheckFormatHandler {
2673public:
2674 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2675 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002676 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002677 Expr **Args, unsigned NumArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002678 unsigned formatIdx, bool inFunctionCall,
2679 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002680 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002681 numDataArgs, beg, hasVAListArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002682 Args, NumArgs, formatIdx, inFunctionCall, CallType)
2683 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002684
2685 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2686 const char *startSpecifier,
2687 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002688
2689 bool HandleInvalidScanfConversionSpecifier(
2690 const analyze_scanf::ScanfSpecifier &FS,
2691 const char *startSpecifier,
2692 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002693
2694 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002695};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002696}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002697
Ted Kremenekb7c21012010-07-16 18:28:03 +00002698void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2699 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002700 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2701 getLocationOfByte(end), /*IsStringLocation*/true,
2702 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002703}
2704
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002705bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2706 const analyze_scanf::ScanfSpecifier &FS,
2707 const char *startSpecifier,
2708 unsigned specifierLen) {
2709
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002710 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002711 FS.getConversionSpecifier();
2712
2713 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2714 getLocationOfByte(CS.getStart()),
2715 startSpecifier, specifierLen,
2716 CS.getStart(), CS.getLength());
2717}
2718
Ted Kremenek826a3452010-07-16 02:11:22 +00002719bool CheckScanfHandler::HandleScanfSpecifier(
2720 const analyze_scanf::ScanfSpecifier &FS,
2721 const char *startSpecifier,
2722 unsigned specifierLen) {
2723
2724 using namespace analyze_scanf;
2725 using namespace analyze_format_string;
2726
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002727 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002728
Ted Kremenekbaa40062010-07-19 22:01:06 +00002729 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2730 // be used to decide if we are using positional arguments consistently.
2731 if (FS.consumesDataArgument()) {
2732 if (atFirstArg) {
2733 atFirstArg = false;
2734 usesPositionalArgs = FS.usesPositionalArg();
2735 }
2736 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002737 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2738 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002739 return false;
2740 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002741 }
2742
2743 // Check if the field with is non-zero.
2744 const OptionalAmount &Amt = FS.getFieldWidth();
2745 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2746 if (Amt.getConstantAmount() == 0) {
2747 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2748 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00002749 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2750 getLocationOfByte(Amt.getStart()),
2751 /*IsStringLocation*/true, R,
2752 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00002753 }
2754 }
2755
2756 if (!FS.consumesDataArgument()) {
2757 // FIXME: Technically specifying a precision or field width here
2758 // makes no sense. Worth issuing a warning at some point.
2759 return true;
2760 }
2761
2762 // Consume the argument.
2763 unsigned argIndex = FS.getArgIndex();
2764 if (argIndex < NumDataArgs) {
2765 // The check to see if the argIndex is valid will come later.
2766 // We set the bit here because we may exit early from this
2767 // function if we encounter some other error.
2768 CoveredArgs.set(argIndex);
2769 }
2770
Ted Kremenek1e51c202010-07-20 20:04:47 +00002771 // Check the length modifier is valid with the given conversion specifier.
2772 const LengthModifier &LM = FS.getLengthModifier();
2773 if (!FS.hasValidLengthModifier()) {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002774 const CharSourceRange &R = getSpecifierRange(LM.getStart(), LM.getLength());
2775 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2776 << LM.toString() << CS.toString()
2777 << getSpecifierRange(startSpecifier, specifierLen),
2778 getLocationOfByte(LM.getStart()),
2779 /*IsStringLocation*/true, R,
2780 FixItHint::CreateRemoval(R));
Ted Kremenek1e51c202010-07-20 20:04:47 +00002781 }
2782
Hans Wennborg76517422012-02-22 10:17:01 +00002783 if (!FS.hasStandardLengthModifier())
2784 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
David Blaikie4e4d0842012-03-11 07:00:24 +00002785 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
Hans Wennborg76517422012-02-22 10:17:01 +00002786 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2787 if (!FS.hasStandardLengthConversionCombination())
2788 HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
2789 specifierLen);
2790
Ted Kremenek826a3452010-07-16 02:11:22 +00002791 // The remaining checks depend on the data arguments.
2792 if (HasVAListArg)
2793 return true;
2794
Ted Kremenek666a1972010-07-26 19:45:42 +00002795 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002796 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002797
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002798 // Check that the argument type matches the format specifier.
2799 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002800 if (!Ex)
2801 return true;
2802
Hans Wennborg58e1e542012-08-07 08:59:46 +00002803 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
2804 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002805 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00002806 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00002807 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002808
2809 if (success) {
2810 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002811 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002812 llvm::raw_svector_ostream os(buf);
2813 fixedFS.toString(os);
2814
2815 EmitFormatDiagnostic(
2816 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00002817 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002818 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00002819 Ex->getLocStart(),
2820 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002821 getSpecifierRange(startSpecifier, specifierLen),
2822 FixItHint::CreateReplacement(
2823 getSpecifierRange(startSpecifier, specifierLen),
2824 os.str()));
2825 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002826 EmitFormatDiagnostic(
2827 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00002828 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002829 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00002830 Ex->getLocStart(),
2831 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002832 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002833 }
2834 }
2835
Ted Kremenek826a3452010-07-16 02:11:22 +00002836 return true;
2837}
2838
2839void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002840 const Expr *OrigFormatExpr,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002841 Expr **Args, unsigned NumArgs,
2842 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002843 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002844 bool inFunctionCall, VariadicCallType CallType) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002845
Ted Kremeneke0e53132010-01-28 23:39:18 +00002846 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00002847 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002848 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002849 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002850 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2851 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002852 return;
2853 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002854
Ted Kremeneke0e53132010-01-28 23:39:18 +00002855 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00002856 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002857 const char *Str = StrRef.data();
2858 unsigned StrLen = StrRef.size();
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002859 const unsigned numDataArgs = NumArgs - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00002860
Ted Kremeneke0e53132010-01-28 23:39:18 +00002861 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00002862 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00002863 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002864 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002865 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2866 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002867 return;
2868 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002869
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002870 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002871 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002872 numDataArgs, (Type == FST_NSString),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002873 Str, HasVAListArg, Args, NumArgs, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002874 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00002875
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002876 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
David Blaikie4e4d0842012-03-11 07:00:24 +00002877 getLangOpts()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002878 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002879 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00002880 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002881 Str, HasVAListArg, Args, NumArgs, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002882 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00002883
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002884 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
David Blaikie4e4d0842012-03-11 07:00:24 +00002885 getLangOpts()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002886 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002887 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00002888}
2889
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002890//===--- CHECK: Standard memory functions ---------------------------------===//
2891
Douglas Gregor2a053a32011-05-03 20:05:22 +00002892/// \brief Determine whether the given type is a dynamic class type (e.g.,
2893/// whether it has a vtable).
2894static bool isDynamicClassType(QualType T) {
2895 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2896 if (CXXRecordDecl *Definition = Record->getDefinition())
2897 if (Definition->isDynamicClass())
2898 return true;
2899
2900 return false;
2901}
2902
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002903/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00002904/// otherwise returns NULL.
2905static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00002906 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00002907 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2908 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2909 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002910
Chandler Carruth000d4282011-06-16 09:09:40 +00002911 return 0;
2912}
2913
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002914/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00002915static QualType getSizeOfArgType(const Expr* E) {
2916 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2917 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2918 if (SizeOf->getKind() == clang::UETT_SizeOf)
2919 return SizeOf->getTypeOfArgument();
2920
2921 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00002922}
2923
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002924/// \brief Check for dangerous or invalid arguments to memset().
2925///
Chandler Carruth929f0132011-06-03 06:23:57 +00002926/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002927/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2928/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002929///
2930/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002931void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00002932 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002933 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00002934 assert(BId != 0);
2935
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002936 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00002937 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00002938 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00002939 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002940 return;
2941
Anna Zaks0a151a12012-01-17 00:37:07 +00002942 unsigned LastArg = (BId == Builtin::BImemset ||
2943 BId == Builtin::BIstrndup ? 1 : 2);
2944 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00002945 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00002946
2947 // We have special checking when the length is a sizeof expression.
2948 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2949 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2950 llvm::FoldingSetNodeID SizeOfArgID;
2951
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002952 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2953 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002954 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002955
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002956 QualType DestTy = Dest->getType();
2957 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2958 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002959
Chandler Carruth000d4282011-06-16 09:09:40 +00002960 // Never warn about void type pointers. This can be used to suppress
2961 // false positives.
2962 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002963 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002964
Chandler Carruth000d4282011-06-16 09:09:40 +00002965 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2966 // actually comparing the expressions for equality. Because computing the
2967 // expression IDs can be expensive, we only do this if the diagnostic is
2968 // enabled.
2969 if (SizeOfArg &&
2970 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2971 SizeOfArg->getExprLoc())) {
2972 // We only compute IDs for expressions if the warning is enabled, and
2973 // cache the sizeof arg's ID.
2974 if (SizeOfArgID == llvm::FoldingSetNodeID())
2975 SizeOfArg->Profile(SizeOfArgID, Context, true);
2976 llvm::FoldingSetNodeID DestID;
2977 Dest->Profile(DestID, Context, true);
2978 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00002979 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2980 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00002981 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00002982 StringRef ReadableName = FnName->getName();
2983
Chandler Carruth000d4282011-06-16 09:09:40 +00002984 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00002985 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00002986 ActionIdx = 1; // If its an address-of operator, just remove it.
2987 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2988 ActionIdx = 2; // If the pointee's size is sizeof(char),
2989 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00002990
2991 // If the function is defined as a builtin macro, do not show macro
2992 // expansion.
2993 SourceLocation SL = SizeOfArg->getExprLoc();
2994 SourceRange DSR = Dest->getSourceRange();
2995 SourceRange SSR = SizeOfArg->getSourceRange();
2996 SourceManager &SM = PP.getSourceManager();
2997
2998 if (SM.isMacroArgExpansion(SL)) {
2999 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3000 SL = SM.getSpellingLoc(SL);
3001 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3002 SM.getSpellingLoc(DSR.getEnd()));
3003 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3004 SM.getSpellingLoc(SSR.getEnd()));
3005 }
3006
Anna Zaks90c78322012-05-30 23:14:52 +00003007 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00003008 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00003009 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00003010 << PointeeTy
3011 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00003012 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00003013 << SSR);
3014 DiagRuntimeBehavior(SL, SizeOfArg,
3015 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3016 << ActionIdx
3017 << SSR);
3018
Chandler Carruth000d4282011-06-16 09:09:40 +00003019 break;
3020 }
3021 }
3022
3023 // Also check for cases where the sizeof argument is the exact same
3024 // type as the memory argument, and where it points to a user-defined
3025 // record type.
3026 if (SizeOfArgTy != QualType()) {
3027 if (PointeeTy->isRecordType() &&
3028 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3029 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3030 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3031 << FnName << SizeOfArgTy << ArgIdx
3032 << PointeeTy << Dest->getSourceRange()
3033 << LenExpr->getSourceRange());
3034 break;
3035 }
Nico Webere4a1c642011-06-14 16:14:58 +00003036 }
3037
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003038 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00003039 if (isDynamicClassType(PointeeTy)) {
3040
3041 unsigned OperationType = 0;
3042 // "overwritten" if we're warning about the destination for any call
3043 // but memcmp; otherwise a verb appropriate to the call.
3044 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3045 if (BId == Builtin::BImemcpy)
3046 OperationType = 1;
3047 else if(BId == Builtin::BImemmove)
3048 OperationType = 2;
3049 else if (BId == Builtin::BImemcmp)
3050 OperationType = 3;
3051 }
3052
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003053 DiagRuntimeBehavior(
3054 Dest->getExprLoc(), Dest,
3055 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003056 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003057 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003058 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003059 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003060 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3061 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003062 DiagRuntimeBehavior(
3063 Dest->getExprLoc(), Dest,
3064 PDiag(diag::warn_arc_object_memaccess)
3065 << ArgIdx << FnName << PointeeTy
3066 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003067 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003068 continue;
John McCallf85e1932011-06-15 23:02:42 +00003069
3070 DiagRuntimeBehavior(
3071 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003072 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003073 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3074 break;
3075 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003076 }
3077}
3078
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003079// A little helper routine: ignore addition and subtraction of integer literals.
3080// This intentionally does not ignore all integer constant expressions because
3081// we don't want to remove sizeof().
3082static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3083 Ex = Ex->IgnoreParenCasts();
3084
3085 for (;;) {
3086 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3087 if (!BO || !BO->isAdditiveOp())
3088 break;
3089
3090 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3091 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3092
3093 if (isa<IntegerLiteral>(RHS))
3094 Ex = LHS;
3095 else if (isa<IntegerLiteral>(LHS))
3096 Ex = RHS;
3097 else
3098 break;
3099 }
3100
3101 return Ex;
3102}
3103
Anna Zaks0f38ace2012-08-08 21:42:23 +00003104static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3105 ASTContext &Context) {
3106 // Only handle constant-sized or VLAs, but not flexible members.
3107 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3108 // Only issue the FIXIT for arrays of size > 1.
3109 if (CAT->getSize().getSExtValue() <= 1)
3110 return false;
3111 } else if (!Ty->isVariableArrayType()) {
3112 return false;
3113 }
3114 return true;
3115}
3116
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003117// Warn if the user has made the 'size' argument to strlcpy or strlcat
3118// be the size of the source, instead of the destination.
3119void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3120 IdentifierInfo *FnName) {
3121
3122 // Don't crash if the user has the wrong number of arguments
3123 if (Call->getNumArgs() != 3)
3124 return;
3125
3126 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3127 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3128 const Expr *CompareWithSrc = NULL;
3129
3130 // Look for 'strlcpy(dst, x, sizeof(x))'
3131 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3132 CompareWithSrc = Ex;
3133 else {
3134 // Look for 'strlcpy(dst, x, strlen(x))'
3135 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003136 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003137 && SizeCall->getNumArgs() == 1)
3138 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3139 }
3140 }
3141
3142 if (!CompareWithSrc)
3143 return;
3144
3145 // Determine if the argument to sizeof/strlen is equal to the source
3146 // argument. In principle there's all kinds of things you could do
3147 // here, for instance creating an == expression and evaluating it with
3148 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3149 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3150 if (!SrcArgDRE)
3151 return;
3152
3153 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3154 if (!CompareWithSrcDRE ||
3155 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3156 return;
3157
3158 const Expr *OriginalSizeArg = Call->getArg(2);
3159 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3160 << OriginalSizeArg->getSourceRange() << FnName;
3161
3162 // Output a FIXIT hint if the destination is an array (rather than a
3163 // pointer to an array). This could be enhanced to handle some
3164 // pointers if we know the actual size, like if DstArg is 'array+2'
3165 // we could say 'sizeof(array)-2'.
3166 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00003167 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00003168 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00003169
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003170 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003171 llvm::raw_svector_ostream OS(sizeString);
3172 OS << "sizeof(";
Douglas Gregor8987b232011-09-27 23:30:47 +00003173 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003174 OS << ")";
3175
3176 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3177 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3178 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003179}
3180
Anna Zaksc36bedc2012-02-01 19:08:57 +00003181/// Check if two expressions refer to the same declaration.
3182static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3183 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3184 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3185 return D1->getDecl() == D2->getDecl();
3186 return false;
3187}
3188
3189static const Expr *getStrlenExprArg(const Expr *E) {
3190 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3191 const FunctionDecl *FD = CE->getDirectCallee();
3192 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3193 return 0;
3194 return CE->getArg(0)->IgnoreParenCasts();
3195 }
3196 return 0;
3197}
3198
3199// Warn on anti-patterns as the 'size' argument to strncat.
3200// The correct size argument should look like following:
3201// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3202void Sema::CheckStrncatArguments(const CallExpr *CE,
3203 IdentifierInfo *FnName) {
3204 // Don't crash if the user has the wrong number of arguments.
3205 if (CE->getNumArgs() < 3)
3206 return;
3207 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3208 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3209 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3210
3211 // Identify common expressions, which are wrongly used as the size argument
3212 // to strncat and may lead to buffer overflows.
3213 unsigned PatternType = 0;
3214 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3215 // - sizeof(dst)
3216 if (referToTheSameDecl(SizeOfArg, DstArg))
3217 PatternType = 1;
3218 // - sizeof(src)
3219 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3220 PatternType = 2;
3221 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3222 if (BE->getOpcode() == BO_Sub) {
3223 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3224 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3225 // - sizeof(dst) - strlen(dst)
3226 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3227 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3228 PatternType = 1;
3229 // - sizeof(src) - (anything)
3230 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3231 PatternType = 2;
3232 }
3233 }
3234
3235 if (PatternType == 0)
3236 return;
3237
Anna Zaksafdb0412012-02-03 01:27:37 +00003238 // Generate the diagnostic.
3239 SourceLocation SL = LenArg->getLocStart();
3240 SourceRange SR = LenArg->getSourceRange();
3241 SourceManager &SM = PP.getSourceManager();
3242
3243 // If the function is defined as a builtin macro, do not show macro expansion.
3244 if (SM.isMacroArgExpansion(SL)) {
3245 SL = SM.getSpellingLoc(SL);
3246 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3247 SM.getSpellingLoc(SR.getEnd()));
3248 }
3249
Anna Zaks0f38ace2012-08-08 21:42:23 +00003250 // Check if the destination is an array (rather than a pointer to an array).
3251 QualType DstTy = DstArg->getType();
3252 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3253 Context);
3254 if (!isKnownSizeArray) {
3255 if (PatternType == 1)
3256 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3257 else
3258 Diag(SL, diag::warn_strncat_src_size) << SR;
3259 return;
3260 }
3261
Anna Zaksc36bedc2012-02-01 19:08:57 +00003262 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003263 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003264 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003265 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003266
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003267 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003268 llvm::raw_svector_ostream OS(sizeString);
3269 OS << "sizeof(";
3270 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
3271 OS << ") - ";
3272 OS << "strlen(";
3273 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
3274 OS << ") - 1";
3275
Anna Zaksafdb0412012-02-03 01:27:37 +00003276 Diag(SL, diag::note_strncat_wrong_size)
3277 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003278}
3279
Ted Kremenek06de2762007-08-17 16:46:58 +00003280//===--- CHECK: Return Address of Stack Variable --------------------------===//
3281
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003282static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3283 Decl *ParentDecl);
3284static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3285 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003286
3287/// CheckReturnStackAddr - Check if a return statement returns the address
3288/// of a stack variable.
3289void
3290Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3291 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003292
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003293 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003294 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003295
3296 // Perform checking for returned stack addresses, local blocks,
3297 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003298 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003299 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003300 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003301 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003302 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003303 }
3304
3305 if (stackE == 0)
3306 return; // Nothing suspicious was found.
3307
3308 SourceLocation diagLoc;
3309 SourceRange diagRange;
3310 if (refVars.empty()) {
3311 diagLoc = stackE->getLocStart();
3312 diagRange = stackE->getSourceRange();
3313 } else {
3314 // We followed through a reference variable. 'stackE' contains the
3315 // problematic expression but we will warn at the return statement pointing
3316 // at the reference variable. We will later display the "trail" of
3317 // reference variables using notes.
3318 diagLoc = refVars[0]->getLocStart();
3319 diagRange = refVars[0]->getSourceRange();
3320 }
3321
3322 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3323 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3324 : diag::warn_ret_stack_addr)
3325 << DR->getDecl()->getDeclName() << diagRange;
3326 } else if (isa<BlockExpr>(stackE)) { // local block.
3327 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3328 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3329 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3330 } else { // local temporary.
3331 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3332 : diag::warn_ret_local_temp_addr)
3333 << diagRange;
3334 }
3335
3336 // Display the "trail" of reference variables that we followed until we
3337 // found the problematic expression using notes.
3338 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3339 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3340 // If this var binds to another reference var, show the range of the next
3341 // var, otherwise the var binds to the problematic expression, in which case
3342 // show the range of the expression.
3343 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3344 : stackE->getSourceRange();
3345 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3346 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003347 }
3348}
3349
3350/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3351/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003352/// to a location on the stack, a local block, an address of a label, or a
3353/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003354/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003355/// encounter a subexpression that (1) clearly does not lead to one of the
3356/// above problematic expressions (2) is something we cannot determine leads to
3357/// a problematic expression based on such local checking.
3358///
3359/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3360/// the expression that they point to. Such variables are added to the
3361/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003362///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003363/// EvalAddr processes expressions that are pointers that are used as
3364/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003365/// At the base case of the recursion is a check for the above problematic
3366/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00003367///
3368/// This implementation handles:
3369///
3370/// * pointer-to-pointer casts
3371/// * implicit conversions from array references to pointers
3372/// * taking the address of fields
3373/// * arbitrary interplay between "&" and "*" operators
3374/// * pointer arithmetic from an address of a stack variable
3375/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003376static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3377 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003378 if (E->isTypeDependent())
3379 return NULL;
3380
Ted Kremenek06de2762007-08-17 16:46:58 +00003381 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00003382 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00003383 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003384 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003385 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00003386
Peter Collingbournef111d932011-04-15 00:35:48 +00003387 E = E->IgnoreParens();
3388
Ted Kremenek06de2762007-08-17 16:46:58 +00003389 // Our "symbolic interpreter" is just a dispatch off the currently
3390 // viewed AST node. We then recursively traverse the AST by calling
3391 // EvalAddr and EvalVal appropriately.
3392 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003393 case Stmt::DeclRefExprClass: {
3394 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3395
3396 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3397 // If this is a reference variable, follow through to the expression that
3398 // it points to.
3399 if (V->hasLocalStorage() &&
3400 V->getType()->isReferenceType() && V->hasInit()) {
3401 // Add the reference variable to the "trail".
3402 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003403 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003404 }
3405
3406 return NULL;
3407 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003408
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003409 case Stmt::UnaryOperatorClass: {
3410 // The only unary operator that make sense to handle here
3411 // is AddrOf. All others don't make sense as pointers.
3412 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003413
John McCall2de56d12010-08-25 11:45:40 +00003414 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003415 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003416 else
Ted Kremenek06de2762007-08-17 16:46:58 +00003417 return NULL;
3418 }
Mike Stump1eb44332009-09-09 15:08:12 +00003419
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003420 case Stmt::BinaryOperatorClass: {
3421 // Handle pointer arithmetic. All other binary operators are not valid
3422 // in this context.
3423 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00003424 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00003425
John McCall2de56d12010-08-25 11:45:40 +00003426 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003427 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00003428
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003429 Expr *Base = B->getLHS();
3430
3431 // Determine which argument is the real pointer base. It could be
3432 // the RHS argument instead of the LHS.
3433 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00003434
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003435 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003436 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003437 }
Steve Naroff61f40a22008-09-10 19:17:48 +00003438
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003439 // For conditional operators we need to see if either the LHS or RHS are
3440 // valid DeclRefExpr*s. If one of them is valid, we return it.
3441 case Stmt::ConditionalOperatorClass: {
3442 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003443
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003444 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003445 if (Expr *lhsExpr = C->getLHS()) {
3446 // In C++, we can have a throw-expression, which has 'void' type.
3447 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003448 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003449 return LHS;
3450 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003451
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003452 // In C++, we can have a throw-expression, which has 'void' type.
3453 if (C->getRHS()->getType()->isVoidType())
3454 return NULL;
3455
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003456 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003457 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003458
3459 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00003460 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003461 return E; // local block.
3462 return NULL;
3463
3464 case Stmt::AddrLabelExprClass:
3465 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00003466
John McCall80ee6e82011-11-10 05:35:25 +00003467 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003468 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
3469 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003470
Ted Kremenek54b52742008-08-07 00:49:01 +00003471 // For casts, we need to handle conversions from arrays to
3472 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00003473 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003474 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003475 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00003476 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00003477 case Stmt::CXXStaticCastExprClass:
3478 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00003479 case Stmt::CXXConstCastExprClass:
3480 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00003481 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3482 switch (cast<CastExpr>(E)->getCastKind()) {
3483 case CK_BitCast:
3484 case CK_LValueToRValue:
3485 case CK_NoOp:
3486 case CK_BaseToDerived:
3487 case CK_DerivedToBase:
3488 case CK_UncheckedDerivedToBase:
3489 case CK_Dynamic:
3490 case CK_CPointerToObjCPointerCast:
3491 case CK_BlockPointerToObjCPointerCast:
3492 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003493 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003494
3495 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003496 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003497
3498 default:
3499 return 0;
3500 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003501 }
Mike Stump1eb44332009-09-09 15:08:12 +00003502
Douglas Gregor03e80032011-06-21 17:03:29 +00003503 case Stmt::MaterializeTemporaryExprClass:
3504 if (Expr *Result = EvalAddr(
3505 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003506 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003507 return Result;
3508
3509 return E;
3510
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003511 // Everything else: we simply don't reason about them.
3512 default:
3513 return NULL;
3514 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003515}
Mike Stump1eb44332009-09-09 15:08:12 +00003516
Ted Kremenek06de2762007-08-17 16:46:58 +00003517
3518/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3519/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003520static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3521 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003522do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003523 // We should only be called for evaluating non-pointer expressions, or
3524 // expressions with a pointer type that are not used as references but instead
3525 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00003526
Ted Kremenek06de2762007-08-17 16:46:58 +00003527 // Our "symbolic interpreter" is just a dispatch off the currently
3528 // viewed AST node. We then recursively traverse the AST by calling
3529 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00003530
3531 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00003532 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003533 case Stmt::ImplicitCastExprClass: {
3534 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00003535 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003536 E = IE->getSubExpr();
3537 continue;
3538 }
3539 return NULL;
3540 }
3541
John McCall80ee6e82011-11-10 05:35:25 +00003542 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003543 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003544
Douglas Gregora2813ce2009-10-23 18:54:35 +00003545 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003546 // When we hit a DeclRefExpr we are looking at code that refers to a
3547 // variable's name. If it's not a reference variable we check if it has
3548 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00003549 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003550
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003551 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
3552 // Check if it refers to itself, e.g. "int& i = i;".
3553 if (V == ParentDecl)
3554 return DR;
3555
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003556 if (V->hasLocalStorage()) {
3557 if (!V->getType()->isReferenceType())
3558 return DR;
3559
3560 // Reference variable, follow through to the expression that
3561 // it points to.
3562 if (V->hasInit()) {
3563 // Add the reference variable to the "trail".
3564 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003565 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003566 }
3567 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003568 }
Mike Stump1eb44332009-09-09 15:08:12 +00003569
Ted Kremenek06de2762007-08-17 16:46:58 +00003570 return NULL;
3571 }
Mike Stump1eb44332009-09-09 15:08:12 +00003572
Ted Kremenek06de2762007-08-17 16:46:58 +00003573 case Stmt::UnaryOperatorClass: {
3574 // The only unary operator that make sense to handle here
3575 // is Deref. All others don't resolve to a "name." This includes
3576 // handling all sorts of rvalues passed to a unary operator.
3577 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003578
John McCall2de56d12010-08-25 11:45:40 +00003579 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003580 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003581
3582 return NULL;
3583 }
Mike Stump1eb44332009-09-09 15:08:12 +00003584
Ted Kremenek06de2762007-08-17 16:46:58 +00003585 case Stmt::ArraySubscriptExprClass: {
3586 // Array subscripts are potential references to data on the stack. We
3587 // retrieve the DeclRefExpr* for the array variable if it indeed
3588 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003589 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003590 }
Mike Stump1eb44332009-09-09 15:08:12 +00003591
Ted Kremenek06de2762007-08-17 16:46:58 +00003592 case Stmt::ConditionalOperatorClass: {
3593 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003594 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003595 ConditionalOperator *C = cast<ConditionalOperator>(E);
3596
Anders Carlsson39073232007-11-30 19:04:31 +00003597 // Handle the GNU extension for missing LHS.
3598 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003599 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00003600 return LHS;
3601
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003602 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003603 }
Mike Stump1eb44332009-09-09 15:08:12 +00003604
Ted Kremenek06de2762007-08-17 16:46:58 +00003605 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003606 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003607 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003608
Ted Kremenek06de2762007-08-17 16:46:58 +00003609 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003610 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003611 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003612
3613 // Check whether the member type is itself a reference, in which case
3614 // we're not going to refer to the member, but to what the member refers to.
3615 if (M->getMemberDecl()->getType()->isReferenceType())
3616 return NULL;
3617
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003618 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003619 }
Mike Stump1eb44332009-09-09 15:08:12 +00003620
Douglas Gregor03e80032011-06-21 17:03:29 +00003621 case Stmt::MaterializeTemporaryExprClass:
3622 if (Expr *Result = EvalVal(
3623 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003624 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003625 return Result;
3626
3627 return E;
3628
Ted Kremenek06de2762007-08-17 16:46:58 +00003629 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003630 // Check that we don't return or take the address of a reference to a
3631 // temporary. This is only useful in C++.
3632 if (!E->isTypeDependent() && E->isRValue())
3633 return E;
3634
3635 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003636 return NULL;
3637 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003638} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003639}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003640
3641//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3642
3643/// Check for comparisons of floating point operands using != and ==.
3644/// Issue a warning if these are no self-comparisons, as they are not likely
3645/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003646void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00003647 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3648 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003649
3650 // Special case: check for x == x (which is OK).
3651 // Do not emit warnings for such cases.
3652 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3653 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3654 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00003655 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003656
3657
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003658 // Special case: check for comparisons against literals that can be exactly
3659 // represented by APFloat. In such cases, do not emit a warning. This
3660 // is a heuristic: often comparison against such literals are used to
3661 // detect if a value in a variable has not changed. This clearly can
3662 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00003663 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3664 if (FLL->isExact())
3665 return;
3666 } else
3667 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
3668 if (FLR->isExact())
3669 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003670
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003671 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00003672 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
3673 if (CL->isBuiltinCall())
3674 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003675
David Blaikie980343b2012-07-16 20:47:22 +00003676 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
3677 if (CR->isBuiltinCall())
3678 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003679
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003680 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00003681 Diag(Loc, diag::warn_floatingpoint_eq)
3682 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003683}
John McCallba26e582010-01-04 23:21:16 +00003684
John McCallf2370c92010-01-06 05:24:50 +00003685//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3686//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003687
John McCallf2370c92010-01-06 05:24:50 +00003688namespace {
John McCallba26e582010-01-04 23:21:16 +00003689
John McCallf2370c92010-01-06 05:24:50 +00003690/// Structure recording the 'active' range of an integer-valued
3691/// expression.
3692struct IntRange {
3693 /// The number of bits active in the int.
3694 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003695
John McCallf2370c92010-01-06 05:24:50 +00003696 /// True if the int is known not to have negative values.
3697 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003698
John McCallf2370c92010-01-06 05:24:50 +00003699 IntRange(unsigned Width, bool NonNegative)
3700 : Width(Width), NonNegative(NonNegative)
3701 {}
John McCallba26e582010-01-04 23:21:16 +00003702
John McCall1844a6e2010-11-10 23:38:19 +00003703 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00003704 static IntRange forBoolType() {
3705 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00003706 }
3707
John McCall1844a6e2010-11-10 23:38:19 +00003708 /// Returns the range of an opaque value of the given integral type.
3709 static IntRange forValueOfType(ASTContext &C, QualType T) {
3710 return forValueOfCanonicalType(C,
3711 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00003712 }
3713
John McCall1844a6e2010-11-10 23:38:19 +00003714 /// Returns the range of an opaque value of a canonical integral type.
3715 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00003716 assert(T->isCanonicalUnqualified());
3717
3718 if (const VectorType *VT = dyn_cast<VectorType>(T))
3719 T = VT->getElementType().getTypePtr();
3720 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3721 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00003722
John McCall091f23f2010-11-09 22:22:12 +00003723 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00003724 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3725 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00003726 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00003727 return IntRange(C.getIntWidth(QualType(T, 0)), false);
3728
John McCall323ed742010-05-06 08:58:33 +00003729 unsigned NumPositive = Enum->getNumPositiveBits();
3730 unsigned NumNegative = Enum->getNumNegativeBits();
3731
3732 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3733 }
John McCallf2370c92010-01-06 05:24:50 +00003734
3735 const BuiltinType *BT = cast<BuiltinType>(T);
3736 assert(BT->isInteger());
3737
3738 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3739 }
3740
John McCall1844a6e2010-11-10 23:38:19 +00003741 /// Returns the "target" range of a canonical integral type, i.e.
3742 /// the range of values expressible in the type.
3743 ///
3744 /// This matches forValueOfCanonicalType except that enums have the
3745 /// full range of their type, not the range of their enumerators.
3746 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3747 assert(T->isCanonicalUnqualified());
3748
3749 if (const VectorType *VT = dyn_cast<VectorType>(T))
3750 T = VT->getElementType().getTypePtr();
3751 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3752 T = CT->getElementType().getTypePtr();
3753 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00003754 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00003755
3756 const BuiltinType *BT = cast<BuiltinType>(T);
3757 assert(BT->isInteger());
3758
3759 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3760 }
3761
3762 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003763 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00003764 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00003765 L.NonNegative && R.NonNegative);
3766 }
3767
John McCall1844a6e2010-11-10 23:38:19 +00003768 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003769 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00003770 return IntRange(std::min(L.Width, R.Width),
3771 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00003772 }
3773};
3774
Ted Kremenek0692a192012-01-31 05:37:37 +00003775static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
3776 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003777 if (value.isSigned() && value.isNegative())
3778 return IntRange(value.getMinSignedBits(), false);
3779
3780 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003781 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003782
3783 // isNonNegative() just checks the sign bit without considering
3784 // signedness.
3785 return IntRange(value.getActiveBits(), true);
3786}
3787
Ted Kremenek0692a192012-01-31 05:37:37 +00003788static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
3789 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003790 if (result.isInt())
3791 return GetValueRange(C, result.getInt(), MaxWidth);
3792
3793 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00003794 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3795 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3796 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3797 R = IntRange::join(R, El);
3798 }
John McCallf2370c92010-01-06 05:24:50 +00003799 return R;
3800 }
3801
3802 if (result.isComplexInt()) {
3803 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3804 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3805 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00003806 }
3807
3808 // This can happen with lossless casts to intptr_t of "based" lvalues.
3809 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00003810 // FIXME: The only reason we need to pass the type in here is to get
3811 // the sign right on this one case. It would be nice if APValue
3812 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00003813 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003814 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00003815}
John McCallf2370c92010-01-06 05:24:50 +00003816
3817/// Pseudo-evaluate the given integer expression, estimating the
3818/// range of values it might take.
3819///
3820/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00003821static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003822 E = E->IgnoreParens();
3823
3824 // Try a full evaluation first.
3825 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003826 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00003827 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003828
3829 // I think we only want to look through implicit casts here; if the
3830 // user has an explicit widening cast, we should treat the value as
3831 // being of the new, wider type.
3832 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00003833 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00003834 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3835
John McCall1844a6e2010-11-10 23:38:19 +00003836 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00003837
John McCall2de56d12010-08-25 11:45:40 +00003838 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00003839
John McCallf2370c92010-01-06 05:24:50 +00003840 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00003841 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00003842 return OutputTypeRange;
3843
3844 IntRange SubRange
3845 = GetExprRange(C, CE->getSubExpr(),
3846 std::min(MaxWidth, OutputTypeRange.Width));
3847
3848 // Bail out if the subexpr's range is as wide as the cast type.
3849 if (SubRange.Width >= OutputTypeRange.Width)
3850 return OutputTypeRange;
3851
3852 // Otherwise, we take the smaller width, and we're non-negative if
3853 // either the output type or the subexpr is.
3854 return IntRange(SubRange.Width,
3855 SubRange.NonNegative || OutputTypeRange.NonNegative);
3856 }
3857
3858 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3859 // If we can fold the condition, just take that operand.
3860 bool CondResult;
3861 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3862 return GetExprRange(C, CondResult ? CO->getTrueExpr()
3863 : CO->getFalseExpr(),
3864 MaxWidth);
3865
3866 // Otherwise, conservatively merge.
3867 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3868 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3869 return IntRange::join(L, R);
3870 }
3871
3872 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3873 switch (BO->getOpcode()) {
3874
3875 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00003876 case BO_LAnd:
3877 case BO_LOr:
3878 case BO_LT:
3879 case BO_GT:
3880 case BO_LE:
3881 case BO_GE:
3882 case BO_EQ:
3883 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00003884 return IntRange::forBoolType();
3885
John McCall862ff872011-07-13 06:35:24 +00003886 // The type of the assignments is the type of the LHS, so the RHS
3887 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00003888 case BO_MulAssign:
3889 case BO_DivAssign:
3890 case BO_RemAssign:
3891 case BO_AddAssign:
3892 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00003893 case BO_XorAssign:
3894 case BO_OrAssign:
3895 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00003896 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00003897
John McCall862ff872011-07-13 06:35:24 +00003898 // Simple assignments just pass through the RHS, which will have
3899 // been coerced to the LHS type.
3900 case BO_Assign:
3901 // TODO: bitfields?
3902 return GetExprRange(C, BO->getRHS(), MaxWidth);
3903
John McCallf2370c92010-01-06 05:24:50 +00003904 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003905 case BO_PtrMemD:
3906 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00003907 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003908
John McCall60fad452010-01-06 22:07:33 +00003909 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00003910 case BO_And:
3911 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00003912 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3913 GetExprRange(C, BO->getRHS(), MaxWidth));
3914
John McCallf2370c92010-01-06 05:24:50 +00003915 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00003916 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00003917 // ...except that we want to treat '1 << (blah)' as logically
3918 // positive. It's an important idiom.
3919 if (IntegerLiteral *I
3920 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3921 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00003922 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00003923 return IntRange(R.Width, /*NonNegative*/ true);
3924 }
3925 }
3926 // fallthrough
3927
John McCall2de56d12010-08-25 11:45:40 +00003928 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00003929 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003930
John McCall60fad452010-01-06 22:07:33 +00003931 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00003932 case BO_Shr:
3933 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00003934 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3935
3936 // If the shift amount is a positive constant, drop the width by
3937 // that much.
3938 llvm::APSInt shift;
3939 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3940 shift.isNonNegative()) {
3941 unsigned zext = shift.getZExtValue();
3942 if (zext >= L.Width)
3943 L.Width = (L.NonNegative ? 0 : 1);
3944 else
3945 L.Width -= zext;
3946 }
3947
3948 return L;
3949 }
3950
3951 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00003952 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00003953 return GetExprRange(C, BO->getRHS(), MaxWidth);
3954
John McCall60fad452010-01-06 22:07:33 +00003955 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00003956 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00003957 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00003958 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00003959 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003960
John McCall00fe7612011-07-14 22:39:48 +00003961 // The width of a division result is mostly determined by the size
3962 // of the LHS.
3963 case BO_Div: {
3964 // Don't 'pre-truncate' the operands.
3965 unsigned opWidth = C.getIntWidth(E->getType());
3966 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3967
3968 // If the divisor is constant, use that.
3969 llvm::APSInt divisor;
3970 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3971 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3972 if (log2 >= L.Width)
3973 L.Width = (L.NonNegative ? 0 : 1);
3974 else
3975 L.Width = std::min(L.Width - log2, MaxWidth);
3976 return L;
3977 }
3978
3979 // Otherwise, just use the LHS's width.
3980 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3981 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3982 }
3983
3984 // The result of a remainder can't be larger than the result of
3985 // either side.
3986 case BO_Rem: {
3987 // Don't 'pre-truncate' the operands.
3988 unsigned opWidth = C.getIntWidth(E->getType());
3989 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3990 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3991
3992 IntRange meet = IntRange::meet(L, R);
3993 meet.Width = std::min(meet.Width, MaxWidth);
3994 return meet;
3995 }
3996
3997 // The default behavior is okay for these.
3998 case BO_Mul:
3999 case BO_Add:
4000 case BO_Xor:
4001 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00004002 break;
4003 }
4004
John McCall00fe7612011-07-14 22:39:48 +00004005 // The default case is to treat the operation as if it were closed
4006 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004007 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4008 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4009 return IntRange::join(L, R);
4010 }
4011
4012 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4013 switch (UO->getOpcode()) {
4014 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004015 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004016 return IntRange::forBoolType();
4017
4018 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004019 case UO_Deref:
4020 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00004021 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004022
4023 default:
4024 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4025 }
4026 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004027
4028 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00004029 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004030 }
John McCallf2370c92010-01-06 05:24:50 +00004031
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004032 if (FieldDecl *BitField = E->getBitField())
4033 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004034 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004035
John McCall1844a6e2010-11-10 23:38:19 +00004036 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004037}
John McCall51313c32010-01-04 23:31:57 +00004038
Ted Kremenek0692a192012-01-31 05:37:37 +00004039static IntRange GetExprRange(ASTContext &C, Expr *E) {
John McCall323ed742010-05-06 08:58:33 +00004040 return GetExprRange(C, E, C.getIntWidth(E->getType()));
4041}
4042
John McCall51313c32010-01-04 23:31:57 +00004043/// Checks whether the given value, which currently has the given
4044/// source semantics, has the same value when coerced through the
4045/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004046static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4047 const llvm::fltSemantics &Src,
4048 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004049 llvm::APFloat truncated = value;
4050
4051 bool ignored;
4052 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4053 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4054
4055 return truncated.bitwiseIsEqual(value);
4056}
4057
4058/// Checks whether the given value, which currently has the given
4059/// source semantics, has the same value when coerced through the
4060/// target semantics.
4061///
4062/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004063static bool IsSameFloatAfterCast(const APValue &value,
4064 const llvm::fltSemantics &Src,
4065 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004066 if (value.isFloat())
4067 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4068
4069 if (value.isVector()) {
4070 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4071 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4072 return false;
4073 return true;
4074 }
4075
4076 assert(value.isComplexFloat());
4077 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4078 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4079}
4080
Ted Kremenek0692a192012-01-31 05:37:37 +00004081static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004082
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004083static bool IsZero(Sema &S, Expr *E) {
4084 // Suppress cases where we are comparing against an enum constant.
4085 if (const DeclRefExpr *DR =
4086 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4087 if (isa<EnumConstantDecl>(DR->getDecl()))
4088 return false;
4089
4090 // Suppress cases where the '0' value is expanded from a macro.
4091 if (E->getLocStart().isMacroID())
4092 return false;
4093
John McCall323ed742010-05-06 08:58:33 +00004094 llvm::APSInt Value;
4095 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4096}
4097
John McCall372e1032010-10-06 00:25:24 +00004098static bool HasEnumType(Expr *E) {
4099 // Strip off implicit integral promotions.
4100 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004101 if (ICE->getCastKind() != CK_IntegralCast &&
4102 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004103 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004104 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004105 }
4106
4107 return E->getType()->isEnumeralType();
4108}
4109
Ted Kremenek0692a192012-01-31 05:37:37 +00004110static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004111 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004112 if (E->isValueDependent())
4113 return;
4114
John McCall2de56d12010-08-25 11:45:40 +00004115 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004116 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004117 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004118 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004119 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004120 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004121 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004122 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004123 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004124 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004125 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004126 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004127 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004128 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004129 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004130 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4131 }
4132}
4133
4134/// Analyze the operands of the given comparison. Implements the
4135/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004136static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004137 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4138 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004139}
John McCall51313c32010-01-04 23:31:57 +00004140
John McCallba26e582010-01-04 23:21:16 +00004141/// \brief Implements -Wsign-compare.
4142///
Richard Trieudd225092011-09-15 21:56:47 +00004143/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004144static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004145 // The type the comparison is being performed in.
4146 QualType T = E->getLHS()->getType();
4147 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4148 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00004149
John McCall323ed742010-05-06 08:58:33 +00004150 // We don't do anything special if this isn't an unsigned integral
4151 // comparison: we're only interested in integral comparisons, and
4152 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004153 //
4154 // We also don't care about value-dependent expressions or expressions
4155 // whose result is a constant.
4156 if (!T->hasUnsignedIntegerRepresentation()
4157 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00004158 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00004159
Richard Trieudd225092011-09-15 21:56:47 +00004160 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4161 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00004162
John McCall323ed742010-05-06 08:58:33 +00004163 // Check to see if one of the (unmodified) operands is of different
4164 // signedness.
4165 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004166 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4167 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004168 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004169 signedOperand = LHS;
4170 unsignedOperand = RHS;
4171 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4172 signedOperand = RHS;
4173 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004174 } else {
John McCall323ed742010-05-06 08:58:33 +00004175 CheckTrivialUnsignedComparison(S, E);
4176 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004177 }
4178
John McCall323ed742010-05-06 08:58:33 +00004179 // Otherwise, calculate the effective range of the signed operand.
4180 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004181
John McCall323ed742010-05-06 08:58:33 +00004182 // Go ahead and analyze implicit conversions in the operands. Note
4183 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004184 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4185 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004186
John McCall323ed742010-05-06 08:58:33 +00004187 // If the signed range is non-negative, -Wsign-compare won't fire,
4188 // but we should still check for comparisons which are always true
4189 // or false.
4190 if (signedRange.NonNegative)
4191 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004192
4193 // For (in)equality comparisons, if the unsigned operand is a
4194 // constant which cannot collide with a overflowed signed operand,
4195 // then reinterpreting the signed operand as unsigned will not
4196 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00004197 if (E->isEqualityOp()) {
4198 unsigned comparisonWidth = S.Context.getIntWidth(T);
4199 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00004200
John McCall323ed742010-05-06 08:58:33 +00004201 // We should never be unable to prove that the unsigned operand is
4202 // non-negative.
4203 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
4204
4205 if (unsignedRange.Width < comparisonWidth)
4206 return;
4207 }
4208
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00004209 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4210 S.PDiag(diag::warn_mixed_sign_comparison)
4211 << LHS->getType() << RHS->getType()
4212 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00004213}
4214
John McCall15d7d122010-11-11 03:21:53 +00004215/// Analyzes an attempt to assign the given value to a bitfield.
4216///
4217/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00004218static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4219 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00004220 assert(Bitfield->isBitField());
4221 if (Bitfield->isInvalidDecl())
4222 return false;
4223
John McCall91b60142010-11-11 05:33:51 +00004224 // White-list bool bitfields.
4225 if (Bitfield->getType()->isBooleanType())
4226 return false;
4227
Douglas Gregor46ff3032011-02-04 13:09:01 +00004228 // Ignore value- or type-dependent expressions.
4229 if (Bitfield->getBitWidth()->isValueDependent() ||
4230 Bitfield->getBitWidth()->isTypeDependent() ||
4231 Init->isValueDependent() ||
4232 Init->isTypeDependent())
4233 return false;
4234
John McCall15d7d122010-11-11 03:21:53 +00004235 Expr *OriginalInit = Init->IgnoreParenImpCasts();
4236
Richard Smith80d4b552011-12-28 19:48:30 +00004237 llvm::APSInt Value;
4238 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00004239 return false;
4240
John McCall15d7d122010-11-11 03:21:53 +00004241 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004242 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00004243
4244 if (OriginalWidth <= FieldWidth)
4245 return false;
4246
Eli Friedman3a643af2012-01-26 23:11:39 +00004247 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004248 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00004249 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00004250
Eli Friedman3a643af2012-01-26 23:11:39 +00004251 // Check whether the stored value is equal to the original value.
4252 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00004253 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00004254 return false;
4255
Eli Friedman3a643af2012-01-26 23:11:39 +00004256 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00004257 // therefore don't strictly fit into a signed bitfield of width 1.
4258 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00004259 return false;
4260
John McCall15d7d122010-11-11 03:21:53 +00004261 std::string PrettyValue = Value.toString(10);
4262 std::string PrettyTrunc = TruncatedValue.toString(10);
4263
4264 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4265 << PrettyValue << PrettyTrunc << OriginalInit->getType()
4266 << Init->getSourceRange();
4267
4268 return true;
4269}
4270
John McCallbeb22aa2010-11-09 23:24:47 +00004271/// Analyze the given simple or compound assignment for warning-worthy
4272/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00004273static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00004274 // Just recurse on the LHS.
4275 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4276
4277 // We want to recurse on the RHS as normal unless we're assigning to
4278 // a bitfield.
4279 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00004280 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
4281 E->getOperatorLoc())) {
4282 // Recurse, ignoring any implicit conversions on the RHS.
4283 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
4284 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00004285 }
4286 }
4287
4288 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4289}
4290
John McCall51313c32010-01-04 23:31:57 +00004291/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004292static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004293 SourceLocation CContext, unsigned diag,
4294 bool pruneControlFlow = false) {
4295 if (pruneControlFlow) {
4296 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4297 S.PDiag(diag)
4298 << SourceType << T << E->getSourceRange()
4299 << SourceRange(CContext));
4300 return;
4301 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004302 S.Diag(E->getExprLoc(), diag)
4303 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
4304}
4305
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004306/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004307static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004308 SourceLocation CContext, unsigned diag,
4309 bool pruneControlFlow = false) {
4310 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004311}
4312
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004313/// Diagnose an implicit cast from a literal expression. Does not warn when the
4314/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004315void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
4316 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004317 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004318 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004319 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00004320 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
4321 T->hasUnsignedIntegerRepresentation());
4322 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00004323 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004324 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00004325 return;
4326
David Blaikiebe0ee872012-05-15 16:56:36 +00004327 SmallString<16> PrettySourceValue;
4328 Value.toString(PrettySourceValue);
David Blaikiede7e7b82012-05-15 17:18:27 +00004329 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00004330 if (T->isSpecificBuiltinType(BuiltinType::Bool))
4331 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
4332 else
David Blaikiede7e7b82012-05-15 17:18:27 +00004333 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00004334
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004335 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00004336 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
4337 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00004338}
4339
John McCall091f23f2010-11-09 22:22:12 +00004340std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
4341 if (!Range.Width) return "0";
4342
4343 llvm::APSInt ValueInRange = Value;
4344 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00004345 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00004346 return ValueInRange.toString(10);
4347}
4348
John McCall323ed742010-05-06 08:58:33 +00004349void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004350 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00004351 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00004352
John McCall323ed742010-05-06 08:58:33 +00004353 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
4354 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
4355 if (Source == Target) return;
4356 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00004357
Chandler Carruth108f7562011-07-26 05:40:03 +00004358 // If the conversion context location is invalid don't complain. We also
4359 // don't want to emit a warning if the issue occurs from the expansion of
4360 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
4361 // delay this check as long as possible. Once we detect we are in that
4362 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00004363 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00004364 return;
4365
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004366 // Diagnose implicit casts to bool.
4367 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
4368 if (isa<StringLiteral>(E))
4369 // Warn on string literal to bool. Checks for string literals in logical
4370 // expressions, for instances, assert(0 && "error here"), is prevented
4371 // by a check in AnalyzeImplicitConversions().
4372 return DiagnoseImpCast(S, E, T, CC,
4373 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00004374 if (Source->isFunctionType()) {
4375 // Warn on function to bool. Checks free functions and static member
4376 // functions. Weakly imported functions are excluded from the check,
4377 // since it's common to test their value to check whether the linker
4378 // found a definition for them.
4379 ValueDecl *D = 0;
4380 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
4381 D = R->getDecl();
4382 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
4383 D = M->getMemberDecl();
4384 }
4385
4386 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00004387 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
4388 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
4389 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00004390 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
4391 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
4392 QualType ReturnType;
4393 UnresolvedSet<4> NonTemplateOverloads;
4394 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
4395 if (!ReturnType.isNull()
4396 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
4397 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
4398 << FixItHint::CreateInsertion(
4399 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00004400 return;
4401 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00004402 }
4403 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004404 }
John McCall51313c32010-01-04 23:31:57 +00004405
4406 // Strip vector types.
4407 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004408 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004409 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004410 return;
John McCallb4eb64d2010-10-08 02:01:28 +00004411 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004412 }
Chris Lattnerb792b302011-06-14 04:51:15 +00004413
4414 // If the vector cast is cast between two vectors of the same size, it is
4415 // a bitcast, not a conversion.
4416 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4417 return;
John McCall51313c32010-01-04 23:31:57 +00004418
4419 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4420 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4421 }
4422
4423 // Strip complex types.
4424 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004425 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004426 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004427 return;
4428
John McCallb4eb64d2010-10-08 02:01:28 +00004429 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004430 }
John McCall51313c32010-01-04 23:31:57 +00004431
4432 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4433 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4434 }
4435
4436 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4437 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4438
4439 // If the source is floating point...
4440 if (SourceBT && SourceBT->isFloatingPoint()) {
4441 // ...and the target is floating point...
4442 if (TargetBT && TargetBT->isFloatingPoint()) {
4443 // ...then warn if we're dropping FP rank.
4444
4445 // Builtin FP kinds are ordered by increasing FP rank.
4446 if (SourceBT->getKind() > TargetBT->getKind()) {
4447 // Don't warn about float constants that are precisely
4448 // representable in the target type.
4449 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004450 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00004451 // Value might be a float, a float vector, or a float complex.
4452 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00004453 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4454 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00004455 return;
4456 }
4457
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004458 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004459 return;
4460
John McCallb4eb64d2010-10-08 02:01:28 +00004461 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00004462 }
4463 return;
4464 }
4465
Ted Kremenekef9ff882011-03-10 20:03:42 +00004466 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00004467 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004468 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004469 return;
4470
Chandler Carrutha5b93322011-02-17 11:05:49 +00004471 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00004472 // We also want to warn on, e.g., "int i = -1.234"
4473 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4474 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4475 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
4476
Chandler Carruthf65076e2011-04-10 08:36:24 +00004477 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4478 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00004479 } else {
4480 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4481 }
4482 }
John McCall51313c32010-01-04 23:31:57 +00004483
4484 return;
4485 }
4486
Richard Trieu1838ca52011-05-29 19:59:02 +00004487 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00004488 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikie28a5f0c2012-06-21 18:51:10 +00004489 && !Target->isBlockPointerType() && !Target->isMemberPointerType()) {
David Blaikieb1360492012-03-16 20:30:12 +00004490 SourceLocation Loc = E->getSourceRange().getBegin();
4491 if (Loc.isMacroID())
4492 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00004493 if (!Loc.isMacroID() || CC.isMacroID())
4494 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
4495 << T << clang::SourceRange(CC)
4496 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
Richard Trieu1838ca52011-05-29 19:59:02 +00004497 }
4498
David Blaikieb26331b2012-06-19 21:19:06 +00004499 if (!Source->isIntegerType() || !Target->isIntegerType())
4500 return;
4501
David Blaikiebe0ee872012-05-15 16:56:36 +00004502 // TODO: remove this early return once the false positives for constant->bool
4503 // in templates, macros, etc, are reduced or removed.
4504 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
4505 return;
4506
John McCall323ed742010-05-06 08:58:33 +00004507 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00004508 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00004509
4510 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00004511 // If the source is a constant, use a default-on diagnostic.
4512 // TODO: this should happen for bitfield stores, too.
4513 llvm::APSInt Value(32);
4514 if (E->isIntegerConstantExpr(Value, S.Context)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004515 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004516 return;
4517
John McCall091f23f2010-11-09 22:22:12 +00004518 std::string PrettySourceValue = Value.toString(10);
4519 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
4520
Ted Kremenek5e745da2011-10-22 02:37:33 +00004521 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4522 S.PDiag(diag::warn_impcast_integer_precision_constant)
4523 << PrettySourceValue << PrettyTargetValue
4524 << E->getType() << T << E->getSourceRange()
4525 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00004526 return;
4527 }
4528
Chris Lattnerb792b302011-06-14 04:51:15 +00004529 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004530 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004531 return;
4532
David Blaikie37050842012-04-12 22:40:54 +00004533 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00004534 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
4535 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00004536 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00004537 }
4538
4539 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
4540 (!TargetRange.NonNegative && SourceRange.NonNegative &&
4541 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004542
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004543 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004544 return;
4545
John McCall323ed742010-05-06 08:58:33 +00004546 unsigned DiagID = diag::warn_impcast_integer_sign;
4547
4548 // Traditionally, gcc has warned about this under -Wsign-compare.
4549 // We also want to warn about it in -Wconversion.
4550 // So if -Wconversion is off, use a completely identical diagnostic
4551 // in the sign-compare group.
4552 // The conditional-checking code will
4553 if (ICContext) {
4554 DiagID = diag::warn_impcast_integer_sign_conditional;
4555 *ICContext = true;
4556 }
4557
John McCallb4eb64d2010-10-08 02:01:28 +00004558 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00004559 }
4560
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004561 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004562 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
4563 // type, to give us better diagnostics.
4564 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00004565 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004566 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4567 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4568 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
4569 SourceType = S.Context.getTypeDeclType(Enum);
4570 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
4571 }
4572 }
4573
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004574 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
4575 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
4576 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004577 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004578 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004579 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00004580 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004581 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004582 return;
4583
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004584 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004585 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004586 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004587
John McCall51313c32010-01-04 23:31:57 +00004588 return;
4589}
4590
David Blaikie9fb1ac52012-05-15 21:57:38 +00004591void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
4592 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00004593
4594void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004595 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00004596 E = E->IgnoreParenImpCasts();
4597
4598 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00004599 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00004600
John McCallb4eb64d2010-10-08 02:01:28 +00004601 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004602 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004603 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00004604 return;
4605}
4606
David Blaikie9fb1ac52012-05-15 21:57:38 +00004607void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
4608 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00004609 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00004610
4611 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00004612 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
4613 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004614
4615 // If -Wconversion would have warned about either of the candidates
4616 // for a signedness conversion to the context type...
4617 if (!Suspicious) return;
4618
4619 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004620 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
4621 CC))
John McCall323ed742010-05-06 08:58:33 +00004622 return;
4623
John McCall323ed742010-05-06 08:58:33 +00004624 // ...then check whether it would have warned about either of the
4625 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00004626 if (E->getType() == T) return;
4627
4628 Suspicious = false;
4629 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
4630 E->getType(), CC, &Suspicious);
4631 if (!Suspicious)
4632 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00004633 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004634}
4635
4636/// AnalyzeImplicitConversions - Find and report any interesting
4637/// implicit conversions in the given expression. There are a couple
4638/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004639void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004640 QualType T = OrigE->getType();
4641 Expr *E = OrigE->IgnoreParenImpCasts();
4642
Douglas Gregorf8b6e152011-10-10 17:38:18 +00004643 if (E->isTypeDependent() || E->isValueDependent())
4644 return;
4645
John McCall323ed742010-05-06 08:58:33 +00004646 // For conditional operators, we analyze the arguments as if they
4647 // were being fed directly into the output.
4648 if (isa<ConditionalOperator>(E)) {
4649 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00004650 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00004651 return;
4652 }
4653
4654 // Go ahead and check any implicit conversions we might have skipped.
4655 // The non-canonical typecheck is just an optimization;
4656 // CheckImplicitConversion will filter out dead implicit conversions.
4657 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004658 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00004659
4660 // Now continue drilling into this expression.
4661
4662 // Skip past explicit casts.
4663 if (isa<ExplicitCastExpr>(E)) {
4664 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00004665 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004666 }
4667
John McCallbeb22aa2010-11-09 23:24:47 +00004668 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4669 // Do a somewhat different check with comparison operators.
4670 if (BO->isComparisonOp())
4671 return AnalyzeComparison(S, BO);
4672
Eli Friedman0fa06382012-01-26 23:34:06 +00004673 // And with simple assignments.
4674 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00004675 return AnalyzeAssignment(S, BO);
4676 }
John McCall323ed742010-05-06 08:58:33 +00004677
4678 // These break the otherwise-useful invariant below. Fortunately,
4679 // we don't really need to recurse into them, because any internal
4680 // expressions should have been analyzed already when they were
4681 // built into statements.
4682 if (isa<StmtExpr>(E)) return;
4683
4684 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004685 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00004686
4687 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00004688 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004689 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
4690 bool IsLogicalOperator = BO && BO->isLogicalOp();
4691 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00004692 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00004693 if (!ChildExpr)
4694 continue;
4695
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004696 if (IsLogicalOperator &&
4697 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
4698 // Ignore checking string literals that are in logical operators.
4699 continue;
4700 AnalyzeImplicitConversions(S, ChildExpr, CC);
4701 }
John McCall323ed742010-05-06 08:58:33 +00004702}
4703
4704} // end anonymous namespace
4705
4706/// Diagnoses "dangerous" implicit conversions within the given
4707/// expression (which is a full expression). Implements -Wconversion
4708/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004709///
4710/// \param CC the "context" location of the implicit conversion, i.e.
4711/// the most location of the syntactic entity requiring the implicit
4712/// conversion
4713void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004714 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00004715 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00004716 return;
4717
4718 // Don't diagnose for value- or type-dependent expressions.
4719 if (E->isTypeDependent() || E->isValueDependent())
4720 return;
4721
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004722 // Check for array bounds violations in cases where the check isn't triggered
4723 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
4724 // ArraySubscriptExpr is on the RHS of a variable initialization.
4725 CheckArrayAccess(E);
4726
John McCallb4eb64d2010-10-08 02:01:28 +00004727 // This is not the right CC for (e.g.) a variable initialization.
4728 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004729}
4730
John McCall15d7d122010-11-11 03:21:53 +00004731void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
4732 FieldDecl *BitField,
4733 Expr *Init) {
4734 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
4735}
4736
Mike Stumpf8c49212010-01-21 03:59:47 +00004737/// CheckParmsForFunctionDef - Check that the parameters of the given
4738/// function are appropriate for the definition of a function. This
4739/// takes care of any checks that cannot be performed on the
4740/// declaration itself, e.g., that the types of each of the function
4741/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004742bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
4743 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004744 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00004745 for (; P != PEnd; ++P) {
4746 ParmVarDecl *Param = *P;
4747
Mike Stumpf8c49212010-01-21 03:59:47 +00004748 // C99 6.7.5.3p4: the parameters in a parameter type list in a
4749 // function declarator that is part of a function definition of
4750 // that function shall not have incomplete type.
4751 //
4752 // This is also C++ [dcl.fct]p6.
4753 if (!Param->isInvalidDecl() &&
4754 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004755 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004756 Param->setInvalidDecl();
4757 HasInvalidParm = true;
4758 }
4759
4760 // C99 6.9.1p5: If the declarator includes a parameter type list, the
4761 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004762 if (CheckParameterNames &&
4763 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00004764 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00004765 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00004766 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00004767
4768 // C99 6.7.5.3p12:
4769 // If the function declarator is not part of a definition of that
4770 // function, parameters may have incomplete type and may use the [*]
4771 // notation in their sequences of declarator specifiers to specify
4772 // variable length array types.
4773 QualType PType = Param->getOriginalType();
4774 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
4775 if (AT->getSizeModifier() == ArrayType::Star) {
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00004776 // FIXME: This diagnosic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00004777 // information is added for it.
4778 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
4779 }
4780 }
Mike Stumpf8c49212010-01-21 03:59:47 +00004781 }
4782
4783 return HasInvalidParm;
4784}
John McCallb7f4ffe2010-08-12 21:44:57 +00004785
4786/// CheckCastAlign - Implements -Wcast-align, which warns when a
4787/// pointer cast increases the alignment requirements.
4788void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
4789 // This is actually a lot of work to potentially be doing on every
4790 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004791 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
4792 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00004793 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00004794 return;
4795
4796 // Ignore dependent types.
4797 if (T->isDependentType() || Op->getType()->isDependentType())
4798 return;
4799
4800 // Require that the destination be a pointer type.
4801 const PointerType *DestPtr = T->getAs<PointerType>();
4802 if (!DestPtr) return;
4803
4804 // If the destination has alignment 1, we're done.
4805 QualType DestPointee = DestPtr->getPointeeType();
4806 if (DestPointee->isIncompleteType()) return;
4807 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
4808 if (DestAlign.isOne()) return;
4809
4810 // Require that the source be a pointer type.
4811 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
4812 if (!SrcPtr) return;
4813 QualType SrcPointee = SrcPtr->getPointeeType();
4814
4815 // Whitelist casts from cv void*. We already implicitly
4816 // whitelisted casts to cv void*, since they have alignment 1.
4817 // Also whitelist casts involving incomplete types, which implicitly
4818 // includes 'void'.
4819 if (SrcPointee->isIncompleteType()) return;
4820
4821 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
4822 if (SrcAlign >= DestAlign) return;
4823
4824 Diag(TRange.getBegin(), diag::warn_cast_align)
4825 << Op->getType() << T
4826 << static_cast<unsigned>(SrcAlign.getQuantity())
4827 << static_cast<unsigned>(DestAlign.getQuantity())
4828 << TRange << Op->getSourceRange();
4829}
4830
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004831static const Type* getElementType(const Expr *BaseExpr) {
4832 const Type* EltType = BaseExpr->getType().getTypePtr();
4833 if (EltType->isAnyPointerType())
4834 return EltType->getPointeeType().getTypePtr();
4835 else if (EltType->isArrayType())
4836 return EltType->getBaseElementTypeUnsafe();
4837 return EltType;
4838}
4839
Chandler Carruthc2684342011-08-05 09:10:50 +00004840/// \brief Check whether this array fits the idiom of a size-one tail padded
4841/// array member of a struct.
4842///
4843/// We avoid emitting out-of-bounds access warnings for such arrays as they are
4844/// commonly used to emulate flexible arrays in C89 code.
4845static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4846 const NamedDecl *ND) {
4847 if (Size != 1 || !ND) return false;
4848
4849 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4850 if (!FD) return false;
4851
4852 // Don't consider sizes resulting from macro expansions or template argument
4853 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00004854
4855 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00004856 while (TInfo) {
4857 TypeLoc TL = TInfo->getTypeLoc();
4858 // Look through typedefs.
4859 const TypedefTypeLoc *TTL = dyn_cast<TypedefTypeLoc>(&TL);
4860 if (TTL) {
4861 const TypedefNameDecl *TDL = TTL->getTypedefNameDecl();
4862 TInfo = TDL->getTypeSourceInfo();
4863 continue;
4864 }
4865 ConstantArrayTypeLoc CTL = cast<ConstantArrayTypeLoc>(TL);
4866 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Sean Callanand2cf3482012-05-04 18:22:53 +00004867 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4868 return false;
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00004869 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00004870 }
Chandler Carruthc2684342011-08-05 09:10:50 +00004871
4872 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00004873 if (!RD) return false;
4874 if (RD->isUnion()) return false;
4875 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
4876 if (!CRD->isStandardLayout()) return false;
4877 }
Chandler Carruthc2684342011-08-05 09:10:50 +00004878
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00004879 // See if this is the last field decl in the record.
4880 const Decl *D = FD;
4881 while ((D = D->getNextDeclInContext()))
4882 if (isa<FieldDecl>(D))
4883 return false;
4884 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00004885}
4886
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004887void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004888 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00004889 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00004890 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004891 if (IndexExpr->isValueDependent())
4892 return;
4893
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00004894 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004895 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00004896 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004897 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00004898 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00004899 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00004900
Chandler Carruth34064582011-02-17 20:55:08 +00004901 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004902 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00004903 return;
Richard Smith25b009a2011-12-16 19:31:14 +00004904 if (IndexNegated)
4905 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004906
Chandler Carruthba447122011-08-05 08:07:29 +00004907 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00004908 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4909 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00004910 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00004911 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00004912
Ted Kremenek9e060ca2011-02-23 23:06:04 +00004913 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00004914 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00004915 if (!size.isStrictlyPositive())
4916 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004917
4918 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00004919 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004920 // Make sure we're comparing apples to apples when comparing index to size
4921 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4922 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00004923 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00004924 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004925 if (ptrarith_typesize != array_typesize) {
4926 // There's a cast to a different size type involved
4927 uint64_t ratio = array_typesize / ptrarith_typesize;
4928 // TODO: Be smarter about handling cases where array_typesize is not a
4929 // multiple of ptrarith_typesize
4930 if (ptrarith_typesize * ratio == array_typesize)
4931 size *= llvm::APInt(size.getBitWidth(), ratio);
4932 }
4933 }
4934
Chandler Carruth34064582011-02-17 20:55:08 +00004935 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00004936 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004937 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00004938 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004939
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004940 // For array subscripting the index must be less than size, but for pointer
4941 // arithmetic also allow the index (offset) to be equal to size since
4942 // computing the next address after the end of the array is legal and
4943 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00004944 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00004945 return;
4946
4947 // Also don't warn for arrays of size 1 which are members of some
4948 // structure. These are often used to approximate flexible arrays in C89
4949 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004950 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004951 return;
Chandler Carruth34064582011-02-17 20:55:08 +00004952
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004953 // Suppress the warning if the subscript expression (as identified by the
4954 // ']' location) and the index expression are both from macro expansions
4955 // within a system header.
4956 if (ASE) {
4957 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
4958 ASE->getRBracketLoc());
4959 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
4960 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
4961 IndexExpr->getLocStart());
4962 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
4963 return;
4964 }
4965 }
4966
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004967 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004968 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004969 DiagID = diag::warn_array_index_exceeds_bounds;
4970
4971 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4972 PDiag(DiagID) << index.toString(10, true)
4973 << size.toString(10, true)
4974 << (unsigned)size.getLimitedValue(~0U)
4975 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00004976 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004977 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004978 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004979 DiagID = diag::warn_ptr_arith_precedes_bounds;
4980 if (index.isNegative()) index = -index;
4981 }
4982
4983 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4984 PDiag(DiagID) << index.toString(10, true)
4985 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004986 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00004987
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00004988 if (!ND) {
4989 // Try harder to find a NamedDecl to point at in the note.
4990 while (const ArraySubscriptExpr *ASE =
4991 dyn_cast<ArraySubscriptExpr>(BaseExpr))
4992 BaseExpr = ASE->getBase()->IgnoreParenCasts();
4993 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4994 ND = dyn_cast<NamedDecl>(DRE->getDecl());
4995 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
4996 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
4997 }
4998
Chandler Carruth35001ca2011-02-17 21:10:52 +00004999 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005000 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
5001 PDiag(diag::note_array_index_out_of_bounds)
5002 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00005003}
5004
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005005void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005006 int AllowOnePastEnd = 0;
5007 while (expr) {
5008 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005009 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005010 case Stmt::ArraySubscriptExprClass: {
5011 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005012 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005013 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005014 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005015 }
5016 case Stmt::UnaryOperatorClass: {
5017 // Only unwrap the * and & unary operators
5018 const UnaryOperator *UO = cast<UnaryOperator>(expr);
5019 expr = UO->getSubExpr();
5020 switch (UO->getOpcode()) {
5021 case UO_AddrOf:
5022 AllowOnePastEnd++;
5023 break;
5024 case UO_Deref:
5025 AllowOnePastEnd--;
5026 break;
5027 default:
5028 return;
5029 }
5030 break;
5031 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005032 case Stmt::ConditionalOperatorClass: {
5033 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
5034 if (const Expr *lhs = cond->getLHS())
5035 CheckArrayAccess(lhs);
5036 if (const Expr *rhs = cond->getRHS())
5037 CheckArrayAccess(rhs);
5038 return;
5039 }
5040 default:
5041 return;
5042 }
Peter Collingbournef111d932011-04-15 00:35:48 +00005043 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005044}
John McCallf85e1932011-06-15 23:02:42 +00005045
5046//===--- CHECK: Objective-C retain cycles ----------------------------------//
5047
5048namespace {
5049 struct RetainCycleOwner {
5050 RetainCycleOwner() : Variable(0), Indirect(false) {}
5051 VarDecl *Variable;
5052 SourceRange Range;
5053 SourceLocation Loc;
5054 bool Indirect;
5055
5056 void setLocsFrom(Expr *e) {
5057 Loc = e->getExprLoc();
5058 Range = e->getSourceRange();
5059 }
5060 };
5061}
5062
5063/// Consider whether capturing the given variable can possibly lead to
5064/// a retain cycle.
5065static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
5066 // In ARC, it's captured strongly iff the variable has __strong
5067 // lifetime. In MRR, it's captured strongly if the variable is
5068 // __block and has an appropriate type.
5069 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
5070 return false;
5071
5072 owner.Variable = var;
5073 owner.setLocsFrom(ref);
5074 return true;
5075}
5076
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005077static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00005078 while (true) {
5079 e = e->IgnoreParens();
5080 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
5081 switch (cast->getCastKind()) {
5082 case CK_BitCast:
5083 case CK_LValueBitCast:
5084 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00005085 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00005086 e = cast->getSubExpr();
5087 continue;
5088
John McCallf85e1932011-06-15 23:02:42 +00005089 default:
5090 return false;
5091 }
5092 }
5093
5094 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
5095 ObjCIvarDecl *ivar = ref->getDecl();
5096 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
5097 return false;
5098
5099 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005100 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00005101 return false;
5102
5103 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
5104 owner.Indirect = true;
5105 return true;
5106 }
5107
5108 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
5109 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
5110 if (!var) return false;
5111 return considerVariable(var, ref, owner);
5112 }
5113
John McCallf85e1932011-06-15 23:02:42 +00005114 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
5115 if (member->isArrow()) return false;
5116
5117 // Don't count this as an indirect ownership.
5118 e = member->getBase();
5119 continue;
5120 }
5121
John McCall4b9c2d22011-11-06 09:01:30 +00005122 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
5123 // Only pay attention to pseudo-objects on property references.
5124 ObjCPropertyRefExpr *pre
5125 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
5126 ->IgnoreParens());
5127 if (!pre) return false;
5128 if (pre->isImplicitProperty()) return false;
5129 ObjCPropertyDecl *property = pre->getExplicitProperty();
5130 if (!property->isRetaining() &&
5131 !(property->getPropertyIvarDecl() &&
5132 property->getPropertyIvarDecl()->getType()
5133 .getObjCLifetime() == Qualifiers::OCL_Strong))
5134 return false;
5135
5136 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005137 if (pre->isSuperReceiver()) {
5138 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
5139 if (!owner.Variable)
5140 return false;
5141 owner.Loc = pre->getLocation();
5142 owner.Range = pre->getSourceRange();
5143 return true;
5144 }
John McCall4b9c2d22011-11-06 09:01:30 +00005145 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
5146 ->getSourceExpr());
5147 continue;
5148 }
5149
John McCallf85e1932011-06-15 23:02:42 +00005150 // Array ivars?
5151
5152 return false;
5153 }
5154}
5155
5156namespace {
5157 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
5158 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
5159 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
5160 Variable(variable), Capturer(0) {}
5161
5162 VarDecl *Variable;
5163 Expr *Capturer;
5164
5165 void VisitDeclRefExpr(DeclRefExpr *ref) {
5166 if (ref->getDecl() == Variable && !Capturer)
5167 Capturer = ref;
5168 }
5169
John McCallf85e1932011-06-15 23:02:42 +00005170 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
5171 if (Capturer) return;
5172 Visit(ref->getBase());
5173 if (Capturer && ref->isFreeIvar())
5174 Capturer = ref;
5175 }
5176
5177 void VisitBlockExpr(BlockExpr *block) {
5178 // Look inside nested blocks
5179 if (block->getBlockDecl()->capturesVariable(Variable))
5180 Visit(block->getBlockDecl()->getBody());
5181 }
5182 };
5183}
5184
5185/// Check whether the given argument is a block which captures a
5186/// variable.
5187static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
5188 assert(owner.Variable && owner.Loc.isValid());
5189
5190 e = e->IgnoreParenCasts();
5191 BlockExpr *block = dyn_cast<BlockExpr>(e);
5192 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
5193 return 0;
5194
5195 FindCaptureVisitor visitor(S.Context, owner.Variable);
5196 visitor.Visit(block->getBlockDecl()->getBody());
5197 return visitor.Capturer;
5198}
5199
5200static void diagnoseRetainCycle(Sema &S, Expr *capturer,
5201 RetainCycleOwner &owner) {
5202 assert(capturer);
5203 assert(owner.Variable && owner.Loc.isValid());
5204
5205 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
5206 << owner.Variable << capturer->getSourceRange();
5207 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
5208 << owner.Indirect << owner.Range;
5209}
5210
5211/// Check for a keyword selector that starts with the word 'add' or
5212/// 'set'.
5213static bool isSetterLikeSelector(Selector sel) {
5214 if (sel.isUnarySelector()) return false;
5215
Chris Lattner5f9e2722011-07-23 10:55:15 +00005216 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00005217 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00005218 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00005219 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00005220 else if (str.startswith("add")) {
5221 // Specially whitelist 'addOperationWithBlock:'.
5222 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
5223 return false;
5224 str = str.substr(3);
5225 }
John McCallf85e1932011-06-15 23:02:42 +00005226 else
5227 return false;
5228
5229 if (str.empty()) return true;
5230 return !islower(str.front());
5231}
5232
5233/// Check a message send to see if it's likely to cause a retain cycle.
5234void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
5235 // Only check instance methods whose selector looks like a setter.
5236 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
5237 return;
5238
5239 // Try to find a variable that the receiver is strongly owned by.
5240 RetainCycleOwner owner;
5241 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005242 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00005243 return;
5244 } else {
5245 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
5246 owner.Variable = getCurMethodDecl()->getSelfDecl();
5247 owner.Loc = msg->getSuperLoc();
5248 owner.Range = msg->getSuperLoc();
5249 }
5250
5251 // Check whether the receiver is captured by any of the arguments.
5252 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
5253 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
5254 return diagnoseRetainCycle(*this, capturer, owner);
5255}
5256
5257/// Check a property assign to see if it's likely to cause a retain cycle.
5258void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
5259 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005260 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00005261 return;
5262
5263 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
5264 diagnoseRetainCycle(*this, capturer, owner);
5265}
5266
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005267bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00005268 QualType LHS, Expr *RHS) {
5269 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
5270 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005271 return false;
5272 // strip off any implicit cast added to get to the one arc-specific
5273 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005274 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00005275 Diag(Loc, diag::warn_arc_retained_assign)
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00005276 << (LT == Qualifiers::OCL_ExplicitNone) << 1
John McCallf85e1932011-06-15 23:02:42 +00005277 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005278 return true;
5279 }
5280 RHS = cast->getSubExpr();
5281 }
5282 return false;
John McCallf85e1932011-06-15 23:02:42 +00005283}
5284
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005285void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
5286 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005287 QualType LHSType;
5288 // PropertyRef on LHS type need be directly obtained from
5289 // its declaration as it has a PsuedoType.
5290 ObjCPropertyRefExpr *PRE
5291 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
5292 if (PRE && !PRE->isImplicitProperty()) {
5293 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5294 if (PD)
5295 LHSType = PD->getType();
5296 }
5297
5298 if (LHSType.isNull())
5299 LHSType = LHS->getType();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005300 if (checkUnsafeAssigns(Loc, LHSType, RHS))
5301 return;
5302 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
5303 // FIXME. Check for other life times.
5304 if (LT != Qualifiers::OCL_None)
5305 return;
5306
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005307 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005308 if (PRE->isImplicitProperty())
5309 return;
5310 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5311 if (!PD)
5312 return;
5313
5314 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005315 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
5316 // when 'assign' attribute was not explicitly specified
5317 // by user, ignore it and rely on property type itself
5318 // for lifetime info.
5319 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
5320 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
5321 LHSType->isObjCRetainableType())
5322 return;
5323
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005324 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005325 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005326 Diag(Loc, diag::warn_arc_retained_property_assign)
5327 << RHS->getSourceRange();
5328 return;
5329 }
5330 RHS = cast->getSubExpr();
5331 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005332 }
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00005333 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
5334 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
5335 if (cast->getCastKind() == CK_ARCConsumeObject) {
5336 Diag(Loc, diag::warn_arc_retained_assign)
5337 << 0 << 0<< RHS->getSourceRange();
5338 return;
5339 }
5340 RHS = cast->getSubExpr();
5341 }
5342 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005343 }
5344}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00005345
5346//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
5347
5348namespace {
5349bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
5350 SourceLocation StmtLoc,
5351 const NullStmt *Body) {
5352 // Do not warn if the body is a macro that expands to nothing, e.g:
5353 //
5354 // #define CALL(x)
5355 // if (condition)
5356 // CALL(0);
5357 //
5358 if (Body->hasLeadingEmptyMacro())
5359 return false;
5360
5361 // Get line numbers of statement and body.
5362 bool StmtLineInvalid;
5363 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
5364 &StmtLineInvalid);
5365 if (StmtLineInvalid)
5366 return false;
5367
5368 bool BodyLineInvalid;
5369 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
5370 &BodyLineInvalid);
5371 if (BodyLineInvalid)
5372 return false;
5373
5374 // Warn if null statement and body are on the same line.
5375 if (StmtLine != BodyLine)
5376 return false;
5377
5378 return true;
5379}
5380} // Unnamed namespace
5381
5382void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
5383 const Stmt *Body,
5384 unsigned DiagID) {
5385 // Since this is a syntactic check, don't emit diagnostic for template
5386 // instantiations, this just adds noise.
5387 if (CurrentInstantiationScope)
5388 return;
5389
5390 // The body should be a null statement.
5391 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5392 if (!NBody)
5393 return;
5394
5395 // Do the usual checks.
5396 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5397 return;
5398
5399 Diag(NBody->getSemiLoc(), DiagID);
5400 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5401}
5402
5403void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
5404 const Stmt *PossibleBody) {
5405 assert(!CurrentInstantiationScope); // Ensured by caller
5406
5407 SourceLocation StmtLoc;
5408 const Stmt *Body;
5409 unsigned DiagID;
5410 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
5411 StmtLoc = FS->getRParenLoc();
5412 Body = FS->getBody();
5413 DiagID = diag::warn_empty_for_body;
5414 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
5415 StmtLoc = WS->getCond()->getSourceRange().getEnd();
5416 Body = WS->getBody();
5417 DiagID = diag::warn_empty_while_body;
5418 } else
5419 return; // Neither `for' nor `while'.
5420
5421 // The body should be a null statement.
5422 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5423 if (!NBody)
5424 return;
5425
5426 // Skip expensive checks if diagnostic is disabled.
5427 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
5428 DiagnosticsEngine::Ignored)
5429 return;
5430
5431 // Do the usual checks.
5432 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5433 return;
5434
5435 // `for(...);' and `while(...);' are popular idioms, so in order to keep
5436 // noise level low, emit diagnostics only if for/while is followed by a
5437 // CompoundStmt, e.g.:
5438 // for (int i = 0; i < n; i++);
5439 // {
5440 // a(i);
5441 // }
5442 // or if for/while is followed by a statement with more indentation
5443 // than for/while itself:
5444 // for (int i = 0; i < n; i++);
5445 // a(i);
5446 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
5447 if (!ProbableTypo) {
5448 bool BodyColInvalid;
5449 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
5450 PossibleBody->getLocStart(),
5451 &BodyColInvalid);
5452 if (BodyColInvalid)
5453 return;
5454
5455 bool StmtColInvalid;
5456 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
5457 S->getLocStart(),
5458 &StmtColInvalid);
5459 if (StmtColInvalid)
5460 return;
5461
5462 if (BodyCol > StmtCol)
5463 ProbableTypo = true;
5464 }
5465
5466 if (ProbableTypo) {
5467 Diag(NBody->getSemiLoc(), DiagID);
5468 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5469 }
5470}