blob: e818f5f3e07271731848e6417f311c4b29844277 [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"
John McCall781472f2010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
Ted Kremenek826a3452010-07-16 02:11:22 +000020#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000021#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000022#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000023#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
David Blaikiebe0ee872012-05-15 16:56:36 +000025#include "clang/AST/Expr.h"
Ted Kremenek23245122007-08-20 16:18:38 +000026#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000027#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000028#include "clang/AST/EvaluatedExprVisitor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000029#include "clang/AST/DeclObjC.h"
30#include "clang/AST/StmtCXX.h"
31#include "clang/AST/StmtObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000032#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000033#include "llvm/ADT/BitVector.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000034#include "llvm/ADT/SmallString.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000035#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000036#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000037#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000038#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000039#include "clang/Basic/ConvertUTF.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000040#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000041using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000042using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000043
Chris Lattner60800082009-02-18 17:49:48 +000044SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000046 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +000047 PP.getLangOpts(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000048}
49
John McCall8e10f3b2011-02-26 05:39:39 +000050/// Checks that a call expression's argument count is the desired number.
51/// This is useful when doing custom type-checking. Returns true on error.
52static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53 unsigned argCount = call->getNumArgs();
54 if (argCount == desiredArgCount) return false;
55
56 if (argCount < desiredArgCount)
57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58 << 0 /*function call*/ << desiredArgCount << argCount
59 << call->getSourceRange();
60
61 // Highlight all the excess arguments.
62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63 call->getArg(argCount - 1)->getLocEnd());
64
65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66 << 0 /*function call*/ << desiredArgCount << argCount
67 << call->getArg(1)->getSourceRange();
68}
69
Julien Lerougee5939212012-04-28 17:39:16 +000070/// Check that the first argument to __builtin_annotation is an integer
71/// and the second argument is a non-wide string literal.
72static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73 if (checkArgCount(S, TheCall, 2))
74 return true;
75
76 // First argument should be an integer.
77 Expr *ValArg = TheCall->getArg(0);
78 QualType Ty = ValArg->getType();
79 if (!Ty->isIntegerType()) {
80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81 << ValArg->getSourceRange();
Julien Lerouge77f68bb2011-09-09 22:41:49 +000082 return true;
83 }
Julien Lerougee5939212012-04-28 17:39:16 +000084
85 // Second argument should be a constant string.
86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88 if (!Literal || !Literal->isAscii()) {
89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90 << StrArg->getSourceRange();
91 return true;
92 }
93
94 TheCall->setType(Ty);
Julien Lerouge77f68bb2011-09-09 22:41:49 +000095 return false;
96}
97
John McCall60d7b3a2010-08-24 06:29:42 +000098ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +000099Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +0000100 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000101
Chris Lattner946928f2010-10-01 23:23:24 +0000102 // Find out if any arguments are required to be integer constant expressions.
103 unsigned ICEArguments = 0;
104 ASTContext::GetBuiltinTypeError Error;
105 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
106 if (Error != ASTContext::GE_None)
107 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
108
109 // If any arguments are required to be ICE's, check and diagnose.
110 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
111 // Skip arguments not required to be ICE's.
112 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
113
114 llvm::APSInt Result;
115 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
116 return true;
117 ICEArguments &= ~(1 << ArgNo);
118 }
119
Anders Carlssond406bf02009-08-16 01:56:34 +0000120 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000121 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000122 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000123 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000124 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000125 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000126 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000127 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000128 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000129 if (SemaBuiltinVAStart(TheCall))
130 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000131 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000132 case Builtin::BI__builtin_isgreater:
133 case Builtin::BI__builtin_isgreaterequal:
134 case Builtin::BI__builtin_isless:
135 case Builtin::BI__builtin_islessequal:
136 case Builtin::BI__builtin_islessgreater:
137 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000138 if (SemaBuiltinUnorderedCompare(TheCall))
139 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000140 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000141 case Builtin::BI__builtin_fpclassify:
142 if (SemaBuiltinFPClassification(TheCall, 6))
143 return ExprError();
144 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000145 case Builtin::BI__builtin_isfinite:
146 case Builtin::BI__builtin_isinf:
147 case Builtin::BI__builtin_isinf_sign:
148 case Builtin::BI__builtin_isnan:
149 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000150 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000151 return ExprError();
152 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000153 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000154 return SemaBuiltinShuffleVector(TheCall);
155 // TheCall will be freed by the smart pointer here, but that's fine, since
156 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000157 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000158 if (SemaBuiltinPrefetch(TheCall))
159 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000160 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000161 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000162 if (SemaBuiltinObjectSize(TheCall))
163 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000164 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000165 case Builtin::BI__builtin_longjmp:
166 if (SemaBuiltinLongjmp(TheCall))
167 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000168 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000169
170 case Builtin::BI__builtin_classify_type:
171 if (checkArgCount(*this, TheCall, 1)) return true;
172 TheCall->setType(Context.IntTy);
173 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000174 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000175 if (checkArgCount(*this, TheCall, 1)) return true;
176 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000177 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000178 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000179 case Builtin::BI__sync_fetch_and_add_1:
180 case Builtin::BI__sync_fetch_and_add_2:
181 case Builtin::BI__sync_fetch_and_add_4:
182 case Builtin::BI__sync_fetch_and_add_8:
183 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000184 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000185 case Builtin::BI__sync_fetch_and_sub_1:
186 case Builtin::BI__sync_fetch_and_sub_2:
187 case Builtin::BI__sync_fetch_and_sub_4:
188 case Builtin::BI__sync_fetch_and_sub_8:
189 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000190 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000191 case Builtin::BI__sync_fetch_and_or_1:
192 case Builtin::BI__sync_fetch_and_or_2:
193 case Builtin::BI__sync_fetch_and_or_4:
194 case Builtin::BI__sync_fetch_and_or_8:
195 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000196 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000197 case Builtin::BI__sync_fetch_and_and_1:
198 case Builtin::BI__sync_fetch_and_and_2:
199 case Builtin::BI__sync_fetch_and_and_4:
200 case Builtin::BI__sync_fetch_and_and_8:
201 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000202 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000203 case Builtin::BI__sync_fetch_and_xor_1:
204 case Builtin::BI__sync_fetch_and_xor_2:
205 case Builtin::BI__sync_fetch_and_xor_4:
206 case Builtin::BI__sync_fetch_and_xor_8:
207 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000208 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000209 case Builtin::BI__sync_add_and_fetch_1:
210 case Builtin::BI__sync_add_and_fetch_2:
211 case Builtin::BI__sync_add_and_fetch_4:
212 case Builtin::BI__sync_add_and_fetch_8:
213 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000214 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000215 case Builtin::BI__sync_sub_and_fetch_1:
216 case Builtin::BI__sync_sub_and_fetch_2:
217 case Builtin::BI__sync_sub_and_fetch_4:
218 case Builtin::BI__sync_sub_and_fetch_8:
219 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000220 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000221 case Builtin::BI__sync_and_and_fetch_1:
222 case Builtin::BI__sync_and_and_fetch_2:
223 case Builtin::BI__sync_and_and_fetch_4:
224 case Builtin::BI__sync_and_and_fetch_8:
225 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000226 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000227 case Builtin::BI__sync_or_and_fetch_1:
228 case Builtin::BI__sync_or_and_fetch_2:
229 case Builtin::BI__sync_or_and_fetch_4:
230 case Builtin::BI__sync_or_and_fetch_8:
231 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000232 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000233 case Builtin::BI__sync_xor_and_fetch_1:
234 case Builtin::BI__sync_xor_and_fetch_2:
235 case Builtin::BI__sync_xor_and_fetch_4:
236 case Builtin::BI__sync_xor_and_fetch_8:
237 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000238 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000239 case Builtin::BI__sync_val_compare_and_swap_1:
240 case Builtin::BI__sync_val_compare_and_swap_2:
241 case Builtin::BI__sync_val_compare_and_swap_4:
242 case Builtin::BI__sync_val_compare_and_swap_8:
243 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000244 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000245 case Builtin::BI__sync_bool_compare_and_swap_1:
246 case Builtin::BI__sync_bool_compare_and_swap_2:
247 case Builtin::BI__sync_bool_compare_and_swap_4:
248 case Builtin::BI__sync_bool_compare_and_swap_8:
249 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000250 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000251 case Builtin::BI__sync_lock_test_and_set_1:
252 case Builtin::BI__sync_lock_test_and_set_2:
253 case Builtin::BI__sync_lock_test_and_set_4:
254 case Builtin::BI__sync_lock_test_and_set_8:
255 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000256 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000257 case Builtin::BI__sync_lock_release_1:
258 case Builtin::BI__sync_lock_release_2:
259 case Builtin::BI__sync_lock_release_4:
260 case Builtin::BI__sync_lock_release_8:
261 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000262 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000263 case Builtin::BI__sync_swap_1:
264 case Builtin::BI__sync_swap_2:
265 case Builtin::BI__sync_swap_4:
266 case Builtin::BI__sync_swap_8:
267 case Builtin::BI__sync_swap_16:
Chandler Carruthd2014572010-07-09 18:59:35 +0000268 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Richard Smithff34d402012-04-12 05:08:17 +0000269#define BUILTIN(ID, TYPE, ATTRS)
270#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
271 case Builtin::BI##ID: \
272 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::AO##ID);
273#include "clang/Basic/Builtins.def"
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000274 case Builtin::BI__builtin_annotation:
Julien Lerougee5939212012-04-28 17:39:16 +0000275 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000276 return ExprError();
277 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000278 }
279
280 // Since the target specific builtins for each arch overlap, only check those
281 // of the arch we are compiling for.
282 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000283 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000284 case llvm::Triple::arm:
285 case llvm::Triple::thumb:
286 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
287 return ExprError();
288 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000289 default:
290 break;
291 }
292 }
293
294 return move(TheCallResult);
295}
296
Nate Begeman61eecf52010-06-14 05:21:25 +0000297// Get the valid immediate range for the specified NEON type code.
298static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000299 NeonTypeFlags Type(t);
300 int IsQuad = Type.isQuad();
301 switch (Type.getEltType()) {
302 case NeonTypeFlags::Int8:
303 case NeonTypeFlags::Poly8:
304 return shift ? 7 : (8 << IsQuad) - 1;
305 case NeonTypeFlags::Int16:
306 case NeonTypeFlags::Poly16:
307 return shift ? 15 : (4 << IsQuad) - 1;
308 case NeonTypeFlags::Int32:
309 return shift ? 31 : (2 << IsQuad) - 1;
310 case NeonTypeFlags::Int64:
311 return shift ? 63 : (1 << IsQuad) - 1;
312 case NeonTypeFlags::Float16:
313 assert(!shift && "cannot shift float types!");
314 return (4 << IsQuad) - 1;
315 case NeonTypeFlags::Float32:
316 assert(!shift && "cannot shift float types!");
317 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000318 }
David Blaikie7530c032012-01-17 06:56:22 +0000319 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000320}
321
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000322/// getNeonEltType - Return the QualType corresponding to the elements of
323/// the vector type specified by the NeonTypeFlags. This is used to check
324/// the pointer arguments for Neon load/store intrinsics.
325static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
326 switch (Flags.getEltType()) {
327 case NeonTypeFlags::Int8:
328 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
329 case NeonTypeFlags::Int16:
330 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
331 case NeonTypeFlags::Int32:
332 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
333 case NeonTypeFlags::Int64:
334 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
335 case NeonTypeFlags::Poly8:
336 return Context.SignedCharTy;
337 case NeonTypeFlags::Poly16:
338 return Context.ShortTy;
339 case NeonTypeFlags::Float16:
340 return Context.UnsignedShortTy;
341 case NeonTypeFlags::Float32:
342 return Context.FloatTy;
343 }
David Blaikie7530c032012-01-17 06:56:22 +0000344 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000345}
346
Nate Begeman26a31422010-06-08 02:47:44 +0000347bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000348 llvm::APSInt Result;
349
Nate Begeman0d15c532010-06-13 04:47:52 +0000350 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000351 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000352 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000353 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000354 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000355#define GET_NEON_OVERLOAD_CHECK
356#include "clang/Basic/arm_neon.inc"
357#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000358 }
359
Nate Begeman0d15c532010-06-13 04:47:52 +0000360 // For NEON intrinsics which are overloaded on vector element type, validate
361 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000362 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000363 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000364 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000365 return true;
366
Bob Wilsonda95f732011-11-08 01:16:11 +0000367 TV = Result.getLimitedValue(64);
368 if ((TV > 63) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000369 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000370 << TheCall->getArg(ImmArg)->getSourceRange();
371 }
372
Bob Wilson46482552011-11-16 21:32:23 +0000373 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000374 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000375 Expr *Arg = TheCall->getArg(PtrArgNum);
376 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
377 Arg = ICE->getSubExpr();
378 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
379 QualType RHSTy = RHS.get()->getType();
380 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
381 if (HasConstPtr)
382 EltTy = EltTy.withConst();
383 QualType LHSTy = Context.getPointerType(EltTy);
384 AssignConvertType ConvTy;
385 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
386 if (RHS.isInvalid())
387 return true;
388 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
389 RHS.get(), AA_Assigning))
390 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000391 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000392
Nate Begeman0d15c532010-06-13 04:47:52 +0000393 // For NEON intrinsics which take an immediate value as part of the
394 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000395 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000396 switch (BuiltinID) {
397 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000398 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
399 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000400 case ARM::BI__builtin_arm_vcvtr_f:
401 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000402#define GET_NEON_IMMEDIATE_CHECK
403#include "clang/Basic/arm_neon.inc"
404#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000405 };
406
Nate Begeman61eecf52010-06-14 05:21:25 +0000407 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000408 if (SemaBuiltinConstantArg(TheCall, i, Result))
409 return true;
410
Nate Begeman61eecf52010-06-14 05:21:25 +0000411 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000412 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000413 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000414 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000415 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000416
Nate Begeman99c40bb2010-08-03 21:32:34 +0000417 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000418 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000419}
Daniel Dunbarde454282008-10-02 18:44:07 +0000420
Anders Carlssond406bf02009-08-16 01:56:34 +0000421/// CheckFunctionCall - Check a direct function call for various correctness
422/// and safety properties not strictly enforced by the C type system.
423bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
424 // Get the IdentifierInfo* for the called function.
425 IdentifierInfo *FnInfo = FDecl->getIdentifier();
426
427 // None of the checks below are needed for functions that don't have
428 // simple names (e.g., C++ conversion functions).
429 if (!FnInfo)
430 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000431
Daniel Dunbarde454282008-10-02 18:44:07 +0000432 // FIXME: This mechanism should be abstracted to be less fragile and
433 // more efficient. For example, just map function ids to custom
434 // handlers.
435
Ted Kremenekc82faca2010-09-09 04:33:05 +0000436 // Printf and scanf checking.
437 for (specific_attr_iterator<FormatAttr>
438 i = FDecl->specific_attr_begin<FormatAttr>(),
439 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000440 CheckFormatArguments(*i, TheCall);
Chris Lattner59907c42007-08-10 20:18:51 +0000441 }
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Ted Kremenekc82faca2010-09-09 04:33:05 +0000443 for (specific_attr_iterator<NonNullAttr>
444 i = FDecl->specific_attr_begin<NonNullAttr>(),
445 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +0000446 CheckNonNullArguments(*i, TheCall->getArgs(),
447 TheCall->getCallee()->getLocStart());
Ted Kremenekc82faca2010-09-09 04:33:05 +0000448 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000449
Anna Zaks0a151a12012-01-17 00:37:07 +0000450 unsigned CMId = FDecl->getMemoryFunctionKind();
451 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000452 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000453
Anna Zaksd9b859a2012-01-13 21:52:01 +0000454 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000455 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000456 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000457 else if (CMId == Builtin::BIstrncat)
458 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000459 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000460 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000461
Anders Carlssond406bf02009-08-16 01:56:34 +0000462 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000463}
464
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000465bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
466 Expr **Args, unsigned NumArgs) {
467 for (specific_attr_iterator<FormatAttr>
468 i = Method->specific_attr_begin<FormatAttr>(),
469 e = Method->specific_attr_end<FormatAttr>(); i != e ; ++i) {
470
471 CheckFormatArguments(*i, Args, NumArgs, false, lbrac,
472 Method->getSourceRange());
473 }
474
475 // diagnose nonnull arguments.
476 for (specific_attr_iterator<NonNullAttr>
477 i = Method->specific_attr_begin<NonNullAttr>(),
478 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
479 CheckNonNullArguments(*i, Args, lbrac);
480 }
481
482 return false;
483}
484
Anders Carlssond406bf02009-08-16 01:56:34 +0000485bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000486 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
487 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000488 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000490 QualType Ty = V->getType();
491 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000492 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Jean-Daniel Dupas43d12512012-01-25 00:55:11 +0000494 // format string checking.
495 for (specific_attr_iterator<FormatAttr>
496 i = NDecl->specific_attr_begin<FormatAttr>(),
497 e = NDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
498 CheckFormatArguments(*i, TheCall);
499 }
Anders Carlssond406bf02009-08-16 01:56:34 +0000500
501 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000502}
503
Richard Smithff34d402012-04-12 05:08:17 +0000504ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
505 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000506 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
507 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000508
Richard Smithff34d402012-04-12 05:08:17 +0000509 // All these operations take one of the following forms:
510 enum {
511 // C __c11_atomic_init(A *, C)
512 Init,
513 // C __c11_atomic_load(A *, int)
514 Load,
515 // void __atomic_load(A *, CP, int)
516 Copy,
517 // C __c11_atomic_add(A *, M, int)
518 Arithmetic,
519 // C __atomic_exchange_n(A *, CP, int)
520 Xchg,
521 // void __atomic_exchange(A *, C *, CP, int)
522 GNUXchg,
523 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
524 C11CmpXchg,
525 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
526 GNUCmpXchg
527 } Form = Init;
528 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
529 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
530 // where:
531 // C is an appropriate type,
532 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
533 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
534 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
535 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000536
Richard Smithff34d402012-04-12 05:08:17 +0000537 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
538 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
539 && "need to update code for modified C11 atomics");
540 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
541 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
542 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
543 Op == AtomicExpr::AO__atomic_store_n ||
544 Op == AtomicExpr::AO__atomic_exchange_n ||
545 Op == AtomicExpr::AO__atomic_compare_exchange_n;
546 bool IsAddSub = false;
547
548 switch (Op) {
549 case AtomicExpr::AO__c11_atomic_init:
550 Form = Init;
551 break;
552
553 case AtomicExpr::AO__c11_atomic_load:
554 case AtomicExpr::AO__atomic_load_n:
555 Form = Load;
556 break;
557
558 case AtomicExpr::AO__c11_atomic_store:
559 case AtomicExpr::AO__atomic_load:
560 case AtomicExpr::AO__atomic_store:
561 case AtomicExpr::AO__atomic_store_n:
562 Form = Copy;
563 break;
564
565 case AtomicExpr::AO__c11_atomic_fetch_add:
566 case AtomicExpr::AO__c11_atomic_fetch_sub:
567 case AtomicExpr::AO__atomic_fetch_add:
568 case AtomicExpr::AO__atomic_fetch_sub:
569 case AtomicExpr::AO__atomic_add_fetch:
570 case AtomicExpr::AO__atomic_sub_fetch:
571 IsAddSub = true;
572 // Fall through.
573 case AtomicExpr::AO__c11_atomic_fetch_and:
574 case AtomicExpr::AO__c11_atomic_fetch_or:
575 case AtomicExpr::AO__c11_atomic_fetch_xor:
576 case AtomicExpr::AO__atomic_fetch_and:
577 case AtomicExpr::AO__atomic_fetch_or:
578 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000579 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000580 case AtomicExpr::AO__atomic_and_fetch:
581 case AtomicExpr::AO__atomic_or_fetch:
582 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000583 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000584 Form = Arithmetic;
585 break;
586
587 case AtomicExpr::AO__c11_atomic_exchange:
588 case AtomicExpr::AO__atomic_exchange_n:
589 Form = Xchg;
590 break;
591
592 case AtomicExpr::AO__atomic_exchange:
593 Form = GNUXchg;
594 break;
595
596 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
597 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
598 Form = C11CmpXchg;
599 break;
600
601 case AtomicExpr::AO__atomic_compare_exchange:
602 case AtomicExpr::AO__atomic_compare_exchange_n:
603 Form = GNUCmpXchg;
604 break;
605 }
606
607 // Check we have the right number of arguments.
608 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000609 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000610 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000611 << TheCall->getCallee()->getSourceRange();
612 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000613 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
614 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000615 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000616 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000617 << TheCall->getCallee()->getSourceRange();
618 return ExprError();
619 }
620
Richard Smithff34d402012-04-12 05:08:17 +0000621 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000622 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000623 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
624 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
625 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +0000626 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +0000627 << Ptr->getType() << Ptr->getSourceRange();
628 return ExprError();
629 }
630
Richard Smithff34d402012-04-12 05:08:17 +0000631 // For a __c11 builtin, this should be a pointer to an _Atomic type.
632 QualType AtomTy = pointerType->getPointeeType(); // 'A'
633 QualType ValType = AtomTy; // 'C'
634 if (IsC11) {
635 if (!AtomTy->isAtomicType()) {
636 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
637 << Ptr->getType() << Ptr->getSourceRange();
638 return ExprError();
639 }
640 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +0000641 }
Eli Friedman276b0612011-10-11 02:20:01 +0000642
Richard Smithff34d402012-04-12 05:08:17 +0000643 // For an arithmetic operation, the implied arithmetic must be well-formed.
644 if (Form == Arithmetic) {
645 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
646 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
647 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
648 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
649 return ExprError();
650 }
651 if (!IsAddSub && !ValType->isIntegerType()) {
652 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
653 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
654 return ExprError();
655 }
656 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
657 // For __atomic_*_n operations, the value type must be a scalar integral or
658 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +0000659 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +0000660 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
661 return ExprError();
662 }
663
664 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
665 // For GNU atomics, require a trivially-copyable type. This is not part of
666 // the GNU atomics specification, but we enforce it for sanity.
667 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +0000668 << Ptr->getType() << Ptr->getSourceRange();
669 return ExprError();
670 }
671
Richard Smithff34d402012-04-12 05:08:17 +0000672 // FIXME: For any builtin other than a load, the ValType must not be
673 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +0000674
675 switch (ValType.getObjCLifetime()) {
676 case Qualifiers::OCL_None:
677 case Qualifiers::OCL_ExplicitNone:
678 // okay
679 break;
680
681 case Qualifiers::OCL_Weak:
682 case Qualifiers::OCL_Strong:
683 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +0000684 // FIXME: Can this happen? By this point, ValType should be known
685 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +0000686 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
687 << ValType << Ptr->getSourceRange();
688 return ExprError();
689 }
690
691 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +0000692 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000693 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +0000694 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +0000695 ResultType = Context.BoolTy;
696
Richard Smithff34d402012-04-12 05:08:17 +0000697 // The type of a parameter passed 'by value'. In the GNU atomics, such
698 // arguments are actually passed as pointers.
699 QualType ByValType = ValType; // 'CP'
700 if (!IsC11 && !IsN)
701 ByValType = Ptr->getType();
702
Eli Friedman276b0612011-10-11 02:20:01 +0000703 // The first argument --- the pointer --- has a fixed type; we
704 // deduce the types of the rest of the arguments accordingly. Walk
705 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +0000706 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +0000707 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +0000708 if (i < NumVals[Form] + 1) {
709 switch (i) {
710 case 1:
711 // The second argument is the non-atomic operand. For arithmetic, this
712 // is always passed by value, and for a compare_exchange it is always
713 // passed by address. For the rest, GNU uses by-address and C11 uses
714 // by-value.
715 assert(Form != Load);
716 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
717 Ty = ValType;
718 else if (Form == Copy || Form == Xchg)
719 Ty = ByValType;
720 else if (Form == Arithmetic)
721 Ty = Context.getPointerDiffType();
722 else
723 Ty = Context.getPointerType(ValType.getUnqualifiedType());
724 break;
725 case 2:
726 // The third argument to compare_exchange / GNU exchange is a
727 // (pointer to a) desired value.
728 Ty = ByValType;
729 break;
730 case 3:
731 // The fourth argument to GNU compare_exchange is a 'weak' flag.
732 Ty = Context.BoolTy;
733 break;
734 }
Eli Friedman276b0612011-10-11 02:20:01 +0000735 } else {
736 // The order(s) are always converted to int.
737 Ty = Context.IntTy;
738 }
Richard Smithff34d402012-04-12 05:08:17 +0000739
Eli Friedman276b0612011-10-11 02:20:01 +0000740 InitializedEntity Entity =
741 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +0000742 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +0000743 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
744 if (Arg.isInvalid())
745 return true;
746 TheCall->setArg(i, Arg.get());
747 }
748
Richard Smithff34d402012-04-12 05:08:17 +0000749 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000750 SmallVector<Expr*, 5> SubExprs;
751 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +0000752 switch (Form) {
753 case Init:
754 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +0000755 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000756 break;
757 case Load:
758 SubExprs.push_back(TheCall->getArg(1)); // Order
759 break;
760 case Copy:
761 case Arithmetic:
762 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000763 SubExprs.push_back(TheCall->getArg(2)); // Order
764 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000765 break;
766 case GNUXchg:
767 // Note, AtomicExpr::getVal2() has a special case for this atomic.
768 SubExprs.push_back(TheCall->getArg(3)); // Order
769 SubExprs.push_back(TheCall->getArg(1)); // Val1
770 SubExprs.push_back(TheCall->getArg(2)); // Val2
771 break;
772 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000773 SubExprs.push_back(TheCall->getArg(3)); // Order
774 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000775 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +0000776 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +0000777 break;
778 case GNUCmpXchg:
779 SubExprs.push_back(TheCall->getArg(4)); // Order
780 SubExprs.push_back(TheCall->getArg(1)); // Val1
781 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
782 SubExprs.push_back(TheCall->getArg(2)); // Val2
783 SubExprs.push_back(TheCall->getArg(3)); // Weak
784 break;
Eli Friedman276b0612011-10-11 02:20:01 +0000785 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000786
787 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
788 SubExprs.data(), SubExprs.size(),
789 ResultType, Op,
790 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000791}
792
793
John McCall5f8d6042011-08-27 01:09:30 +0000794/// checkBuiltinArgument - Given a call to a builtin function, perform
795/// normal type-checking on the given argument, updating the call in
796/// place. This is useful when a builtin function requires custom
797/// type-checking for some of its arguments but not necessarily all of
798/// them.
799///
800/// Returns true on error.
801static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
802 FunctionDecl *Fn = E->getDirectCallee();
803 assert(Fn && "builtin call without direct callee!");
804
805 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
806 InitializedEntity Entity =
807 InitializedEntity::InitializeParameter(S.Context, Param);
808
809 ExprResult Arg = E->getArg(0);
810 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
811 if (Arg.isInvalid())
812 return true;
813
814 E->setArg(ArgIndex, Arg.take());
815 return false;
816}
817
Chris Lattner5caa3702009-05-08 06:58:22 +0000818/// SemaBuiltinAtomicOverloaded - We have a call to a function like
819/// __sync_fetch_and_add, which is an overloaded function based on the pointer
820/// type of its first argument. The main ActOnCallExpr routines have already
821/// promoted the types of arguments because all of these calls are prototyped as
822/// void(...).
823///
824/// This function goes through and does final semantic checking for these
825/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000826ExprResult
827Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000828 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000829 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
830 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
831
832 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000833 if (TheCall->getNumArgs() < 1) {
834 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
835 << 0 << 1 << TheCall->getNumArgs()
836 << TheCall->getCallee()->getSourceRange();
837 return ExprError();
838 }
Mike Stump1eb44332009-09-09 15:08:12 +0000839
Chris Lattner5caa3702009-05-08 06:58:22 +0000840 // Inspect the first argument of the atomic builtin. This should always be
841 // a pointer type, whose element is an integral scalar or pointer type.
842 // Because it is a pointer type, we don't have to worry about any implicit
843 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000844 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000845 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +0000846 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
847 if (FirstArgResult.isInvalid())
848 return ExprError();
849 FirstArg = FirstArgResult.take();
850 TheCall->setArg(0, FirstArg);
851
John McCallf85e1932011-06-15 23:02:42 +0000852 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
853 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000854 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
855 << FirstArg->getType() << FirstArg->getSourceRange();
856 return ExprError();
857 }
Mike Stump1eb44332009-09-09 15:08:12 +0000858
John McCallf85e1932011-06-15 23:02:42 +0000859 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000860 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000861 !ValType->isBlockPointerType()) {
862 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
863 << FirstArg->getType() << FirstArg->getSourceRange();
864 return ExprError();
865 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000866
John McCallf85e1932011-06-15 23:02:42 +0000867 switch (ValType.getObjCLifetime()) {
868 case Qualifiers::OCL_None:
869 case Qualifiers::OCL_ExplicitNone:
870 // okay
871 break;
872
873 case Qualifiers::OCL_Weak:
874 case Qualifiers::OCL_Strong:
875 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000876 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000877 << ValType << FirstArg->getSourceRange();
878 return ExprError();
879 }
880
John McCallb45ae252011-10-05 07:41:44 +0000881 // Strip any qualifiers off ValType.
882 ValType = ValType.getUnqualifiedType();
883
Chandler Carruth8d13d222010-07-18 20:54:12 +0000884 // The majority of builtins return a value, but a few have special return
885 // types, so allow them to override appropriately below.
886 QualType ResultType = ValType;
887
Chris Lattner5caa3702009-05-08 06:58:22 +0000888 // We need to figure out which concrete builtin this maps onto. For example,
889 // __sync_fetch_and_add with a 2 byte object turns into
890 // __sync_fetch_and_add_2.
891#define BUILTIN_ROW(x) \
892 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
893 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000894
Chris Lattner5caa3702009-05-08 06:58:22 +0000895 static const unsigned BuiltinIndices[][5] = {
896 BUILTIN_ROW(__sync_fetch_and_add),
897 BUILTIN_ROW(__sync_fetch_and_sub),
898 BUILTIN_ROW(__sync_fetch_and_or),
899 BUILTIN_ROW(__sync_fetch_and_and),
900 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000901
Chris Lattner5caa3702009-05-08 06:58:22 +0000902 BUILTIN_ROW(__sync_add_and_fetch),
903 BUILTIN_ROW(__sync_sub_and_fetch),
904 BUILTIN_ROW(__sync_and_and_fetch),
905 BUILTIN_ROW(__sync_or_and_fetch),
906 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000907
Chris Lattner5caa3702009-05-08 06:58:22 +0000908 BUILTIN_ROW(__sync_val_compare_and_swap),
909 BUILTIN_ROW(__sync_bool_compare_and_swap),
910 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000911 BUILTIN_ROW(__sync_lock_release),
912 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000913 };
Mike Stump1eb44332009-09-09 15:08:12 +0000914#undef BUILTIN_ROW
915
Chris Lattner5caa3702009-05-08 06:58:22 +0000916 // Determine the index of the size.
917 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000918 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000919 case 1: SizeIndex = 0; break;
920 case 2: SizeIndex = 1; break;
921 case 4: SizeIndex = 2; break;
922 case 8: SizeIndex = 3; break;
923 case 16: SizeIndex = 4; break;
924 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000925 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
926 << FirstArg->getType() << FirstArg->getSourceRange();
927 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000928 }
Mike Stump1eb44332009-09-09 15:08:12 +0000929
Chris Lattner5caa3702009-05-08 06:58:22 +0000930 // Each of these builtins has one pointer argument, followed by some number of
931 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
932 // that we ignore. Find out which row of BuiltinIndices to read from as well
933 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000934 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000935 unsigned BuiltinIndex, NumFixed = 1;
936 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000937 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +0000938 case Builtin::BI__sync_fetch_and_add:
939 case Builtin::BI__sync_fetch_and_add_1:
940 case Builtin::BI__sync_fetch_and_add_2:
941 case Builtin::BI__sync_fetch_and_add_4:
942 case Builtin::BI__sync_fetch_and_add_8:
943 case Builtin::BI__sync_fetch_and_add_16:
944 BuiltinIndex = 0;
945 break;
946
947 case Builtin::BI__sync_fetch_and_sub:
948 case Builtin::BI__sync_fetch_and_sub_1:
949 case Builtin::BI__sync_fetch_and_sub_2:
950 case Builtin::BI__sync_fetch_and_sub_4:
951 case Builtin::BI__sync_fetch_and_sub_8:
952 case Builtin::BI__sync_fetch_and_sub_16:
953 BuiltinIndex = 1;
954 break;
955
956 case Builtin::BI__sync_fetch_and_or:
957 case Builtin::BI__sync_fetch_and_or_1:
958 case Builtin::BI__sync_fetch_and_or_2:
959 case Builtin::BI__sync_fetch_and_or_4:
960 case Builtin::BI__sync_fetch_and_or_8:
961 case Builtin::BI__sync_fetch_and_or_16:
962 BuiltinIndex = 2;
963 break;
964
965 case Builtin::BI__sync_fetch_and_and:
966 case Builtin::BI__sync_fetch_and_and_1:
967 case Builtin::BI__sync_fetch_and_and_2:
968 case Builtin::BI__sync_fetch_and_and_4:
969 case Builtin::BI__sync_fetch_and_and_8:
970 case Builtin::BI__sync_fetch_and_and_16:
971 BuiltinIndex = 3;
972 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000973
Douglas Gregora9766412011-11-28 16:30:08 +0000974 case Builtin::BI__sync_fetch_and_xor:
975 case Builtin::BI__sync_fetch_and_xor_1:
976 case Builtin::BI__sync_fetch_and_xor_2:
977 case Builtin::BI__sync_fetch_and_xor_4:
978 case Builtin::BI__sync_fetch_and_xor_8:
979 case Builtin::BI__sync_fetch_and_xor_16:
980 BuiltinIndex = 4;
981 break;
982
983 case Builtin::BI__sync_add_and_fetch:
984 case Builtin::BI__sync_add_and_fetch_1:
985 case Builtin::BI__sync_add_and_fetch_2:
986 case Builtin::BI__sync_add_and_fetch_4:
987 case Builtin::BI__sync_add_and_fetch_8:
988 case Builtin::BI__sync_add_and_fetch_16:
989 BuiltinIndex = 5;
990 break;
991
992 case Builtin::BI__sync_sub_and_fetch:
993 case Builtin::BI__sync_sub_and_fetch_1:
994 case Builtin::BI__sync_sub_and_fetch_2:
995 case Builtin::BI__sync_sub_and_fetch_4:
996 case Builtin::BI__sync_sub_and_fetch_8:
997 case Builtin::BI__sync_sub_and_fetch_16:
998 BuiltinIndex = 6;
999 break;
1000
1001 case Builtin::BI__sync_and_and_fetch:
1002 case Builtin::BI__sync_and_and_fetch_1:
1003 case Builtin::BI__sync_and_and_fetch_2:
1004 case Builtin::BI__sync_and_and_fetch_4:
1005 case Builtin::BI__sync_and_and_fetch_8:
1006 case Builtin::BI__sync_and_and_fetch_16:
1007 BuiltinIndex = 7;
1008 break;
1009
1010 case Builtin::BI__sync_or_and_fetch:
1011 case Builtin::BI__sync_or_and_fetch_1:
1012 case Builtin::BI__sync_or_and_fetch_2:
1013 case Builtin::BI__sync_or_and_fetch_4:
1014 case Builtin::BI__sync_or_and_fetch_8:
1015 case Builtin::BI__sync_or_and_fetch_16:
1016 BuiltinIndex = 8;
1017 break;
1018
1019 case Builtin::BI__sync_xor_and_fetch:
1020 case Builtin::BI__sync_xor_and_fetch_1:
1021 case Builtin::BI__sync_xor_and_fetch_2:
1022 case Builtin::BI__sync_xor_and_fetch_4:
1023 case Builtin::BI__sync_xor_and_fetch_8:
1024 case Builtin::BI__sync_xor_and_fetch_16:
1025 BuiltinIndex = 9;
1026 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Chris Lattner5caa3702009-05-08 06:58:22 +00001028 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001029 case Builtin::BI__sync_val_compare_and_swap_1:
1030 case Builtin::BI__sync_val_compare_and_swap_2:
1031 case Builtin::BI__sync_val_compare_and_swap_4:
1032 case Builtin::BI__sync_val_compare_and_swap_8:
1033 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001034 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001035 NumFixed = 2;
1036 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001037
Chris Lattner5caa3702009-05-08 06:58:22 +00001038 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001039 case Builtin::BI__sync_bool_compare_and_swap_1:
1040 case Builtin::BI__sync_bool_compare_and_swap_2:
1041 case Builtin::BI__sync_bool_compare_and_swap_4:
1042 case Builtin::BI__sync_bool_compare_and_swap_8:
1043 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001044 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001045 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001046 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001047 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001048
1049 case Builtin::BI__sync_lock_test_and_set:
1050 case Builtin::BI__sync_lock_test_and_set_1:
1051 case Builtin::BI__sync_lock_test_and_set_2:
1052 case Builtin::BI__sync_lock_test_and_set_4:
1053 case Builtin::BI__sync_lock_test_and_set_8:
1054 case Builtin::BI__sync_lock_test_and_set_16:
1055 BuiltinIndex = 12;
1056 break;
1057
Chris Lattner5caa3702009-05-08 06:58:22 +00001058 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001059 case Builtin::BI__sync_lock_release_1:
1060 case Builtin::BI__sync_lock_release_2:
1061 case Builtin::BI__sync_lock_release_4:
1062 case Builtin::BI__sync_lock_release_8:
1063 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001064 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001065 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001066 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001067 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001068
1069 case Builtin::BI__sync_swap:
1070 case Builtin::BI__sync_swap_1:
1071 case Builtin::BI__sync_swap_2:
1072 case Builtin::BI__sync_swap_4:
1073 case Builtin::BI__sync_swap_8:
1074 case Builtin::BI__sync_swap_16:
1075 BuiltinIndex = 14;
1076 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001077 }
Mike Stump1eb44332009-09-09 15:08:12 +00001078
Chris Lattner5caa3702009-05-08 06:58:22 +00001079 // Now that we know how many fixed arguments we expect, first check that we
1080 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001081 if (TheCall->getNumArgs() < 1+NumFixed) {
1082 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1083 << 0 << 1+NumFixed << TheCall->getNumArgs()
1084 << TheCall->getCallee()->getSourceRange();
1085 return ExprError();
1086 }
Mike Stump1eb44332009-09-09 15:08:12 +00001087
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001088 // Get the decl for the concrete builtin from this, we can tell what the
1089 // concrete integer type we should convert to is.
1090 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1091 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
1092 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +00001093 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001094 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
1095 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +00001096
John McCallf871d0c2010-08-07 06:22:56 +00001097 // The first argument --- the pointer --- has a fixed type; we
1098 // deduce the types of the rest of the arguments accordingly. Walk
1099 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001100 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001101 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001102
Chris Lattner5caa3702009-05-08 06:58:22 +00001103 // GCC does an implicit conversion to the pointer or integer ValType. This
1104 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001105 // Initialize the argument.
1106 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1107 ValType, /*consume*/ false);
1108 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001109 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001110 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001111
Chris Lattner5caa3702009-05-08 06:58:22 +00001112 // Okay, we have something that *can* be converted to the right type. Check
1113 // to see if there is a potentially weird extension going on here. This can
1114 // happen when you do an atomic operation on something like an char* and
1115 // pass in 42. The 42 gets converted to char. This is even more strange
1116 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001117 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001118 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001119 }
Mike Stump1eb44332009-09-09 15:08:12 +00001120
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001121 ASTContext& Context = this->getASTContext();
1122
1123 // Create a new DeclRefExpr to refer to the new decl.
1124 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1125 Context,
1126 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001127 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001128 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001129 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001130 DRE->getLocation(),
1131 NewBuiltinDecl->getType(),
1132 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001133
Chris Lattner5caa3702009-05-08 06:58:22 +00001134 // Set the callee in the CallExpr.
1135 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001136 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley429bb272011-04-08 18:41:53 +00001137 if (PromotedCall.isInvalid())
1138 return ExprError();
1139 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001140
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001141 // Change the result type of the call to match the original value type. This
1142 // is arbitrary, but the codegen for these builtins ins design to handle it
1143 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001144 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001145
1146 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +00001147}
1148
Chris Lattner69039812009-02-18 06:01:06 +00001149/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001150/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001151/// Note: It might also make sense to do the UTF-16 conversion here (would
1152/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001153bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001154 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001155 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1156
Douglas Gregor5cee1192011-07-27 05:40:30 +00001157 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001158 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1159 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001160 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001161 }
Mike Stump1eb44332009-09-09 15:08:12 +00001162
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001163 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001164 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001165 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001166 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001167 const UTF8 *FromPtr = (UTF8 *)String.data();
1168 UTF16 *ToPtr = &ToBuf[0];
1169
1170 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1171 &ToPtr, ToPtr + NumBytes,
1172 strictConversion);
1173 // Check for conversion failure.
1174 if (Result != conversionOK)
1175 Diag(Arg->getLocStart(),
1176 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1177 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001178 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001179}
1180
Chris Lattnerc27c6652007-12-20 00:05:45 +00001181/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1182/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001183bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1184 Expr *Fn = TheCall->getCallee();
1185 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001186 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001187 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001188 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1189 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001190 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001191 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001192 return true;
1193 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001194
1195 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001196 return Diag(TheCall->getLocEnd(),
1197 diag::err_typecheck_call_too_few_args_at_least)
1198 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001199 }
1200
John McCall5f8d6042011-08-27 01:09:30 +00001201 // Type-check the first argument normally.
1202 if (checkBuiltinArgument(*this, TheCall, 0))
1203 return true;
1204
Chris Lattnerc27c6652007-12-20 00:05:45 +00001205 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001206 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001207 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001208 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001209 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001210 else if (FunctionDecl *FD = getCurFunctionDecl())
1211 isVariadic = FD->isVariadic();
1212 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001213 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001214
Chris Lattnerc27c6652007-12-20 00:05:45 +00001215 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001216 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1217 return true;
1218 }
Mike Stump1eb44332009-09-09 15:08:12 +00001219
Chris Lattner30ce3442007-12-19 23:59:04 +00001220 // Verify that the second argument to the builtin is the last argument of the
1221 // current function or method.
1222 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001223 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Anders Carlsson88cf2262008-02-11 04:20:54 +00001225 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1226 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001227 // FIXME: This isn't correct for methods (results in bogus warning).
1228 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001229 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001230 if (CurBlock)
1231 LastArg = *(CurBlock->TheDecl->param_end()-1);
1232 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001233 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001234 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001235 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001236 SecondArgIsLastNamedArgument = PV == LastArg;
1237 }
1238 }
Mike Stump1eb44332009-09-09 15:08:12 +00001239
Chris Lattner30ce3442007-12-19 23:59:04 +00001240 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001241 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001242 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1243 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001244}
Chris Lattner30ce3442007-12-19 23:59:04 +00001245
Chris Lattner1b9a0792007-12-20 00:26:33 +00001246/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1247/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001248bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1249 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001250 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001251 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001252 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001253 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001254 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001255 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001256 << SourceRange(TheCall->getArg(2)->getLocStart(),
1257 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001258
John Wiegley429bb272011-04-08 18:41:53 +00001259 ExprResult OrigArg0 = TheCall->getArg(0);
1260 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001261
Chris Lattner1b9a0792007-12-20 00:26:33 +00001262 // Do standard promotions between the two arguments, returning their common
1263 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001264 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001265 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1266 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001267
1268 // Make sure any conversions are pushed back into the call; this is
1269 // type safe since unordered compare builtins are declared as "_Bool
1270 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001271 TheCall->setArg(0, OrigArg0.get());
1272 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001273
John Wiegley429bb272011-04-08 18:41:53 +00001274 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001275 return false;
1276
Chris Lattner1b9a0792007-12-20 00:26:33 +00001277 // If the common type isn't a real floating type, then the arguments were
1278 // invalid for this operation.
1279 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001280 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001281 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001282 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1283 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001284
Chris Lattner1b9a0792007-12-20 00:26:33 +00001285 return false;
1286}
1287
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001288/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1289/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001290/// to check everything. We expect the last argument to be a floating point
1291/// value.
1292bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1293 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001294 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001295 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001296 if (TheCall->getNumArgs() > NumArgs)
1297 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001298 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001299 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001300 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001301 (*(TheCall->arg_end()-1))->getLocEnd());
1302
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001303 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001304
Eli Friedman9ac6f622009-08-31 20:06:00 +00001305 if (OrigArg->isTypeDependent())
1306 return false;
1307
Chris Lattner81368fb2010-05-06 05:50:07 +00001308 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001309 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001310 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001311 diag::err_typecheck_call_invalid_unary_fp)
1312 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001313
Chris Lattner81368fb2010-05-06 05:50:07 +00001314 // If this is an implicit conversion from float -> double, remove it.
1315 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1316 Expr *CastArg = Cast->getSubExpr();
1317 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1318 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1319 "promotion from float to double is the only expected cast here");
1320 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001321 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001322 }
1323 }
1324
Eli Friedman9ac6f622009-08-31 20:06:00 +00001325 return false;
1326}
1327
Eli Friedmand38617c2008-05-14 19:38:39 +00001328/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1329// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001330ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001331 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001332 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001333 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001334 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001335 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001336
Nate Begeman37b6a572010-06-08 00:16:34 +00001337 // Determine which of the following types of shufflevector we're checking:
1338 // 1) unary, vector mask: (lhs, mask)
1339 // 2) binary, vector mask: (lhs, rhs, mask)
1340 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1341 QualType resType = TheCall->getArg(0)->getType();
1342 unsigned numElements = 0;
1343
Douglas Gregorcde01732009-05-19 22:10:17 +00001344 if (!TheCall->getArg(0)->isTypeDependent() &&
1345 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001346 QualType LHSType = TheCall->getArg(0)->getType();
1347 QualType RHSType = TheCall->getArg(1)->getType();
1348
1349 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001350 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001351 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001352 TheCall->getArg(1)->getLocEnd());
1353 return ExprError();
1354 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001355
1356 numElements = LHSType->getAs<VectorType>()->getNumElements();
1357 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001358
Nate Begeman37b6a572010-06-08 00:16:34 +00001359 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1360 // with mask. If so, verify that RHS is an integer vector type with the
1361 // same number of elts as lhs.
1362 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001363 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001364 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1365 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1366 << SourceRange(TheCall->getArg(1)->getLocStart(),
1367 TheCall->getArg(1)->getLocEnd());
1368 numResElements = numElements;
1369 }
1370 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001371 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001372 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001373 TheCall->getArg(1)->getLocEnd());
1374 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001375 } else if (numElements != numResElements) {
1376 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001377 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001378 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001379 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001380 }
1381
1382 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001383 if (TheCall->getArg(i)->isTypeDependent() ||
1384 TheCall->getArg(i)->isValueDependent())
1385 continue;
1386
Nate Begeman37b6a572010-06-08 00:16:34 +00001387 llvm::APSInt Result(32);
1388 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1389 return ExprError(Diag(TheCall->getLocStart(),
1390 diag::err_shufflevector_nonconstant_argument)
1391 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001392
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001393 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001394 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001395 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001396 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001397 }
1398
Chris Lattner5f9e2722011-07-23 10:55:15 +00001399 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001400
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001401 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001402 exprs.push_back(TheCall->getArg(i));
1403 TheCall->setArg(i, 0);
1404 }
1405
Nate Begemana88dc302009-08-12 02:10:25 +00001406 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +00001407 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001408 TheCall->getCallee()->getLocStart(),
1409 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001410}
Chris Lattner30ce3442007-12-19 23:59:04 +00001411
Daniel Dunbar4493f792008-07-21 22:59:13 +00001412/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1413// This is declared to take (const void*, ...) and can take two
1414// optional constant int args.
1415bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001416 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001417
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001418 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001419 return Diag(TheCall->getLocEnd(),
1420 diag::err_typecheck_call_too_many_args_at_most)
1421 << 0 /*function call*/ << 3 << NumArgs
1422 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001423
1424 // Argument 0 is checked for us and the remaining arguments must be
1425 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001426 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001427 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +00001428
Eli Friedman9aef7262009-12-04 00:30:06 +00001429 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001430 if (SemaBuiltinConstantArg(TheCall, i, Result))
1431 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001432
Daniel Dunbar4493f792008-07-21 22:59:13 +00001433 // FIXME: gcc issues a warning and rewrites these to 0. These
1434 // seems especially odd for the third argument since the default
1435 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001436 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001437 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001438 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001439 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001440 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001441 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001442 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001443 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001444 }
1445 }
1446
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001447 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001448}
1449
Eric Christopher691ebc32010-04-17 02:26:23 +00001450/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1451/// TheCall is a constant expression.
1452bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1453 llvm::APSInt &Result) {
1454 Expr *Arg = TheCall->getArg(ArgNum);
1455 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1456 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1457
1458 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1459
1460 if (!Arg->isIntegerConstantExpr(Result, Context))
1461 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001462 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001463
Chris Lattner21fb98e2009-09-23 06:06:36 +00001464 return false;
1465}
1466
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001467/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1468/// int type). This simply type checks that type is one of the defined
1469/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001470// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001471bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001472 llvm::APSInt Result;
1473
1474 // Check constant-ness first.
1475 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1476 return true;
1477
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001478 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001479 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001480 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1481 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001482 }
1483
1484 return false;
1485}
1486
Eli Friedman586d6a82009-05-03 06:04:26 +00001487/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001488/// This checks that val is a constant 1.
1489bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1490 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001491 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001492
Eric Christopher691ebc32010-04-17 02:26:23 +00001493 // TODO: This is less than ideal. Overload this to take a value.
1494 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1495 return true;
1496
1497 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001498 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1499 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1500
1501 return false;
1502}
1503
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001504// Handle i > 1 ? "x" : "y", recursively.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001505bool Sema::SemaCheckStringLiteral(const Expr *E, Expr **Args,
1506 unsigned NumArgs, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001507 unsigned format_idx, unsigned firstDataArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001508 FormatStringType Type, bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001509 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001510 if (E->isTypeDependent() || E->isValueDependent())
1511 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001512
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001513 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001514
David Blaikiea73cdcb2012-02-10 21:07:25 +00001515 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1516 // Technically -Wformat-nonliteral does not warn about this case.
1517 // The behavior of printf and friends in this case is implementation
1518 // dependent. Ideally if the format string cannot be null then
1519 // it should have a 'nonnull' attribute in the function prototype.
1520 return true;
1521
Ted Kremenekd30ef872009-01-12 23:09:09 +00001522 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001523 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001524 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +00001525 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001526 return SemaCheckStringLiteral(C->getTrueExpr(), Args, NumArgs, HasVAListArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001527 format_idx, firstDataArg, Type,
Richard Trieu55733de2011-10-28 00:41:25 +00001528 inFunctionCall)
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001529 && SemaCheckStringLiteral(C->getFalseExpr(), Args, NumArgs, HasVAListArg,
1530 format_idx, firstDataArg, Type,
1531 inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001532 }
1533
1534 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001535 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1536 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001537 }
1538
John McCall56ca35d2011-02-17 10:25:35 +00001539 case Stmt::OpaqueValueExprClass:
1540 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1541 E = src;
1542 goto tryAgain;
1543 }
1544 return false;
1545
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001546 case Stmt::PredefinedExprClass:
1547 // While __func__, etc., are technically not string literals, they
1548 // cannot contain format specifiers and thus are not a security
1549 // liability.
1550 return true;
1551
Ted Kremenek082d9362009-03-20 21:35:28 +00001552 case Stmt::DeclRefExprClass: {
1553 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001554
Ted Kremenek082d9362009-03-20 21:35:28 +00001555 // As an exception, do not flag errors for variables binding to
1556 // const string literals.
1557 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1558 bool isConstant = false;
1559 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001560
Ted Kremenek082d9362009-03-20 21:35:28 +00001561 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1562 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001563 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001564 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001565 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001566 } else if (T->isObjCObjectPointerType()) {
1567 // In ObjC, there is usually no "const ObjectPointer" type,
1568 // so don't check if the pointee type is constant.
1569 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001570 }
Mike Stump1eb44332009-09-09 15:08:12 +00001571
Ted Kremenek082d9362009-03-20 21:35:28 +00001572 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001573 if (const Expr *Init = VD->getAnyInitializer()) {
1574 // Look through initializers like const char c[] = { "foo" }
1575 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
1576 if (InitList->isStringLiteralInit())
1577 Init = InitList->getInit(0)->IgnoreParenImpCasts();
1578 }
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001579 return SemaCheckStringLiteral(Init, Args, NumArgs,
Ted Kremenek826a3452010-07-16 02:11:22 +00001580 HasVAListArg, format_idx, firstDataArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001581 Type, /*inFunctionCall*/false);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001582 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001583 }
Mike Stump1eb44332009-09-09 15:08:12 +00001584
Anders Carlssond966a552009-06-28 19:55:58 +00001585 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1586 // special check to see if the format string is a function parameter
1587 // of the function calling the printf function. If the function
1588 // has an attribute indicating it is a printf-like function, then we
1589 // should suppress warnings concerning non-literals being used in a call
1590 // to a vprintf function. For example:
1591 //
1592 // void
1593 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1594 // va_list ap;
1595 // va_start(ap, fmt);
1596 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1597 // ...
1598 //
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001599 if (HasVAListArg) {
1600 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1601 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1602 int PVIndex = PV->getFunctionScopeIndex() + 1;
1603 for (specific_attr_iterator<FormatAttr>
1604 i = ND->specific_attr_begin<FormatAttr>(),
1605 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1606 FormatAttr *PVFormat = *i;
1607 // adjust for implicit parameter
1608 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1609 if (MD->isInstance())
1610 ++PVIndex;
1611 // We also check if the formats are compatible.
1612 // We can't pass a 'scanf' string to a 'printf' function.
1613 if (PVIndex == PVFormat->getFormatIdx() &&
1614 Type == GetFormatStringType(PVFormat))
1615 return true;
1616 }
1617 }
1618 }
1619 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001620 }
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Ted Kremenek082d9362009-03-20 21:35:28 +00001622 return false;
1623 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001624
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001625 case Stmt::CallExprClass:
1626 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001627 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001628 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1629 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1630 unsigned ArgIndex = FA->getFormatIdx();
1631 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1632 if (MD->isInstance())
1633 --ArgIndex;
1634 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001635
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001636 return SemaCheckStringLiteral(Arg, Args, NumArgs, HasVAListArg,
1637 format_idx, firstDataArg, Type,
1638 inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001639 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1640 unsigned BuiltinID = FD->getBuiltinID();
1641 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
1642 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
1643 const Expr *Arg = CE->getArg(0);
1644 return SemaCheckStringLiteral(Arg, Args, NumArgs, HasVAListArg,
1645 format_idx, firstDataArg, Type,
1646 inFunctionCall);
1647 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00001648 }
1649 }
Mike Stump1eb44332009-09-09 15:08:12 +00001650
Anders Carlsson8f031b32009-06-27 04:05:33 +00001651 return false;
1652 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001653 case Stmt::ObjCStringLiteralClass:
1654 case Stmt::StringLiteralClass: {
1655 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001656
Ted Kremenek082d9362009-03-20 21:35:28 +00001657 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001658 StrE = ObjCFExpr->getString();
1659 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001660 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Ted Kremenekd30ef872009-01-12 23:09:09 +00001662 if (StrE) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001663 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001664 firstDataArg, Type, inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001665 return true;
1666 }
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Ted Kremenekd30ef872009-01-12 23:09:09 +00001668 return false;
1669 }
Mike Stump1eb44332009-09-09 15:08:12 +00001670
Ted Kremenek082d9362009-03-20 21:35:28 +00001671 default:
1672 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001673 }
1674}
1675
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001676void
Mike Stump1eb44332009-09-09 15:08:12 +00001677Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001678 const Expr * const *ExprArgs,
1679 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001680 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1681 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001682 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001683 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001684 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001685 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001686 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001687 }
1688}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001689
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001690Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1691 return llvm::StringSwitch<FormatStringType>(Format->getType())
1692 .Case("scanf", FST_Scanf)
1693 .Cases("printf", "printf0", FST_Printf)
1694 .Cases("NSString", "CFString", FST_NSString)
1695 .Case("strftime", FST_Strftime)
1696 .Case("strfmon", FST_Strfmon)
1697 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1698 .Default(FST_Unknown);
1699}
1700
Ted Kremenek826a3452010-07-16 02:11:22 +00001701/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1702/// functions) for correct use of format strings.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001703void Sema::CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCall) {
1704 bool IsCXXMember = false;
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001705 // The way the format attribute works in GCC, the implicit this argument
1706 // of member functions is counted. However, it doesn't appear in our own
1707 // lists, so decrement format_idx in that case.
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001708 IsCXXMember = isa<CXXMemberCallExpr>(TheCall);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001709 CheckFormatArguments(Format, TheCall->getArgs(), TheCall->getNumArgs(),
1710 IsCXXMember, TheCall->getRParenLoc(),
1711 TheCall->getCallee()->getSourceRange());
1712}
1713
1714void Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
1715 unsigned NumArgs, bool IsCXXMember,
1716 SourceLocation Loc, SourceRange Range) {
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001717 bool HasVAListArg = Format->getFirstArg() == 0;
1718 unsigned format_idx = Format->getFormatIdx() - 1;
1719 unsigned firstDataArg = HasVAListArg ? 0 : Format->getFirstArg() - 1;
1720 if (IsCXXMember) {
1721 if (format_idx == 0)
1722 return;
1723 --format_idx;
1724 if(firstDataArg != 0)
1725 --firstDataArg;
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001726 }
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001727 CheckFormatArguments(Args, NumArgs, HasVAListArg, format_idx,
1728 firstDataArg, GetFormatStringType(Format), Loc, Range);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001729}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001730
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001731void Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
1732 bool HasVAListArg, unsigned format_idx,
1733 unsigned firstDataArg, FormatStringType Type,
1734 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001735 // CHECK: printf/scanf-like function is called with no format string.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001736 if (format_idx >= NumArgs) {
1737 Diag(Loc, diag::warn_missing_format_string) << Range;
Ted Kremenek71895b92007-08-14 17:39:48 +00001738 return;
1739 }
Mike Stump1eb44332009-09-09 15:08:12 +00001740
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001741 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001742
Chris Lattner59907c42007-08-10 20:18:51 +00001743 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001744 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001745 // Dynamically generated format strings are difficult to
1746 // automatically vet at compile time. Requiring that format strings
1747 // are string literals: (1) permits the checking of format strings by
1748 // the compiler and thereby (2) can practically remove the source of
1749 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001750
Mike Stump1eb44332009-09-09 15:08:12 +00001751 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001752 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001753 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001754 // the same format string checking logic for both ObjC and C strings.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001755 if (SemaCheckStringLiteral(OrigFormatExpr, Args, NumArgs, HasVAListArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001756 format_idx, firstDataArg, Type))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001757 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001758
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001759 // Strftime is particular as it always uses a single 'time' argument,
1760 // so it is safe to pass a non-literal string.
1761 if (Type == FST_Strftime)
1762 return;
1763
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001764 // Do not emit diag when the string param is a macro expansion and the
1765 // format is either NSString or CFString. This is a hack to prevent
1766 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1767 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00001768 if (Type == FST_NSString &&
1769 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001770 return;
1771
Chris Lattner655f1412009-04-29 04:59:47 +00001772 // If there are no arguments specified, warn with -Wformat-security, otherwise
1773 // warn only with -Wformat-nonliteral.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001774 if (NumArgs == format_idx+1)
1775 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001776 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001777 << OrigFormatExpr->getSourceRange();
1778 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001779 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001780 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001781 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001782}
Ted Kremenek71895b92007-08-14 17:39:48 +00001783
Ted Kremeneke0e53132010-01-28 23:39:18 +00001784namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001785class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1786protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001787 Sema &S;
1788 const StringLiteral *FExpr;
1789 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001790 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001791 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001792 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001793 const bool HasVAListArg;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001794 const Expr * const *Args;
1795 const unsigned NumArgs;
Ted Kremenek0d277352010-01-29 01:06:55 +00001796 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001797 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001798 bool usesPositionalArgs;
1799 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001800 bool inFunctionCall;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001801public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001802 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001803 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00001804 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001805 Expr **args, unsigned numArgs,
1806 unsigned formatIdx, bool inFunctionCall)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001807 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00001808 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
1809 Beg(beg), HasVAListArg(hasVAListArg),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001810 Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001811 usesPositionalArgs(false), atFirstArg(true),
1812 inFunctionCall(inFunctionCall) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001813 CoveredArgs.resize(numDataArgs);
1814 CoveredArgs.reset();
1815 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001816
Ted Kremenek07d161f2010-01-29 01:50:07 +00001817 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001818
Ted Kremenek826a3452010-07-16 02:11:22 +00001819 void HandleIncompleteSpecifier(const char *startSpecifier,
1820 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00001821
1822 void HandleNonStandardLengthModifier(
1823 const analyze_format_string::LengthModifier &LM,
1824 const char *startSpecifier, unsigned specifierLen);
1825
1826 void HandleNonStandardConversionSpecifier(
1827 const analyze_format_string::ConversionSpecifier &CS,
1828 const char *startSpecifier, unsigned specifierLen);
1829
1830 void HandleNonStandardConversionSpecification(
1831 const analyze_format_string::LengthModifier &LM,
1832 const analyze_format_string::ConversionSpecifier &CS,
1833 const char *startSpecifier, unsigned specifierLen);
1834
Hans Wennborgf8562642012-03-09 10:10:54 +00001835 virtual void HandlePosition(const char *startPos, unsigned posLen);
1836
Ted Kremenekefaff192010-02-27 01:41:03 +00001837 virtual void HandleInvalidPosition(const char *startSpecifier,
1838 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001839 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001840
1841 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1842
Ted Kremeneke0e53132010-01-28 23:39:18 +00001843 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001844
Richard Trieu55733de2011-10-28 00:41:25 +00001845 template <typename Range>
1846 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1847 const Expr *ArgumentExpr,
1848 PartialDiagnostic PDiag,
1849 SourceLocation StringLoc,
1850 bool IsStringLocation, Range StringRange,
1851 FixItHint Fixit = FixItHint());
1852
Ted Kremenek826a3452010-07-16 02:11:22 +00001853protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001854 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1855 const char *startSpec,
1856 unsigned specifierLen,
1857 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00001858
1859 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1860 const char *startSpec,
1861 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001862
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001863 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001864 CharSourceRange getSpecifierRange(const char *startSpecifier,
1865 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001866 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001867
Ted Kremenek0d277352010-01-29 01:06:55 +00001868 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001869
1870 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1871 const analyze_format_string::ConversionSpecifier &CS,
1872 const char *startSpecifier, unsigned specifierLen,
1873 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00001874
1875 template <typename Range>
1876 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1877 bool IsStringLocation, Range StringRange,
1878 FixItHint Fixit = FixItHint());
1879
1880 void CheckPositionalAndNonpositionalArgs(
1881 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001882};
1883}
1884
Ted Kremenek826a3452010-07-16 02:11:22 +00001885SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001886 return OrigFormatExpr->getSourceRange();
1887}
1888
Ted Kremenek826a3452010-07-16 02:11:22 +00001889CharSourceRange CheckFormatHandler::
1890getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001891 SourceLocation Start = getLocationOfByte(startSpecifier);
1892 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1893
1894 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001895 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00001896
1897 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001898}
1899
Ted Kremenek826a3452010-07-16 02:11:22 +00001900SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001901 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001902}
1903
Ted Kremenek826a3452010-07-16 02:11:22 +00001904void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1905 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00001906 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
1907 getLocationOfByte(startSpecifier),
1908 /*IsStringLocation*/true,
1909 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00001910}
1911
Hans Wennborg76517422012-02-22 10:17:01 +00001912void CheckFormatHandler::HandleNonStandardLengthModifier(
1913 const analyze_format_string::LengthModifier &LM,
1914 const char *startSpecifier, unsigned specifierLen) {
1915 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << LM.toString()
Hans Wennborgf8562642012-03-09 10:10:54 +00001916 << 0,
Hans Wennborg76517422012-02-22 10:17:01 +00001917 getLocationOfByte(LM.getStart()),
1918 /*IsStringLocation*/true,
1919 getSpecifierRange(startSpecifier, specifierLen));
1920}
1921
1922void CheckFormatHandler::HandleNonStandardConversionSpecifier(
1923 const analyze_format_string::ConversionSpecifier &CS,
1924 const char *startSpecifier, unsigned specifierLen) {
1925 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << CS.toString()
Hans Wennborgf8562642012-03-09 10:10:54 +00001926 << 1,
Hans Wennborg76517422012-02-22 10:17:01 +00001927 getLocationOfByte(CS.getStart()),
1928 /*IsStringLocation*/true,
1929 getSpecifierRange(startSpecifier, specifierLen));
1930}
1931
1932void CheckFormatHandler::HandleNonStandardConversionSpecification(
1933 const analyze_format_string::LengthModifier &LM,
1934 const analyze_format_string::ConversionSpecifier &CS,
1935 const char *startSpecifier, unsigned specifierLen) {
1936 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_conversion_spec)
1937 << LM.toString() << CS.toString(),
1938 getLocationOfByte(LM.getStart()),
1939 /*IsStringLocation*/true,
1940 getSpecifierRange(startSpecifier, specifierLen));
1941}
1942
Hans Wennborgf8562642012-03-09 10:10:54 +00001943void CheckFormatHandler::HandlePosition(const char *startPos,
1944 unsigned posLen) {
1945 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
1946 getLocationOfByte(startPos),
1947 /*IsStringLocation*/true,
1948 getSpecifierRange(startPos, posLen));
1949}
1950
Ted Kremenekefaff192010-02-27 01:41:03 +00001951void
Ted Kremenek826a3452010-07-16 02:11:22 +00001952CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1953 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00001954 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
1955 << (unsigned) p,
1956 getLocationOfByte(startPos), /*IsStringLocation*/true,
1957 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001958}
1959
Ted Kremenek826a3452010-07-16 02:11:22 +00001960void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001961 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00001962 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
1963 getLocationOfByte(startPos),
1964 /*IsStringLocation*/true,
1965 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001966}
1967
Ted Kremenek826a3452010-07-16 02:11:22 +00001968void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00001969 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001970 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00001971 EmitFormatDiagnostic(
1972 S.PDiag(diag::warn_printf_format_string_contains_null_char),
1973 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
1974 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00001975 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001976}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001977
Ted Kremenek826a3452010-07-16 02:11:22 +00001978const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001979 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00001980}
1981
1982void CheckFormatHandler::DoneProcessing() {
1983 // Does the number of data arguments exceed the number of
1984 // format conversions in the format string?
1985 if (!HasVAListArg) {
1986 // Find any arguments that weren't covered.
1987 CoveredArgs.flip();
1988 signed notCoveredArg = CoveredArgs.find_first();
1989 if (notCoveredArg >= 0) {
1990 assert((unsigned)notCoveredArg < NumDataArgs);
Bob Wilsonc03f2df2012-05-03 19:47:19 +00001991 SourceLocation Loc = getDataArg((unsigned) notCoveredArg)->getLocStart();
1992 if (!S.getSourceManager().isInSystemMacro(Loc)) {
1993 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
1994 Loc,
1995 /*IsStringLocation*/false, getFormatStringRange());
1996 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001997 }
1998 }
1999}
2000
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002001bool
2002CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2003 SourceLocation Loc,
2004 const char *startSpec,
2005 unsigned specifierLen,
2006 const char *csStart,
2007 unsigned csLen) {
2008
2009 bool keepGoing = true;
2010 if (argIndex < NumDataArgs) {
2011 // Consider the argument coverered, even though the specifier doesn't
2012 // make sense.
2013 CoveredArgs.set(argIndex);
2014 }
2015 else {
2016 // If argIndex exceeds the number of data arguments we
2017 // don't issue a warning because that is just a cascade of warnings (and
2018 // they may have intended '%%' anyway). We don't want to continue processing
2019 // the format string after this point, however, as we will like just get
2020 // gibberish when trying to match arguments.
2021 keepGoing = false;
2022 }
2023
Richard Trieu55733de2011-10-28 00:41:25 +00002024 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2025 << StringRef(csStart, csLen),
2026 Loc, /*IsStringLocation*/true,
2027 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002028
2029 return keepGoing;
2030}
2031
Richard Trieu55733de2011-10-28 00:41:25 +00002032void
2033CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2034 const char *startSpec,
2035 unsigned specifierLen) {
2036 EmitFormatDiagnostic(
2037 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2038 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2039}
2040
Ted Kremenek666a1972010-07-26 19:45:42 +00002041bool
2042CheckFormatHandler::CheckNumArgs(
2043 const analyze_format_string::FormatSpecifier &FS,
2044 const analyze_format_string::ConversionSpecifier &CS,
2045 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2046
2047 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002048 PartialDiagnostic PDiag = FS.usesPositionalArg()
2049 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2050 << (argIndex+1) << NumDataArgs)
2051 : S.PDiag(diag::warn_printf_insufficient_data_args);
2052 EmitFormatDiagnostic(
2053 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2054 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002055 return false;
2056 }
2057 return true;
2058}
2059
Richard Trieu55733de2011-10-28 00:41:25 +00002060template<typename Range>
2061void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2062 SourceLocation Loc,
2063 bool IsStringLocation,
2064 Range StringRange,
2065 FixItHint FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002066 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002067 Loc, IsStringLocation, StringRange, FixIt);
2068}
2069
2070/// \brief If the format string is not within the funcion call, emit a note
2071/// so that the function call and string are in diagnostic messages.
2072///
2073/// \param inFunctionCall if true, the format string is within the function
2074/// call and only one diagnostic message will be produced. Otherwise, an
2075/// extra note will be emitted pointing to location of the format string.
2076///
2077/// \param ArgumentExpr the expression that is passed as the format string
2078/// argument in the function call. Used for getting locations when two
2079/// diagnostics are emitted.
2080///
2081/// \param PDiag the callee should already have provided any strings for the
2082/// diagnostic message. This function only adds locations and fixits
2083/// to diagnostics.
2084///
2085/// \param Loc primary location for diagnostic. If two diagnostics are
2086/// required, one will be at Loc and a new SourceLocation will be created for
2087/// the other one.
2088///
2089/// \param IsStringLocation if true, Loc points to the format string should be
2090/// used for the note. Otherwise, Loc points to the argument list and will
2091/// be used with PDiag.
2092///
2093/// \param StringRange some or all of the string to highlight. This is
2094/// templated so it can accept either a CharSourceRange or a SourceRange.
2095///
2096/// \param Fixit optional fix it hint for the format string.
2097template<typename Range>
2098void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2099 const Expr *ArgumentExpr,
2100 PartialDiagnostic PDiag,
2101 SourceLocation Loc,
2102 bool IsStringLocation,
2103 Range StringRange,
2104 FixItHint FixIt) {
2105 if (InFunctionCall)
2106 S.Diag(Loc, PDiag) << StringRange << FixIt;
2107 else {
2108 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2109 << ArgumentExpr->getSourceRange();
2110 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2111 diag::note_format_string_defined)
2112 << StringRange << FixIt;
2113 }
2114}
2115
Ted Kremenek826a3452010-07-16 02:11:22 +00002116//===--- CHECK: Printf format string checking ------------------------------===//
2117
2118namespace {
2119class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002120 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002121public:
2122 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2123 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002124 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002125 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002126 Expr **Args, unsigned NumArgs,
2127 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00002128 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002129 numDataArgs, beg, hasVAListArg, Args, NumArgs,
2130 formatIdx, inFunctionCall), ObjCContext(isObjC) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002131
2132
2133 bool HandleInvalidPrintfConversionSpecifier(
2134 const analyze_printf::PrintfSpecifier &FS,
2135 const char *startSpecifier,
2136 unsigned specifierLen);
2137
2138 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2139 const char *startSpecifier,
2140 unsigned specifierLen);
2141
2142 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2143 const char *startSpecifier, unsigned specifierLen);
2144 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2145 const analyze_printf::OptionalAmount &Amt,
2146 unsigned type,
2147 const char *startSpecifier, unsigned specifierLen);
2148 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2149 const analyze_printf::OptionalFlag &flag,
2150 const char *startSpecifier, unsigned specifierLen);
2151 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2152 const analyze_printf::OptionalFlag &ignoredFlag,
2153 const analyze_printf::OptionalFlag &flag,
2154 const char *startSpecifier, unsigned specifierLen);
2155};
2156}
2157
2158bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2159 const analyze_printf::PrintfSpecifier &FS,
2160 const char *startSpecifier,
2161 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002162 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002163 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002164
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002165 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2166 getLocationOfByte(CS.getStart()),
2167 startSpecifier, specifierLen,
2168 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002169}
2170
Ted Kremenek826a3452010-07-16 02:11:22 +00002171bool CheckPrintfHandler::HandleAmount(
2172 const analyze_format_string::OptionalAmount &Amt,
2173 unsigned k, const char *startSpecifier,
2174 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002175
2176 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002177 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002178 unsigned argIndex = Amt.getArgIndex();
2179 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002180 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2181 << k,
2182 getLocationOfByte(Amt.getStart()),
2183 /*IsStringLocation*/true,
2184 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002185 // Don't do any more checking. We will just emit
2186 // spurious errors.
2187 return false;
2188 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002189
Ted Kremenek0d277352010-01-29 01:06:55 +00002190 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002191 // Although not in conformance with C99, we also allow the argument to be
2192 // an 'unsigned int' as that is a reasonably safe case. GCC also
2193 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002194 CoveredArgs.set(argIndex);
2195 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00002196 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002197
2198 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
2199 assert(ATR.isValid());
2200
2201 if (!ATR.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002202 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborga792aff2011-12-07 10:33:11 +00002203 << k << ATR.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002204 << T << Arg->getSourceRange(),
2205 getLocationOfByte(Amt.getStart()),
2206 /*IsStringLocation*/true,
2207 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002208 // Don't do any more checking. We will just emit
2209 // spurious errors.
2210 return false;
2211 }
2212 }
2213 }
2214 return true;
2215}
Ted Kremenek0d277352010-01-29 01:06:55 +00002216
Tom Caree4ee9662010-06-17 19:00:27 +00002217void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002218 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002219 const analyze_printf::OptionalAmount &Amt,
2220 unsigned type,
2221 const char *startSpecifier,
2222 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002223 const analyze_printf::PrintfConversionSpecifier &CS =
2224 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002225
Richard Trieu55733de2011-10-28 00:41:25 +00002226 FixItHint fixit =
2227 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2228 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2229 Amt.getConstantLength()))
2230 : FixItHint();
2231
2232 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2233 << type << CS.toString(),
2234 getLocationOfByte(Amt.getStart()),
2235 /*IsStringLocation*/true,
2236 getSpecifierRange(startSpecifier, specifierLen),
2237 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002238}
2239
Ted Kremenek826a3452010-07-16 02:11:22 +00002240void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002241 const analyze_printf::OptionalFlag &flag,
2242 const char *startSpecifier,
2243 unsigned specifierLen) {
2244 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002245 const analyze_printf::PrintfConversionSpecifier &CS =
2246 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002247 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2248 << flag.toString() << CS.toString(),
2249 getLocationOfByte(flag.getPosition()),
2250 /*IsStringLocation*/true,
2251 getSpecifierRange(startSpecifier, specifierLen),
2252 FixItHint::CreateRemoval(
2253 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002254}
2255
2256void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002257 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002258 const analyze_printf::OptionalFlag &ignoredFlag,
2259 const analyze_printf::OptionalFlag &flag,
2260 const char *startSpecifier,
2261 unsigned specifierLen) {
2262 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002263 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2264 << ignoredFlag.toString() << flag.toString(),
2265 getLocationOfByte(ignoredFlag.getPosition()),
2266 /*IsStringLocation*/true,
2267 getSpecifierRange(startSpecifier, specifierLen),
2268 FixItHint::CreateRemoval(
2269 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002270}
2271
Ted Kremeneke0e53132010-01-28 23:39:18 +00002272bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002273CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002274 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002275 const char *startSpecifier,
2276 unsigned specifierLen) {
2277
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002278 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002279 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002280 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002281
Ted Kremenekbaa40062010-07-19 22:01:06 +00002282 if (FS.consumesDataArgument()) {
2283 if (atFirstArg) {
2284 atFirstArg = false;
2285 usesPositionalArgs = FS.usesPositionalArg();
2286 }
2287 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002288 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2289 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002290 return false;
2291 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002292 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002293
Ted Kremenekefaff192010-02-27 01:41:03 +00002294 // First check if the field width, precision, and conversion specifier
2295 // have matching data arguments.
2296 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2297 startSpecifier, specifierLen)) {
2298 return false;
2299 }
2300
2301 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2302 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002303 return false;
2304 }
2305
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002306 if (!CS.consumesDataArgument()) {
2307 // FIXME: Technically specifying a precision or field width here
2308 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002309 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002310 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002311
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002312 // Consume the argument.
2313 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002314 if (argIndex < NumDataArgs) {
2315 // The check to see if the argIndex is valid will come later.
2316 // We set the bit here because we may exit early from this
2317 // function if we encounter some other error.
2318 CoveredArgs.set(argIndex);
2319 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002320
2321 // Check for using an Objective-C specific conversion specifier
2322 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002323 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002324 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2325 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002326 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002327
Tom Caree4ee9662010-06-17 19:00:27 +00002328 // Check for invalid use of field width
2329 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002330 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002331 startSpecifier, specifierLen);
2332 }
2333
2334 // Check for invalid use of precision
2335 if (!FS.hasValidPrecision()) {
2336 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2337 startSpecifier, specifierLen);
2338 }
2339
2340 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002341 if (!FS.hasValidThousandsGroupingPrefix())
2342 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002343 if (!FS.hasValidLeadingZeros())
2344 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2345 if (!FS.hasValidPlusPrefix())
2346 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002347 if (!FS.hasValidSpacePrefix())
2348 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002349 if (!FS.hasValidAlternativeForm())
2350 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2351 if (!FS.hasValidLeftJustified())
2352 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2353
2354 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002355 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2356 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2357 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002358 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2359 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2360 startSpecifier, specifierLen);
2361
2362 // Check the length modifier is valid with the given conversion specifier.
2363 const LengthModifier &LM = FS.getLengthModifier();
2364 if (!FS.hasValidLengthModifier())
Richard Trieu55733de2011-10-28 00:41:25 +00002365 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2366 << LM.toString() << CS.toString(),
2367 getLocationOfByte(LM.getStart()),
2368 /*IsStringLocation*/true,
2369 getSpecifierRange(startSpecifier, specifierLen),
2370 FixItHint::CreateRemoval(
2371 getSpecifierRange(LM.getStart(),
2372 LM.getLength())));
Hans Wennborg76517422012-02-22 10:17:01 +00002373 if (!FS.hasStandardLengthModifier())
2374 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
David Blaikie4e4d0842012-03-11 07:00:24 +00002375 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
Hans Wennborg76517422012-02-22 10:17:01 +00002376 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2377 if (!FS.hasStandardLengthConversionCombination())
2378 HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
2379 specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002380
2381 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00002382 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00002383 // Issue a warning about this being a possible security issue.
Richard Trieu55733de2011-10-28 00:41:25 +00002384 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
2385 getLocationOfByte(CS.getStart()),
2386 /*IsStringLocation*/true,
2387 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremeneke82d8042010-01-29 01:35:25 +00002388 // Continue checking the other format specifiers.
2389 return true;
2390 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002391
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002392 // The remaining checks depend on the data arguments.
2393 if (HasVAListArg)
2394 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002395
Ted Kremenek666a1972010-07-26 19:45:42 +00002396 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002397 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002398
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002399 // Now type check the data expression that matches the
2400 // format specifier.
2401 const Expr *Ex = getDataArg(argIndex);
Nico Weber339b9072012-01-31 01:43:25 +00002402 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context,
Jordan Rose50687312012-06-04 23:52:23 +00002403 ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002404 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
Jordan Roseee0259d2012-06-04 22:48:57 +00002405 // Look through argument promotions for our error message's reported type.
2406 // This includes the integral and floating promotions, but excludes array
2407 // and function pointer decay; seeing that an argument intended to be a
2408 // string has type 'char [6]' is probably more confusing than 'char *'.
2409 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex)) {
2410 if (ICE->getCastKind() == CK_IntegralCast ||
2411 ICE->getCastKind() == CK_FloatingCast) {
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002412 Ex = ICE->getSubExpr();
Jordan Roseee0259d2012-06-04 22:48:57 +00002413
2414 // Check if we didn't match because of an implicit cast from a 'char'
2415 // or 'short' to an 'int'. This is done because printf is a varargs
2416 // function.
2417 if (ICE->getType() == S.Context.IntTy ||
2418 ICE->getType() == S.Context.UnsignedIntTy) {
2419 // All further checking is done on the subexpression.
2420 if (ATR.matchesType(S.Context, Ex->getType()))
2421 return true;
2422 }
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002423 }
Jordan Roseee0259d2012-06-04 22:48:57 +00002424 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002425
2426 // We may be able to offer a FixItHint if it is a supported type.
2427 PrintfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00002428 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Jordan Rose50687312012-06-04 23:52:23 +00002429 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002430
2431 if (success) {
2432 // Get the fix string from the fixed format specifier
Jordan Roseee0259d2012-06-04 22:48:57 +00002433 SmallString<16> buf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002434 llvm::raw_svector_ostream os(buf);
2435 fixedFS.toString(os);
2436
Richard Trieu55733de2011-10-28 00:41:25 +00002437 EmitFormatDiagnostic(
2438 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborga792aff2011-12-07 10:33:11 +00002439 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Richard Trieu55733de2011-10-28 00:41:25 +00002440 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00002441 Ex->getLocStart(),
2442 /*IsStringLocation*/false,
Richard Trieu55733de2011-10-28 00:41:25 +00002443 getSpecifierRange(startSpecifier, specifierLen),
2444 FixItHint::CreateReplacement(
2445 getSpecifierRange(startSpecifier, specifierLen),
2446 os.str()));
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002447 }
2448 else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002449 EmitFormatDiagnostic(
2450 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2451 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2452 << getSpecifierRange(startSpecifier, specifierLen)
2453 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00002454 Ex->getLocStart(),
2455 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002456 getSpecifierRange(startSpecifier, specifierLen));
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002457 }
2458 }
2459
Ted Kremeneke0e53132010-01-28 23:39:18 +00002460 return true;
2461}
2462
Ted Kremenek826a3452010-07-16 02:11:22 +00002463//===--- CHECK: Scanf format string checking ------------------------------===//
2464
2465namespace {
2466class CheckScanfHandler : public CheckFormatHandler {
2467public:
2468 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2469 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002470 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002471 Expr **Args, unsigned NumArgs,
2472 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00002473 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002474 numDataArgs, beg, hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002475 Args, NumArgs, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002476
2477 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2478 const char *startSpecifier,
2479 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002480
2481 bool HandleInvalidScanfConversionSpecifier(
2482 const analyze_scanf::ScanfSpecifier &FS,
2483 const char *startSpecifier,
2484 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002485
2486 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002487};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002488}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002489
Ted Kremenekb7c21012010-07-16 18:28:03 +00002490void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2491 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002492 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2493 getLocationOfByte(end), /*IsStringLocation*/true,
2494 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002495}
2496
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002497bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2498 const analyze_scanf::ScanfSpecifier &FS,
2499 const char *startSpecifier,
2500 unsigned specifierLen) {
2501
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002502 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002503 FS.getConversionSpecifier();
2504
2505 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2506 getLocationOfByte(CS.getStart()),
2507 startSpecifier, specifierLen,
2508 CS.getStart(), CS.getLength());
2509}
2510
Ted Kremenek826a3452010-07-16 02:11:22 +00002511bool CheckScanfHandler::HandleScanfSpecifier(
2512 const analyze_scanf::ScanfSpecifier &FS,
2513 const char *startSpecifier,
2514 unsigned specifierLen) {
2515
2516 using namespace analyze_scanf;
2517 using namespace analyze_format_string;
2518
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002519 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002520
Ted Kremenekbaa40062010-07-19 22:01:06 +00002521 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2522 // be used to decide if we are using positional arguments consistently.
2523 if (FS.consumesDataArgument()) {
2524 if (atFirstArg) {
2525 atFirstArg = false;
2526 usesPositionalArgs = FS.usesPositionalArg();
2527 }
2528 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002529 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2530 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002531 return false;
2532 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002533 }
2534
2535 // Check if the field with is non-zero.
2536 const OptionalAmount &Amt = FS.getFieldWidth();
2537 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2538 if (Amt.getConstantAmount() == 0) {
2539 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2540 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00002541 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2542 getLocationOfByte(Amt.getStart()),
2543 /*IsStringLocation*/true, R,
2544 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00002545 }
2546 }
2547
2548 if (!FS.consumesDataArgument()) {
2549 // FIXME: Technically specifying a precision or field width here
2550 // makes no sense. Worth issuing a warning at some point.
2551 return true;
2552 }
2553
2554 // Consume the argument.
2555 unsigned argIndex = FS.getArgIndex();
2556 if (argIndex < NumDataArgs) {
2557 // The check to see if the argIndex is valid will come later.
2558 // We set the bit here because we may exit early from this
2559 // function if we encounter some other error.
2560 CoveredArgs.set(argIndex);
2561 }
2562
Ted Kremenek1e51c202010-07-20 20:04:47 +00002563 // Check the length modifier is valid with the given conversion specifier.
2564 const LengthModifier &LM = FS.getLengthModifier();
2565 if (!FS.hasValidLengthModifier()) {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002566 const CharSourceRange &R = getSpecifierRange(LM.getStart(), LM.getLength());
2567 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2568 << LM.toString() << CS.toString()
2569 << getSpecifierRange(startSpecifier, specifierLen),
2570 getLocationOfByte(LM.getStart()),
2571 /*IsStringLocation*/true, R,
2572 FixItHint::CreateRemoval(R));
Ted Kremenek1e51c202010-07-20 20:04:47 +00002573 }
2574
Hans Wennborg76517422012-02-22 10:17:01 +00002575 if (!FS.hasStandardLengthModifier())
2576 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
David Blaikie4e4d0842012-03-11 07:00:24 +00002577 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
Hans Wennborg76517422012-02-22 10:17:01 +00002578 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2579 if (!FS.hasStandardLengthConversionCombination())
2580 HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
2581 specifierLen);
2582
Ted Kremenek826a3452010-07-16 02:11:22 +00002583 // The remaining checks depend on the data arguments.
2584 if (HasVAListArg)
2585 return true;
2586
Ted Kremenek666a1972010-07-26 19:45:42 +00002587 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002588 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002589
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002590 // Check that the argument type matches the format specifier.
2591 const Expr *Ex = getDataArg(argIndex);
2592 const analyze_scanf::ScanfArgTypeResult &ATR = FS.getArgType(S.Context);
2593 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2594 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00002595 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00002596 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002597
2598 if (success) {
2599 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002600 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002601 llvm::raw_svector_ostream os(buf);
2602 fixedFS.toString(os);
2603
2604 EmitFormatDiagnostic(
2605 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2606 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2607 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00002608 Ex->getLocStart(),
2609 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002610 getSpecifierRange(startSpecifier, specifierLen),
2611 FixItHint::CreateReplacement(
2612 getSpecifierRange(startSpecifier, specifierLen),
2613 os.str()));
2614 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002615 EmitFormatDiagnostic(
2616 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002617 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002618 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00002619 Ex->getLocStart(),
2620 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002621 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002622 }
2623 }
2624
Ted Kremenek826a3452010-07-16 02:11:22 +00002625 return true;
2626}
2627
2628void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002629 const Expr *OrigFormatExpr,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002630 Expr **Args, unsigned NumArgs,
2631 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002632 unsigned firstDataArg, FormatStringType Type,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002633 bool inFunctionCall) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002634
Ted Kremeneke0e53132010-01-28 23:39:18 +00002635 // CHECK: is the format string a wide literal?
Douglas Gregor5cee1192011-07-27 05:40:30 +00002636 if (!FExpr->isAscii()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002637 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002638 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002639 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2640 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002641 return;
2642 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002643
Ted Kremeneke0e53132010-01-28 23:39:18 +00002644 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00002645 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002646 const char *Str = StrRef.data();
2647 unsigned StrLen = StrRef.size();
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002648 const unsigned numDataArgs = NumArgs - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00002649
Ted Kremeneke0e53132010-01-28 23:39:18 +00002650 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00002651 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00002652 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002653 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002654 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2655 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002656 return;
2657 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002658
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002659 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002660 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002661 numDataArgs, (Type == FST_NSString),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002662 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00002663 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002664
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002665 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
David Blaikie4e4d0842012-03-11 07:00:24 +00002666 getLangOpts()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002667 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002668 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00002669 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002670 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00002671 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002672
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002673 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
David Blaikie4e4d0842012-03-11 07:00:24 +00002674 getLangOpts()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002675 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002676 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00002677}
2678
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002679//===--- CHECK: Standard memory functions ---------------------------------===//
2680
Douglas Gregor2a053a32011-05-03 20:05:22 +00002681/// \brief Determine whether the given type is a dynamic class type (e.g.,
2682/// whether it has a vtable).
2683static bool isDynamicClassType(QualType T) {
2684 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2685 if (CXXRecordDecl *Definition = Record->getDefinition())
2686 if (Definition->isDynamicClass())
2687 return true;
2688
2689 return false;
2690}
2691
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002692/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00002693/// otherwise returns NULL.
2694static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00002695 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00002696 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2697 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2698 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002699
Chandler Carruth000d4282011-06-16 09:09:40 +00002700 return 0;
2701}
2702
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002703/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00002704static QualType getSizeOfArgType(const Expr* E) {
2705 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2706 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2707 if (SizeOf->getKind() == clang::UETT_SizeOf)
2708 return SizeOf->getTypeOfArgument();
2709
2710 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00002711}
2712
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002713/// \brief Check for dangerous or invalid arguments to memset().
2714///
Chandler Carruth929f0132011-06-03 06:23:57 +00002715/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002716/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2717/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002718///
2719/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002720void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00002721 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002722 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00002723 assert(BId != 0);
2724
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002725 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00002726 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00002727 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00002728 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002729 return;
2730
Anna Zaks0a151a12012-01-17 00:37:07 +00002731 unsigned LastArg = (BId == Builtin::BImemset ||
2732 BId == Builtin::BIstrndup ? 1 : 2);
2733 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00002734 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00002735
2736 // We have special checking when the length is a sizeof expression.
2737 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2738 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2739 llvm::FoldingSetNodeID SizeOfArgID;
2740
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002741 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2742 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002743 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002744
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002745 QualType DestTy = Dest->getType();
2746 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2747 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002748
Chandler Carruth000d4282011-06-16 09:09:40 +00002749 // Never warn about void type pointers. This can be used to suppress
2750 // false positives.
2751 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002752 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002753
Chandler Carruth000d4282011-06-16 09:09:40 +00002754 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2755 // actually comparing the expressions for equality. Because computing the
2756 // expression IDs can be expensive, we only do this if the diagnostic is
2757 // enabled.
2758 if (SizeOfArg &&
2759 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2760 SizeOfArg->getExprLoc())) {
2761 // We only compute IDs for expressions if the warning is enabled, and
2762 // cache the sizeof arg's ID.
2763 if (SizeOfArgID == llvm::FoldingSetNodeID())
2764 SizeOfArg->Profile(SizeOfArgID, Context, true);
2765 llvm::FoldingSetNodeID DestID;
2766 Dest->Profile(DestID, Context, true);
2767 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00002768 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2769 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00002770 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00002771 StringRef ReadableName = FnName->getName();
2772
Chandler Carruth000d4282011-06-16 09:09:40 +00002773 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00002774 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00002775 ActionIdx = 1; // If its an address-of operator, just remove it.
2776 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2777 ActionIdx = 2; // If the pointee's size is sizeof(char),
2778 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00002779
2780 // If the function is defined as a builtin macro, do not show macro
2781 // expansion.
2782 SourceLocation SL = SizeOfArg->getExprLoc();
2783 SourceRange DSR = Dest->getSourceRange();
2784 SourceRange SSR = SizeOfArg->getSourceRange();
2785 SourceManager &SM = PP.getSourceManager();
2786
2787 if (SM.isMacroArgExpansion(SL)) {
2788 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
2789 SL = SM.getSpellingLoc(SL);
2790 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
2791 SM.getSpellingLoc(DSR.getEnd()));
2792 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
2793 SM.getSpellingLoc(SSR.getEnd()));
2794 }
2795
Anna Zaks90c78322012-05-30 23:14:52 +00002796 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00002797 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00002798 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00002799 << PointeeTy
2800 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00002801 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00002802 << SSR);
2803 DiagRuntimeBehavior(SL, SizeOfArg,
2804 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
2805 << ActionIdx
2806 << SSR);
2807
Chandler Carruth000d4282011-06-16 09:09:40 +00002808 break;
2809 }
2810 }
2811
2812 // Also check for cases where the sizeof argument is the exact same
2813 // type as the memory argument, and where it points to a user-defined
2814 // record type.
2815 if (SizeOfArgTy != QualType()) {
2816 if (PointeeTy->isRecordType() &&
2817 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2818 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2819 PDiag(diag::warn_sizeof_pointer_type_memaccess)
2820 << FnName << SizeOfArgTy << ArgIdx
2821 << PointeeTy << Dest->getSourceRange()
2822 << LenExpr->getSourceRange());
2823 break;
2824 }
Nico Webere4a1c642011-06-14 16:14:58 +00002825 }
2826
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002827 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00002828 if (isDynamicClassType(PointeeTy)) {
2829
2830 unsigned OperationType = 0;
2831 // "overwritten" if we're warning about the destination for any call
2832 // but memcmp; otherwise a verb appropriate to the call.
2833 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
2834 if (BId == Builtin::BImemcpy)
2835 OperationType = 1;
2836 else if(BId == Builtin::BImemmove)
2837 OperationType = 2;
2838 else if (BId == Builtin::BImemcmp)
2839 OperationType = 3;
2840 }
2841
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002842 DiagRuntimeBehavior(
2843 Dest->getExprLoc(), Dest,
2844 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00002845 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00002846 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00002847 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002848 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00002849 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
2850 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002851 DiagRuntimeBehavior(
2852 Dest->getExprLoc(), Dest,
2853 PDiag(diag::warn_arc_object_memaccess)
2854 << ArgIdx << FnName << PointeeTy
2855 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00002856 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002857 continue;
John McCallf85e1932011-06-15 23:02:42 +00002858
2859 DiagRuntimeBehavior(
2860 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00002861 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002862 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2863 break;
2864 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002865 }
2866}
2867
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002868// A little helper routine: ignore addition and subtraction of integer literals.
2869// This intentionally does not ignore all integer constant expressions because
2870// we don't want to remove sizeof().
2871static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2872 Ex = Ex->IgnoreParenCasts();
2873
2874 for (;;) {
2875 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2876 if (!BO || !BO->isAdditiveOp())
2877 break;
2878
2879 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2880 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2881
2882 if (isa<IntegerLiteral>(RHS))
2883 Ex = LHS;
2884 else if (isa<IntegerLiteral>(LHS))
2885 Ex = RHS;
2886 else
2887 break;
2888 }
2889
2890 return Ex;
2891}
2892
2893// Warn if the user has made the 'size' argument to strlcpy or strlcat
2894// be the size of the source, instead of the destination.
2895void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2896 IdentifierInfo *FnName) {
2897
2898 // Don't crash if the user has the wrong number of arguments
2899 if (Call->getNumArgs() != 3)
2900 return;
2901
2902 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2903 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2904 const Expr *CompareWithSrc = NULL;
2905
2906 // Look for 'strlcpy(dst, x, sizeof(x))'
2907 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2908 CompareWithSrc = Ex;
2909 else {
2910 // Look for 'strlcpy(dst, x, strlen(x))'
2911 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00002912 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002913 && SizeCall->getNumArgs() == 1)
2914 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2915 }
2916 }
2917
2918 if (!CompareWithSrc)
2919 return;
2920
2921 // Determine if the argument to sizeof/strlen is equal to the source
2922 // argument. In principle there's all kinds of things you could do
2923 // here, for instance creating an == expression and evaluating it with
2924 // EvaluateAsBooleanCondition, but this uses a more direct technique:
2925 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2926 if (!SrcArgDRE)
2927 return;
2928
2929 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2930 if (!CompareWithSrcDRE ||
2931 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2932 return;
2933
2934 const Expr *OriginalSizeArg = Call->getArg(2);
2935 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2936 << OriginalSizeArg->getSourceRange() << FnName;
2937
2938 // Output a FIXIT hint if the destination is an array (rather than a
2939 // pointer to an array). This could be enhanced to handle some
2940 // pointers if we know the actual size, like if DstArg is 'array+2'
2941 // we could say 'sizeof(array)-2'.
2942 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek8f746222011-08-18 22:48:41 +00002943 QualType DstArgTy = DstArg->getType();
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002944
Ted Kremenek8f746222011-08-18 22:48:41 +00002945 // Only handle constant-sized or VLAs, but not flexible members.
2946 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2947 // Only issue the FIXIT for arrays of size > 1.
2948 if (CAT->getSize().getSExtValue() <= 1)
2949 return;
2950 } else if (!DstArgTy->isVariableArrayType()) {
2951 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002952 }
Ted Kremenek8f746222011-08-18 22:48:41 +00002953
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002954 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00002955 llvm::raw_svector_ostream OS(sizeString);
2956 OS << "sizeof(";
Douglas Gregor8987b232011-09-27 23:30:47 +00002957 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00002958 OS << ")";
2959
2960 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2961 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2962 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002963}
2964
Anna Zaksc36bedc2012-02-01 19:08:57 +00002965/// Check if two expressions refer to the same declaration.
2966static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
2967 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
2968 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
2969 return D1->getDecl() == D2->getDecl();
2970 return false;
2971}
2972
2973static const Expr *getStrlenExprArg(const Expr *E) {
2974 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
2975 const FunctionDecl *FD = CE->getDirectCallee();
2976 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
2977 return 0;
2978 return CE->getArg(0)->IgnoreParenCasts();
2979 }
2980 return 0;
2981}
2982
2983// Warn on anti-patterns as the 'size' argument to strncat.
2984// The correct size argument should look like following:
2985// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
2986void Sema::CheckStrncatArguments(const CallExpr *CE,
2987 IdentifierInfo *FnName) {
2988 // Don't crash if the user has the wrong number of arguments.
2989 if (CE->getNumArgs() < 3)
2990 return;
2991 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
2992 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
2993 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
2994
2995 // Identify common expressions, which are wrongly used as the size argument
2996 // to strncat and may lead to buffer overflows.
2997 unsigned PatternType = 0;
2998 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
2999 // - sizeof(dst)
3000 if (referToTheSameDecl(SizeOfArg, DstArg))
3001 PatternType = 1;
3002 // - sizeof(src)
3003 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3004 PatternType = 2;
3005 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3006 if (BE->getOpcode() == BO_Sub) {
3007 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3008 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3009 // - sizeof(dst) - strlen(dst)
3010 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3011 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3012 PatternType = 1;
3013 // - sizeof(src) - (anything)
3014 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3015 PatternType = 2;
3016 }
3017 }
3018
3019 if (PatternType == 0)
3020 return;
3021
Anna Zaksafdb0412012-02-03 01:27:37 +00003022 // Generate the diagnostic.
3023 SourceLocation SL = LenArg->getLocStart();
3024 SourceRange SR = LenArg->getSourceRange();
3025 SourceManager &SM = PP.getSourceManager();
3026
3027 // If the function is defined as a builtin macro, do not show macro expansion.
3028 if (SM.isMacroArgExpansion(SL)) {
3029 SL = SM.getSpellingLoc(SL);
3030 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3031 SM.getSpellingLoc(SR.getEnd()));
3032 }
3033
Anna Zaksc36bedc2012-02-01 19:08:57 +00003034 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003035 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003036 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003037 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003038
3039 // Output a FIXIT hint if the destination is an array (rather than a
3040 // pointer to an array). This could be enhanced to handle some
3041 // pointers if we know the actual size, like if DstArg is 'array+2'
3042 // we could say 'sizeof(array)-2'.
3043 QualType DstArgTy = DstArg->getType();
3044
3045 // Only handle constant-sized or VLAs, but not flexible members.
3046 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
3047 // Only issue the FIXIT for arrays of size > 1.
3048 if (CAT->getSize().getSExtValue() <= 1)
3049 return;
3050 } else if (!DstArgTy->isVariableArrayType()) {
3051 return;
3052 }
3053
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003054 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003055 llvm::raw_svector_ostream OS(sizeString);
3056 OS << "sizeof(";
3057 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
3058 OS << ") - ";
3059 OS << "strlen(";
3060 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
3061 OS << ") - 1";
3062
Anna Zaksafdb0412012-02-03 01:27:37 +00003063 Diag(SL, diag::note_strncat_wrong_size)
3064 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003065}
3066
Ted Kremenek06de2762007-08-17 16:46:58 +00003067//===--- CHECK: Return Address of Stack Variable --------------------------===//
3068
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003069static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3070 Decl *ParentDecl);
3071static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3072 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003073
3074/// CheckReturnStackAddr - Check if a return statement returns the address
3075/// of a stack variable.
3076void
3077Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3078 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003079
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003080 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003081 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003082
3083 // Perform checking for returned stack addresses, local blocks,
3084 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003085 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003086 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003087 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003088 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003089 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003090 }
3091
3092 if (stackE == 0)
3093 return; // Nothing suspicious was found.
3094
3095 SourceLocation diagLoc;
3096 SourceRange diagRange;
3097 if (refVars.empty()) {
3098 diagLoc = stackE->getLocStart();
3099 diagRange = stackE->getSourceRange();
3100 } else {
3101 // We followed through a reference variable. 'stackE' contains the
3102 // problematic expression but we will warn at the return statement pointing
3103 // at the reference variable. We will later display the "trail" of
3104 // reference variables using notes.
3105 diagLoc = refVars[0]->getLocStart();
3106 diagRange = refVars[0]->getSourceRange();
3107 }
3108
3109 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3110 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3111 : diag::warn_ret_stack_addr)
3112 << DR->getDecl()->getDeclName() << diagRange;
3113 } else if (isa<BlockExpr>(stackE)) { // local block.
3114 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3115 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3116 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3117 } else { // local temporary.
3118 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3119 : diag::warn_ret_local_temp_addr)
3120 << diagRange;
3121 }
3122
3123 // Display the "trail" of reference variables that we followed until we
3124 // found the problematic expression using notes.
3125 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3126 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3127 // If this var binds to another reference var, show the range of the next
3128 // var, otherwise the var binds to the problematic expression, in which case
3129 // show the range of the expression.
3130 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3131 : stackE->getSourceRange();
3132 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3133 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003134 }
3135}
3136
3137/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3138/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003139/// to a location on the stack, a local block, an address of a label, or a
3140/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003141/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003142/// encounter a subexpression that (1) clearly does not lead to one of the
3143/// above problematic expressions (2) is something we cannot determine leads to
3144/// a problematic expression based on such local checking.
3145///
3146/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3147/// the expression that they point to. Such variables are added to the
3148/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003149///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003150/// EvalAddr processes expressions that are pointers that are used as
3151/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003152/// At the base case of the recursion is a check for the above problematic
3153/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00003154///
3155/// This implementation handles:
3156///
3157/// * pointer-to-pointer casts
3158/// * implicit conversions from array references to pointers
3159/// * taking the address of fields
3160/// * arbitrary interplay between "&" and "*" operators
3161/// * pointer arithmetic from an address of a stack variable
3162/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003163static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3164 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003165 if (E->isTypeDependent())
3166 return NULL;
3167
Ted Kremenek06de2762007-08-17 16:46:58 +00003168 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00003169 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00003170 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003171 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003172 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00003173
Peter Collingbournef111d932011-04-15 00:35:48 +00003174 E = E->IgnoreParens();
3175
Ted Kremenek06de2762007-08-17 16:46:58 +00003176 // Our "symbolic interpreter" is just a dispatch off the currently
3177 // viewed AST node. We then recursively traverse the AST by calling
3178 // EvalAddr and EvalVal appropriately.
3179 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003180 case Stmt::DeclRefExprClass: {
3181 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3182
3183 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3184 // If this is a reference variable, follow through to the expression that
3185 // it points to.
3186 if (V->hasLocalStorage() &&
3187 V->getType()->isReferenceType() && V->hasInit()) {
3188 // Add the reference variable to the "trail".
3189 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003190 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003191 }
3192
3193 return NULL;
3194 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003195
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003196 case Stmt::UnaryOperatorClass: {
3197 // The only unary operator that make sense to handle here
3198 // is AddrOf. All others don't make sense as pointers.
3199 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003200
John McCall2de56d12010-08-25 11:45:40 +00003201 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003202 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003203 else
Ted Kremenek06de2762007-08-17 16:46:58 +00003204 return NULL;
3205 }
Mike Stump1eb44332009-09-09 15:08:12 +00003206
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003207 case Stmt::BinaryOperatorClass: {
3208 // Handle pointer arithmetic. All other binary operators are not valid
3209 // in this context.
3210 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00003211 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00003212
John McCall2de56d12010-08-25 11:45:40 +00003213 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003214 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00003215
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003216 Expr *Base = B->getLHS();
3217
3218 // Determine which argument is the real pointer base. It could be
3219 // the RHS argument instead of the LHS.
3220 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00003221
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003222 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003223 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003224 }
Steve Naroff61f40a22008-09-10 19:17:48 +00003225
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003226 // For conditional operators we need to see if either the LHS or RHS are
3227 // valid DeclRefExpr*s. If one of them is valid, we return it.
3228 case Stmt::ConditionalOperatorClass: {
3229 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003230
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003231 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003232 if (Expr *lhsExpr = C->getLHS()) {
3233 // In C++, we can have a throw-expression, which has 'void' type.
3234 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003235 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003236 return LHS;
3237 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003238
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003239 // In C++, we can have a throw-expression, which has 'void' type.
3240 if (C->getRHS()->getType()->isVoidType())
3241 return NULL;
3242
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003243 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003244 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003245
3246 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00003247 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003248 return E; // local block.
3249 return NULL;
3250
3251 case Stmt::AddrLabelExprClass:
3252 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00003253
John McCall80ee6e82011-11-10 05:35:25 +00003254 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003255 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
3256 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003257
Ted Kremenek54b52742008-08-07 00:49:01 +00003258 // For casts, we need to handle conversions from arrays to
3259 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00003260 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003261 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003262 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00003263 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00003264 case Stmt::CXXStaticCastExprClass:
3265 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00003266 case Stmt::CXXConstCastExprClass:
3267 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00003268 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3269 switch (cast<CastExpr>(E)->getCastKind()) {
3270 case CK_BitCast:
3271 case CK_LValueToRValue:
3272 case CK_NoOp:
3273 case CK_BaseToDerived:
3274 case CK_DerivedToBase:
3275 case CK_UncheckedDerivedToBase:
3276 case CK_Dynamic:
3277 case CK_CPointerToObjCPointerCast:
3278 case CK_BlockPointerToObjCPointerCast:
3279 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003280 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003281
3282 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003283 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003284
3285 default:
3286 return 0;
3287 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003288 }
Mike Stump1eb44332009-09-09 15:08:12 +00003289
Douglas Gregor03e80032011-06-21 17:03:29 +00003290 case Stmt::MaterializeTemporaryExprClass:
3291 if (Expr *Result = EvalAddr(
3292 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003293 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003294 return Result;
3295
3296 return E;
3297
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003298 // Everything else: we simply don't reason about them.
3299 default:
3300 return NULL;
3301 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003302}
Mike Stump1eb44332009-09-09 15:08:12 +00003303
Ted Kremenek06de2762007-08-17 16:46:58 +00003304
3305/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3306/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003307static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3308 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003309do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003310 // We should only be called for evaluating non-pointer expressions, or
3311 // expressions with a pointer type that are not used as references but instead
3312 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00003313
Ted Kremenek06de2762007-08-17 16:46:58 +00003314 // Our "symbolic interpreter" is just a dispatch off the currently
3315 // viewed AST node. We then recursively traverse the AST by calling
3316 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00003317
3318 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00003319 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003320 case Stmt::ImplicitCastExprClass: {
3321 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00003322 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003323 E = IE->getSubExpr();
3324 continue;
3325 }
3326 return NULL;
3327 }
3328
John McCall80ee6e82011-11-10 05:35:25 +00003329 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003330 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003331
Douglas Gregora2813ce2009-10-23 18:54:35 +00003332 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003333 // When we hit a DeclRefExpr we are looking at code that refers to a
3334 // variable's name. If it's not a reference variable we check if it has
3335 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00003336 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003337
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003338 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
3339 // Check if it refers to itself, e.g. "int& i = i;".
3340 if (V == ParentDecl)
3341 return DR;
3342
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003343 if (V->hasLocalStorage()) {
3344 if (!V->getType()->isReferenceType())
3345 return DR;
3346
3347 // Reference variable, follow through to the expression that
3348 // it points to.
3349 if (V->hasInit()) {
3350 // Add the reference variable to the "trail".
3351 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003352 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003353 }
3354 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003355 }
Mike Stump1eb44332009-09-09 15:08:12 +00003356
Ted Kremenek06de2762007-08-17 16:46:58 +00003357 return NULL;
3358 }
Mike Stump1eb44332009-09-09 15:08:12 +00003359
Ted Kremenek06de2762007-08-17 16:46:58 +00003360 case Stmt::UnaryOperatorClass: {
3361 // The only unary operator that make sense to handle here
3362 // is Deref. All others don't resolve to a "name." This includes
3363 // handling all sorts of rvalues passed to a unary operator.
3364 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003365
John McCall2de56d12010-08-25 11:45:40 +00003366 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003367 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003368
3369 return NULL;
3370 }
Mike Stump1eb44332009-09-09 15:08:12 +00003371
Ted Kremenek06de2762007-08-17 16:46:58 +00003372 case Stmt::ArraySubscriptExprClass: {
3373 // Array subscripts are potential references to data on the stack. We
3374 // retrieve the DeclRefExpr* for the array variable if it indeed
3375 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003376 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003377 }
Mike Stump1eb44332009-09-09 15:08:12 +00003378
Ted Kremenek06de2762007-08-17 16:46:58 +00003379 case Stmt::ConditionalOperatorClass: {
3380 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003381 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003382 ConditionalOperator *C = cast<ConditionalOperator>(E);
3383
Anders Carlsson39073232007-11-30 19:04:31 +00003384 // Handle the GNU extension for missing LHS.
3385 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003386 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00003387 return LHS;
3388
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003389 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003390 }
Mike Stump1eb44332009-09-09 15:08:12 +00003391
Ted Kremenek06de2762007-08-17 16:46:58 +00003392 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003393 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003394 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003395
Ted Kremenek06de2762007-08-17 16:46:58 +00003396 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003397 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003398 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003399
3400 // Check whether the member type is itself a reference, in which case
3401 // we're not going to refer to the member, but to what the member refers to.
3402 if (M->getMemberDecl()->getType()->isReferenceType())
3403 return NULL;
3404
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003405 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003406 }
Mike Stump1eb44332009-09-09 15:08:12 +00003407
Douglas Gregor03e80032011-06-21 17:03:29 +00003408 case Stmt::MaterializeTemporaryExprClass:
3409 if (Expr *Result = EvalVal(
3410 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003411 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003412 return Result;
3413
3414 return E;
3415
Ted Kremenek06de2762007-08-17 16:46:58 +00003416 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003417 // Check that we don't return or take the address of a reference to a
3418 // temporary. This is only useful in C++.
3419 if (!E->isTypeDependent() && E->isRValue())
3420 return E;
3421
3422 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003423 return NULL;
3424 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003425} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003426}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003427
3428//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3429
3430/// Check for comparisons of floating point operands using != and ==.
3431/// Issue a warning if these are no self-comparisons, as they are not likely
3432/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003433void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003434 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003435
Richard Trieudd225092011-09-15 21:56:47 +00003436 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3437 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003438
3439 // Special case: check for x == x (which is OK).
3440 // Do not emit warnings for such cases.
3441 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3442 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3443 if (DRL->getDecl() == DRR->getDecl())
3444 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003445
3446
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003447 // Special case: check for comparisons against literals that can be exactly
3448 // represented by APFloat. In such cases, do not emit a warning. This
3449 // is a heuristic: often comparison against such literals are used to
3450 // detect if a value in a variable has not changed. This clearly can
3451 // lead to false negatives.
3452 if (EmitWarning) {
3453 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3454 if (FLL->isExact())
3455 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003456 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003457 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
3458 if (FLR->isExact())
3459 EmitWarning = false;
3460 }
3461 }
Mike Stump1eb44332009-09-09 15:08:12 +00003462
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003463 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003464 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003465 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003466 if (CL->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003467 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003468
Sebastian Redl0eb23302009-01-19 00:08:26 +00003469 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003470 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003471 if (CR->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003472 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003473
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003474 // Emit the diagnostic.
3475 if (EmitWarning)
Richard Trieudd225092011-09-15 21:56:47 +00003476 Diag(Loc, diag::warn_floatingpoint_eq)
3477 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003478}
John McCallba26e582010-01-04 23:21:16 +00003479
John McCallf2370c92010-01-06 05:24:50 +00003480//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3481//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003482
John McCallf2370c92010-01-06 05:24:50 +00003483namespace {
John McCallba26e582010-01-04 23:21:16 +00003484
John McCallf2370c92010-01-06 05:24:50 +00003485/// Structure recording the 'active' range of an integer-valued
3486/// expression.
3487struct IntRange {
3488 /// The number of bits active in the int.
3489 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003490
John McCallf2370c92010-01-06 05:24:50 +00003491 /// True if the int is known not to have negative values.
3492 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003493
John McCallf2370c92010-01-06 05:24:50 +00003494 IntRange(unsigned Width, bool NonNegative)
3495 : Width(Width), NonNegative(NonNegative)
3496 {}
John McCallba26e582010-01-04 23:21:16 +00003497
John McCall1844a6e2010-11-10 23:38:19 +00003498 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00003499 static IntRange forBoolType() {
3500 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00003501 }
3502
John McCall1844a6e2010-11-10 23:38:19 +00003503 /// Returns the range of an opaque value of the given integral type.
3504 static IntRange forValueOfType(ASTContext &C, QualType T) {
3505 return forValueOfCanonicalType(C,
3506 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00003507 }
3508
John McCall1844a6e2010-11-10 23:38:19 +00003509 /// Returns the range of an opaque value of a canonical integral type.
3510 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00003511 assert(T->isCanonicalUnqualified());
3512
3513 if (const VectorType *VT = dyn_cast<VectorType>(T))
3514 T = VT->getElementType().getTypePtr();
3515 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3516 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00003517
John McCall091f23f2010-11-09 22:22:12 +00003518 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00003519 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3520 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00003521 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00003522 return IntRange(C.getIntWidth(QualType(T, 0)), false);
3523
John McCall323ed742010-05-06 08:58:33 +00003524 unsigned NumPositive = Enum->getNumPositiveBits();
3525 unsigned NumNegative = Enum->getNumNegativeBits();
3526
3527 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3528 }
John McCallf2370c92010-01-06 05:24:50 +00003529
3530 const BuiltinType *BT = cast<BuiltinType>(T);
3531 assert(BT->isInteger());
3532
3533 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3534 }
3535
John McCall1844a6e2010-11-10 23:38:19 +00003536 /// Returns the "target" range of a canonical integral type, i.e.
3537 /// the range of values expressible in the type.
3538 ///
3539 /// This matches forValueOfCanonicalType except that enums have the
3540 /// full range of their type, not the range of their enumerators.
3541 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3542 assert(T->isCanonicalUnqualified());
3543
3544 if (const VectorType *VT = dyn_cast<VectorType>(T))
3545 T = VT->getElementType().getTypePtr();
3546 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3547 T = CT->getElementType().getTypePtr();
3548 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00003549 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00003550
3551 const BuiltinType *BT = cast<BuiltinType>(T);
3552 assert(BT->isInteger());
3553
3554 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3555 }
3556
3557 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003558 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00003559 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00003560 L.NonNegative && R.NonNegative);
3561 }
3562
John McCall1844a6e2010-11-10 23:38:19 +00003563 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003564 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00003565 return IntRange(std::min(L.Width, R.Width),
3566 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00003567 }
3568};
3569
Ted Kremenek0692a192012-01-31 05:37:37 +00003570static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
3571 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003572 if (value.isSigned() && value.isNegative())
3573 return IntRange(value.getMinSignedBits(), false);
3574
3575 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003576 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003577
3578 // isNonNegative() just checks the sign bit without considering
3579 // signedness.
3580 return IntRange(value.getActiveBits(), true);
3581}
3582
Ted Kremenek0692a192012-01-31 05:37:37 +00003583static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
3584 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003585 if (result.isInt())
3586 return GetValueRange(C, result.getInt(), MaxWidth);
3587
3588 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00003589 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3590 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3591 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3592 R = IntRange::join(R, El);
3593 }
John McCallf2370c92010-01-06 05:24:50 +00003594 return R;
3595 }
3596
3597 if (result.isComplexInt()) {
3598 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3599 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3600 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00003601 }
3602
3603 // This can happen with lossless casts to intptr_t of "based" lvalues.
3604 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00003605 // FIXME: The only reason we need to pass the type in here is to get
3606 // the sign right on this one case. It would be nice if APValue
3607 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00003608 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003609 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00003610}
John McCallf2370c92010-01-06 05:24:50 +00003611
3612/// Pseudo-evaluate the given integer expression, estimating the
3613/// range of values it might take.
3614///
3615/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00003616static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003617 E = E->IgnoreParens();
3618
3619 // Try a full evaluation first.
3620 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003621 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00003622 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003623
3624 // I think we only want to look through implicit casts here; if the
3625 // user has an explicit widening cast, we should treat the value as
3626 // being of the new, wider type.
3627 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00003628 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00003629 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3630
John McCall1844a6e2010-11-10 23:38:19 +00003631 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00003632
John McCall2de56d12010-08-25 11:45:40 +00003633 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00003634
John McCallf2370c92010-01-06 05:24:50 +00003635 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00003636 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00003637 return OutputTypeRange;
3638
3639 IntRange SubRange
3640 = GetExprRange(C, CE->getSubExpr(),
3641 std::min(MaxWidth, OutputTypeRange.Width));
3642
3643 // Bail out if the subexpr's range is as wide as the cast type.
3644 if (SubRange.Width >= OutputTypeRange.Width)
3645 return OutputTypeRange;
3646
3647 // Otherwise, we take the smaller width, and we're non-negative if
3648 // either the output type or the subexpr is.
3649 return IntRange(SubRange.Width,
3650 SubRange.NonNegative || OutputTypeRange.NonNegative);
3651 }
3652
3653 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3654 // If we can fold the condition, just take that operand.
3655 bool CondResult;
3656 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3657 return GetExprRange(C, CondResult ? CO->getTrueExpr()
3658 : CO->getFalseExpr(),
3659 MaxWidth);
3660
3661 // Otherwise, conservatively merge.
3662 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3663 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3664 return IntRange::join(L, R);
3665 }
3666
3667 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3668 switch (BO->getOpcode()) {
3669
3670 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00003671 case BO_LAnd:
3672 case BO_LOr:
3673 case BO_LT:
3674 case BO_GT:
3675 case BO_LE:
3676 case BO_GE:
3677 case BO_EQ:
3678 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00003679 return IntRange::forBoolType();
3680
John McCall862ff872011-07-13 06:35:24 +00003681 // The type of the assignments is the type of the LHS, so the RHS
3682 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00003683 case BO_MulAssign:
3684 case BO_DivAssign:
3685 case BO_RemAssign:
3686 case BO_AddAssign:
3687 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00003688 case BO_XorAssign:
3689 case BO_OrAssign:
3690 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00003691 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00003692
John McCall862ff872011-07-13 06:35:24 +00003693 // Simple assignments just pass through the RHS, which will have
3694 // been coerced to the LHS type.
3695 case BO_Assign:
3696 // TODO: bitfields?
3697 return GetExprRange(C, BO->getRHS(), MaxWidth);
3698
John McCallf2370c92010-01-06 05:24:50 +00003699 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003700 case BO_PtrMemD:
3701 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00003702 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003703
John McCall60fad452010-01-06 22:07:33 +00003704 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00003705 case BO_And:
3706 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00003707 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3708 GetExprRange(C, BO->getRHS(), MaxWidth));
3709
John McCallf2370c92010-01-06 05:24:50 +00003710 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00003711 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00003712 // ...except that we want to treat '1 << (blah)' as logically
3713 // positive. It's an important idiom.
3714 if (IntegerLiteral *I
3715 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3716 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00003717 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00003718 return IntRange(R.Width, /*NonNegative*/ true);
3719 }
3720 }
3721 // fallthrough
3722
John McCall2de56d12010-08-25 11:45:40 +00003723 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00003724 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003725
John McCall60fad452010-01-06 22:07:33 +00003726 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00003727 case BO_Shr:
3728 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00003729 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3730
3731 // If the shift amount is a positive constant, drop the width by
3732 // that much.
3733 llvm::APSInt shift;
3734 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3735 shift.isNonNegative()) {
3736 unsigned zext = shift.getZExtValue();
3737 if (zext >= L.Width)
3738 L.Width = (L.NonNegative ? 0 : 1);
3739 else
3740 L.Width -= zext;
3741 }
3742
3743 return L;
3744 }
3745
3746 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00003747 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00003748 return GetExprRange(C, BO->getRHS(), MaxWidth);
3749
John McCall60fad452010-01-06 22:07:33 +00003750 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00003751 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00003752 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00003753 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00003754 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003755
John McCall00fe7612011-07-14 22:39:48 +00003756 // The width of a division result is mostly determined by the size
3757 // of the LHS.
3758 case BO_Div: {
3759 // Don't 'pre-truncate' the operands.
3760 unsigned opWidth = C.getIntWidth(E->getType());
3761 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3762
3763 // If the divisor is constant, use that.
3764 llvm::APSInt divisor;
3765 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3766 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3767 if (log2 >= L.Width)
3768 L.Width = (L.NonNegative ? 0 : 1);
3769 else
3770 L.Width = std::min(L.Width - log2, MaxWidth);
3771 return L;
3772 }
3773
3774 // Otherwise, just use the LHS's width.
3775 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3776 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3777 }
3778
3779 // The result of a remainder can't be larger than the result of
3780 // either side.
3781 case BO_Rem: {
3782 // Don't 'pre-truncate' the operands.
3783 unsigned opWidth = C.getIntWidth(E->getType());
3784 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3785 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3786
3787 IntRange meet = IntRange::meet(L, R);
3788 meet.Width = std::min(meet.Width, MaxWidth);
3789 return meet;
3790 }
3791
3792 // The default behavior is okay for these.
3793 case BO_Mul:
3794 case BO_Add:
3795 case BO_Xor:
3796 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00003797 break;
3798 }
3799
John McCall00fe7612011-07-14 22:39:48 +00003800 // The default case is to treat the operation as if it were closed
3801 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00003802 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3803 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3804 return IntRange::join(L, R);
3805 }
3806
3807 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3808 switch (UO->getOpcode()) {
3809 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00003810 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00003811 return IntRange::forBoolType();
3812
3813 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003814 case UO_Deref:
3815 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00003816 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003817
3818 default:
3819 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3820 }
3821 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003822
3823 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00003824 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003825 }
John McCallf2370c92010-01-06 05:24:50 +00003826
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003827 if (FieldDecl *BitField = E->getBitField())
3828 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003829 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00003830
John McCall1844a6e2010-11-10 23:38:19 +00003831 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003832}
John McCall51313c32010-01-04 23:31:57 +00003833
Ted Kremenek0692a192012-01-31 05:37:37 +00003834static IntRange GetExprRange(ASTContext &C, Expr *E) {
John McCall323ed742010-05-06 08:58:33 +00003835 return GetExprRange(C, E, C.getIntWidth(E->getType()));
3836}
3837
John McCall51313c32010-01-04 23:31:57 +00003838/// Checks whether the given value, which currently has the given
3839/// source semantics, has the same value when coerced through the
3840/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00003841static bool IsSameFloatAfterCast(const llvm::APFloat &value,
3842 const llvm::fltSemantics &Src,
3843 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003844 llvm::APFloat truncated = value;
3845
3846 bool ignored;
3847 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3848 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3849
3850 return truncated.bitwiseIsEqual(value);
3851}
3852
3853/// Checks whether the given value, which currently has the given
3854/// source semantics, has the same value when coerced through the
3855/// target semantics.
3856///
3857/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00003858static bool IsSameFloatAfterCast(const APValue &value,
3859 const llvm::fltSemantics &Src,
3860 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003861 if (value.isFloat())
3862 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3863
3864 if (value.isVector()) {
3865 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3866 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3867 return false;
3868 return true;
3869 }
3870
3871 assert(value.isComplexFloat());
3872 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3873 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3874}
3875
Ted Kremenek0692a192012-01-31 05:37:37 +00003876static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00003877
Ted Kremeneke3b159c2010-09-23 21:43:44 +00003878static bool IsZero(Sema &S, Expr *E) {
3879 // Suppress cases where we are comparing against an enum constant.
3880 if (const DeclRefExpr *DR =
3881 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3882 if (isa<EnumConstantDecl>(DR->getDecl()))
3883 return false;
3884
3885 // Suppress cases where the '0' value is expanded from a macro.
3886 if (E->getLocStart().isMacroID())
3887 return false;
3888
John McCall323ed742010-05-06 08:58:33 +00003889 llvm::APSInt Value;
3890 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3891}
3892
John McCall372e1032010-10-06 00:25:24 +00003893static bool HasEnumType(Expr *E) {
3894 // Strip off implicit integral promotions.
3895 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003896 if (ICE->getCastKind() != CK_IntegralCast &&
3897 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00003898 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003899 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00003900 }
3901
3902 return E->getType()->isEnumeralType();
3903}
3904
Ted Kremenek0692a192012-01-31 05:37:37 +00003905static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003906 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00003907 if (E->isValueDependent())
3908 return;
3909
John McCall2de56d12010-08-25 11:45:40 +00003910 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003911 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003912 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003913 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003914 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003915 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003916 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003917 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003918 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003919 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003920 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003921 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003922 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003923 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003924 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003925 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3926 }
3927}
3928
3929/// Analyze the operands of the given comparison. Implements the
3930/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00003931static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00003932 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3933 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00003934}
John McCall51313c32010-01-04 23:31:57 +00003935
John McCallba26e582010-01-04 23:21:16 +00003936/// \brief Implements -Wsign-compare.
3937///
Richard Trieudd225092011-09-15 21:56:47 +00003938/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00003939static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00003940 // The type the comparison is being performed in.
3941 QualType T = E->getLHS()->getType();
3942 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3943 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00003944
John McCall323ed742010-05-06 08:58:33 +00003945 // We don't do anything special if this isn't an unsigned integral
3946 // comparison: we're only interested in integral comparisons, and
3947 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00003948 //
3949 // We also don't care about value-dependent expressions or expressions
3950 // whose result is a constant.
3951 if (!T->hasUnsignedIntegerRepresentation()
3952 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00003953 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00003954
Richard Trieudd225092011-09-15 21:56:47 +00003955 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3956 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00003957
John McCall323ed742010-05-06 08:58:33 +00003958 // Check to see if one of the (unmodified) operands is of different
3959 // signedness.
3960 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00003961 if (LHS->getType()->hasSignedIntegerRepresentation()) {
3962 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00003963 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00003964 signedOperand = LHS;
3965 unsignedOperand = RHS;
3966 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3967 signedOperand = RHS;
3968 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00003969 } else {
John McCall323ed742010-05-06 08:58:33 +00003970 CheckTrivialUnsignedComparison(S, E);
3971 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003972 }
3973
John McCall323ed742010-05-06 08:58:33 +00003974 // Otherwise, calculate the effective range of the signed operand.
3975 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00003976
John McCall323ed742010-05-06 08:58:33 +00003977 // Go ahead and analyze implicit conversions in the operands. Note
3978 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00003979 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3980 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00003981
John McCall323ed742010-05-06 08:58:33 +00003982 // If the signed range is non-negative, -Wsign-compare won't fire,
3983 // but we should still check for comparisons which are always true
3984 // or false.
3985 if (signedRange.NonNegative)
3986 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003987
3988 // For (in)equality comparisons, if the unsigned operand is a
3989 // constant which cannot collide with a overflowed signed operand,
3990 // then reinterpreting the signed operand as unsigned will not
3991 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00003992 if (E->isEqualityOp()) {
3993 unsigned comparisonWidth = S.Context.getIntWidth(T);
3994 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00003995
John McCall323ed742010-05-06 08:58:33 +00003996 // We should never be unable to prove that the unsigned operand is
3997 // non-negative.
3998 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3999
4000 if (unsignedRange.Width < comparisonWidth)
4001 return;
4002 }
4003
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00004004 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4005 S.PDiag(diag::warn_mixed_sign_comparison)
4006 << LHS->getType() << RHS->getType()
4007 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00004008}
4009
John McCall15d7d122010-11-11 03:21:53 +00004010/// Analyzes an attempt to assign the given value to a bitfield.
4011///
4012/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00004013static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4014 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00004015 assert(Bitfield->isBitField());
4016 if (Bitfield->isInvalidDecl())
4017 return false;
4018
John McCall91b60142010-11-11 05:33:51 +00004019 // White-list bool bitfields.
4020 if (Bitfield->getType()->isBooleanType())
4021 return false;
4022
Douglas Gregor46ff3032011-02-04 13:09:01 +00004023 // Ignore value- or type-dependent expressions.
4024 if (Bitfield->getBitWidth()->isValueDependent() ||
4025 Bitfield->getBitWidth()->isTypeDependent() ||
4026 Init->isValueDependent() ||
4027 Init->isTypeDependent())
4028 return false;
4029
John McCall15d7d122010-11-11 03:21:53 +00004030 Expr *OriginalInit = Init->IgnoreParenImpCasts();
4031
Richard Smith80d4b552011-12-28 19:48:30 +00004032 llvm::APSInt Value;
4033 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00004034 return false;
4035
John McCall15d7d122010-11-11 03:21:53 +00004036 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004037 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00004038
4039 if (OriginalWidth <= FieldWidth)
4040 return false;
4041
Eli Friedman3a643af2012-01-26 23:11:39 +00004042 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004043 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00004044 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00004045
Eli Friedman3a643af2012-01-26 23:11:39 +00004046 // Check whether the stored value is equal to the original value.
4047 TruncatedValue = TruncatedValue.extend(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00004048 if (Value == TruncatedValue)
4049 return false;
4050
Eli Friedman3a643af2012-01-26 23:11:39 +00004051 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00004052 // therefore don't strictly fit into a signed bitfield of width 1.
4053 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00004054 return false;
4055
John McCall15d7d122010-11-11 03:21:53 +00004056 std::string PrettyValue = Value.toString(10);
4057 std::string PrettyTrunc = TruncatedValue.toString(10);
4058
4059 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4060 << PrettyValue << PrettyTrunc << OriginalInit->getType()
4061 << Init->getSourceRange();
4062
4063 return true;
4064}
4065
John McCallbeb22aa2010-11-09 23:24:47 +00004066/// Analyze the given simple or compound assignment for warning-worthy
4067/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00004068static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00004069 // Just recurse on the LHS.
4070 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4071
4072 // We want to recurse on the RHS as normal unless we're assigning to
4073 // a bitfield.
4074 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00004075 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
4076 E->getOperatorLoc())) {
4077 // Recurse, ignoring any implicit conversions on the RHS.
4078 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
4079 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00004080 }
4081 }
4082
4083 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4084}
4085
John McCall51313c32010-01-04 23:31:57 +00004086/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004087static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004088 SourceLocation CContext, unsigned diag,
4089 bool pruneControlFlow = false) {
4090 if (pruneControlFlow) {
4091 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4092 S.PDiag(diag)
4093 << SourceType << T << E->getSourceRange()
4094 << SourceRange(CContext));
4095 return;
4096 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004097 S.Diag(E->getExprLoc(), diag)
4098 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
4099}
4100
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004101/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004102static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004103 SourceLocation CContext, unsigned diag,
4104 bool pruneControlFlow = false) {
4105 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004106}
4107
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004108/// Diagnose an implicit cast from a literal expression. Does not warn when the
4109/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004110void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
4111 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004112 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004113 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004114 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00004115 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
4116 T->hasUnsignedIntegerRepresentation());
4117 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00004118 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004119 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00004120 return;
4121
David Blaikiebe0ee872012-05-15 16:56:36 +00004122 SmallString<16> PrettySourceValue;
4123 Value.toString(PrettySourceValue);
David Blaikiede7e7b82012-05-15 17:18:27 +00004124 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00004125 if (T->isSpecificBuiltinType(BuiltinType::Bool))
4126 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
4127 else
David Blaikiede7e7b82012-05-15 17:18:27 +00004128 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00004129
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004130 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00004131 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
4132 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00004133}
4134
John McCall091f23f2010-11-09 22:22:12 +00004135std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
4136 if (!Range.Width) return "0";
4137
4138 llvm::APSInt ValueInRange = Value;
4139 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00004140 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00004141 return ValueInRange.toString(10);
4142}
4143
John McCall323ed742010-05-06 08:58:33 +00004144void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004145 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00004146 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00004147
John McCall323ed742010-05-06 08:58:33 +00004148 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
4149 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
4150 if (Source == Target) return;
4151 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00004152
Chandler Carruth108f7562011-07-26 05:40:03 +00004153 // If the conversion context location is invalid don't complain. We also
4154 // don't want to emit a warning if the issue occurs from the expansion of
4155 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
4156 // delay this check as long as possible. Once we detect we are in that
4157 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00004158 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00004159 return;
4160
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004161 // Diagnose implicit casts to bool.
4162 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
4163 if (isa<StringLiteral>(E))
4164 // Warn on string literal to bool. Checks for string literals in logical
4165 // expressions, for instances, assert(0 && "error here"), is prevented
4166 // by a check in AnalyzeImplicitConversions().
4167 return DiagnoseImpCast(S, E, T, CC,
4168 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00004169 if (Source->isFunctionType()) {
4170 // Warn on function to bool. Checks free functions and static member
4171 // functions. Weakly imported functions are excluded from the check,
4172 // since it's common to test their value to check whether the linker
4173 // found a definition for them.
4174 ValueDecl *D = 0;
4175 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
4176 D = R->getDecl();
4177 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
4178 D = M->getMemberDecl();
4179 }
4180
4181 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00004182 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
4183 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
4184 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00004185 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
4186 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
4187 QualType ReturnType;
4188 UnresolvedSet<4> NonTemplateOverloads;
4189 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
4190 if (!ReturnType.isNull()
4191 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
4192 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
4193 << FixItHint::CreateInsertion(
4194 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00004195 return;
4196 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00004197 }
4198 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004199 }
John McCall51313c32010-01-04 23:31:57 +00004200
4201 // Strip vector types.
4202 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004203 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004204 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004205 return;
John McCallb4eb64d2010-10-08 02:01:28 +00004206 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004207 }
Chris Lattnerb792b302011-06-14 04:51:15 +00004208
4209 // If the vector cast is cast between two vectors of the same size, it is
4210 // a bitcast, not a conversion.
4211 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4212 return;
John McCall51313c32010-01-04 23:31:57 +00004213
4214 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4215 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4216 }
4217
4218 // Strip complex types.
4219 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004220 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004221 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004222 return;
4223
John McCallb4eb64d2010-10-08 02:01:28 +00004224 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004225 }
John McCall51313c32010-01-04 23:31:57 +00004226
4227 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4228 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4229 }
4230
4231 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4232 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4233
4234 // If the source is floating point...
4235 if (SourceBT && SourceBT->isFloatingPoint()) {
4236 // ...and the target is floating point...
4237 if (TargetBT && TargetBT->isFloatingPoint()) {
4238 // ...then warn if we're dropping FP rank.
4239
4240 // Builtin FP kinds are ordered by increasing FP rank.
4241 if (SourceBT->getKind() > TargetBT->getKind()) {
4242 // Don't warn about float constants that are precisely
4243 // representable in the target type.
4244 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004245 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00004246 // Value might be a float, a float vector, or a float complex.
4247 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00004248 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4249 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00004250 return;
4251 }
4252
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004253 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004254 return;
4255
John McCallb4eb64d2010-10-08 02:01:28 +00004256 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00004257 }
4258 return;
4259 }
4260
Ted Kremenekef9ff882011-03-10 20:03:42 +00004261 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00004262 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004263 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004264 return;
4265
Chandler Carrutha5b93322011-02-17 11:05:49 +00004266 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00004267 // We also want to warn on, e.g., "int i = -1.234"
4268 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4269 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4270 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
4271
Chandler Carruthf65076e2011-04-10 08:36:24 +00004272 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4273 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00004274 } else {
4275 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4276 }
4277 }
John McCall51313c32010-01-04 23:31:57 +00004278
4279 return;
4280 }
4281
John McCallf2370c92010-01-06 05:24:50 +00004282 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00004283 return;
4284
Richard Trieu1838ca52011-05-29 19:59:02 +00004285 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
4286 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
David Blaikieb1360492012-03-16 20:30:12 +00004287 SourceLocation Loc = E->getSourceRange().getBegin();
4288 if (Loc.isMacroID())
4289 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00004290 if (!Loc.isMacroID() || CC.isMacroID())
4291 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
4292 << T << clang::SourceRange(CC)
4293 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
Richard Trieu1838ca52011-05-29 19:59:02 +00004294 return;
4295 }
4296
David Blaikiebe0ee872012-05-15 16:56:36 +00004297 // TODO: remove this early return once the false positives for constant->bool
4298 // in templates, macros, etc, are reduced or removed.
4299 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
4300 return;
4301
John McCall323ed742010-05-06 08:58:33 +00004302 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00004303 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00004304
4305 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00004306 // If the source is a constant, use a default-on diagnostic.
4307 // TODO: this should happen for bitfield stores, too.
4308 llvm::APSInt Value(32);
4309 if (E->isIntegerConstantExpr(Value, S.Context)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004310 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004311 return;
4312
John McCall091f23f2010-11-09 22:22:12 +00004313 std::string PrettySourceValue = Value.toString(10);
4314 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
4315
Ted Kremenek5e745da2011-10-22 02:37:33 +00004316 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4317 S.PDiag(diag::warn_impcast_integer_precision_constant)
4318 << PrettySourceValue << PrettyTargetValue
4319 << E->getType() << T << E->getSourceRange()
4320 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00004321 return;
4322 }
4323
Chris Lattnerb792b302011-06-14 04:51:15 +00004324 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004325 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004326 return;
4327
David Blaikie37050842012-04-12 22:40:54 +00004328 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00004329 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
4330 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00004331 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00004332 }
4333
4334 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
4335 (!TargetRange.NonNegative && SourceRange.NonNegative &&
4336 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004337
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004338 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004339 return;
4340
John McCall323ed742010-05-06 08:58:33 +00004341 unsigned DiagID = diag::warn_impcast_integer_sign;
4342
4343 // Traditionally, gcc has warned about this under -Wsign-compare.
4344 // We also want to warn about it in -Wconversion.
4345 // So if -Wconversion is off, use a completely identical diagnostic
4346 // in the sign-compare group.
4347 // The conditional-checking code will
4348 if (ICContext) {
4349 DiagID = diag::warn_impcast_integer_sign_conditional;
4350 *ICContext = true;
4351 }
4352
John McCallb4eb64d2010-10-08 02:01:28 +00004353 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00004354 }
4355
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004356 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004357 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
4358 // type, to give us better diagnostics.
4359 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00004360 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004361 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4362 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4363 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
4364 SourceType = S.Context.getTypeDeclType(Enum);
4365 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
4366 }
4367 }
4368
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004369 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
4370 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
4371 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004372 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004373 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004374 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00004375 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004376 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004377 return;
4378
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004379 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004380 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004381 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004382
John McCall51313c32010-01-04 23:31:57 +00004383 return;
4384}
4385
David Blaikie9fb1ac52012-05-15 21:57:38 +00004386void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
4387 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00004388
4389void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004390 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00004391 E = E->IgnoreParenImpCasts();
4392
4393 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00004394 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00004395
John McCallb4eb64d2010-10-08 02:01:28 +00004396 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004397 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004398 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00004399 return;
4400}
4401
David Blaikie9fb1ac52012-05-15 21:57:38 +00004402void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
4403 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00004404 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00004405
4406 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00004407 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
4408 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004409
4410 // If -Wconversion would have warned about either of the candidates
4411 // for a signedness conversion to the context type...
4412 if (!Suspicious) return;
4413
4414 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004415 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
4416 CC))
John McCall323ed742010-05-06 08:58:33 +00004417 return;
4418
John McCall323ed742010-05-06 08:58:33 +00004419 // ...then check whether it would have warned about either of the
4420 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00004421 if (E->getType() == T) return;
4422
4423 Suspicious = false;
4424 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
4425 E->getType(), CC, &Suspicious);
4426 if (!Suspicious)
4427 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00004428 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004429}
4430
4431/// AnalyzeImplicitConversions - Find and report any interesting
4432/// implicit conversions in the given expression. There are a couple
4433/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004434void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004435 QualType T = OrigE->getType();
4436 Expr *E = OrigE->IgnoreParenImpCasts();
4437
Douglas Gregorf8b6e152011-10-10 17:38:18 +00004438 if (E->isTypeDependent() || E->isValueDependent())
4439 return;
4440
John McCall323ed742010-05-06 08:58:33 +00004441 // For conditional operators, we analyze the arguments as if they
4442 // were being fed directly into the output.
4443 if (isa<ConditionalOperator>(E)) {
4444 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00004445 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00004446 return;
4447 }
4448
4449 // Go ahead and check any implicit conversions we might have skipped.
4450 // The non-canonical typecheck is just an optimization;
4451 // CheckImplicitConversion will filter out dead implicit conversions.
4452 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004453 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00004454
4455 // Now continue drilling into this expression.
4456
4457 // Skip past explicit casts.
4458 if (isa<ExplicitCastExpr>(E)) {
4459 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00004460 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004461 }
4462
John McCallbeb22aa2010-11-09 23:24:47 +00004463 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4464 // Do a somewhat different check with comparison operators.
4465 if (BO->isComparisonOp())
4466 return AnalyzeComparison(S, BO);
4467
Eli Friedman0fa06382012-01-26 23:34:06 +00004468 // And with simple assignments.
4469 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00004470 return AnalyzeAssignment(S, BO);
4471 }
John McCall323ed742010-05-06 08:58:33 +00004472
4473 // These break the otherwise-useful invariant below. Fortunately,
4474 // we don't really need to recurse into them, because any internal
4475 // expressions should have been analyzed already when they were
4476 // built into statements.
4477 if (isa<StmtExpr>(E)) return;
4478
4479 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004480 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00004481
4482 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00004483 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004484 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
4485 bool IsLogicalOperator = BO && BO->isLogicalOp();
4486 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00004487 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00004488 if (!ChildExpr)
4489 continue;
4490
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004491 if (IsLogicalOperator &&
4492 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
4493 // Ignore checking string literals that are in logical operators.
4494 continue;
4495 AnalyzeImplicitConversions(S, ChildExpr, CC);
4496 }
John McCall323ed742010-05-06 08:58:33 +00004497}
4498
4499} // end anonymous namespace
4500
4501/// Diagnoses "dangerous" implicit conversions within the given
4502/// expression (which is a full expression). Implements -Wconversion
4503/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004504///
4505/// \param CC the "context" location of the implicit conversion, i.e.
4506/// the most location of the syntactic entity requiring the implicit
4507/// conversion
4508void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004509 // Don't diagnose in unevaluated contexts.
4510 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
4511 return;
4512
4513 // Don't diagnose for value- or type-dependent expressions.
4514 if (E->isTypeDependent() || E->isValueDependent())
4515 return;
4516
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004517 // Check for array bounds violations in cases where the check isn't triggered
4518 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
4519 // ArraySubscriptExpr is on the RHS of a variable initialization.
4520 CheckArrayAccess(E);
4521
John McCallb4eb64d2010-10-08 02:01:28 +00004522 // This is not the right CC for (e.g.) a variable initialization.
4523 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004524}
4525
John McCall15d7d122010-11-11 03:21:53 +00004526void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
4527 FieldDecl *BitField,
4528 Expr *Init) {
4529 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
4530}
4531
Mike Stumpf8c49212010-01-21 03:59:47 +00004532/// CheckParmsForFunctionDef - Check that the parameters of the given
4533/// function are appropriate for the definition of a function. This
4534/// takes care of any checks that cannot be performed on the
4535/// declaration itself, e.g., that the types of each of the function
4536/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004537bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
4538 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004539 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00004540 for (; P != PEnd; ++P) {
4541 ParmVarDecl *Param = *P;
4542
Mike Stumpf8c49212010-01-21 03:59:47 +00004543 // C99 6.7.5.3p4: the parameters in a parameter type list in a
4544 // function declarator that is part of a function definition of
4545 // that function shall not have incomplete type.
4546 //
4547 // This is also C++ [dcl.fct]p6.
4548 if (!Param->isInvalidDecl() &&
4549 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004550 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004551 Param->setInvalidDecl();
4552 HasInvalidParm = true;
4553 }
4554
4555 // C99 6.9.1p5: If the declarator includes a parameter type list, the
4556 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004557 if (CheckParameterNames &&
4558 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00004559 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00004560 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00004561 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00004562
4563 // C99 6.7.5.3p12:
4564 // If the function declarator is not part of a definition of that
4565 // function, parameters may have incomplete type and may use the [*]
4566 // notation in their sequences of declarator specifiers to specify
4567 // variable length array types.
4568 QualType PType = Param->getOriginalType();
4569 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
4570 if (AT->getSizeModifier() == ArrayType::Star) {
4571 // FIXME: This diagnosic should point the the '[*]' if source-location
4572 // information is added for it.
4573 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
4574 }
4575 }
Mike Stumpf8c49212010-01-21 03:59:47 +00004576 }
4577
4578 return HasInvalidParm;
4579}
John McCallb7f4ffe2010-08-12 21:44:57 +00004580
4581/// CheckCastAlign - Implements -Wcast-align, which warns when a
4582/// pointer cast increases the alignment requirements.
4583void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
4584 // This is actually a lot of work to potentially be doing on every
4585 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004586 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
4587 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00004588 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00004589 return;
4590
4591 // Ignore dependent types.
4592 if (T->isDependentType() || Op->getType()->isDependentType())
4593 return;
4594
4595 // Require that the destination be a pointer type.
4596 const PointerType *DestPtr = T->getAs<PointerType>();
4597 if (!DestPtr) return;
4598
4599 // If the destination has alignment 1, we're done.
4600 QualType DestPointee = DestPtr->getPointeeType();
4601 if (DestPointee->isIncompleteType()) return;
4602 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
4603 if (DestAlign.isOne()) return;
4604
4605 // Require that the source be a pointer type.
4606 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
4607 if (!SrcPtr) return;
4608 QualType SrcPointee = SrcPtr->getPointeeType();
4609
4610 // Whitelist casts from cv void*. We already implicitly
4611 // whitelisted casts to cv void*, since they have alignment 1.
4612 // Also whitelist casts involving incomplete types, which implicitly
4613 // includes 'void'.
4614 if (SrcPointee->isIncompleteType()) return;
4615
4616 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
4617 if (SrcAlign >= DestAlign) return;
4618
4619 Diag(TRange.getBegin(), diag::warn_cast_align)
4620 << Op->getType() << T
4621 << static_cast<unsigned>(SrcAlign.getQuantity())
4622 << static_cast<unsigned>(DestAlign.getQuantity())
4623 << TRange << Op->getSourceRange();
4624}
4625
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004626static const Type* getElementType(const Expr *BaseExpr) {
4627 const Type* EltType = BaseExpr->getType().getTypePtr();
4628 if (EltType->isAnyPointerType())
4629 return EltType->getPointeeType().getTypePtr();
4630 else if (EltType->isArrayType())
4631 return EltType->getBaseElementTypeUnsafe();
4632 return EltType;
4633}
4634
Chandler Carruthc2684342011-08-05 09:10:50 +00004635/// \brief Check whether this array fits the idiom of a size-one tail padded
4636/// array member of a struct.
4637///
4638/// We avoid emitting out-of-bounds access warnings for such arrays as they are
4639/// commonly used to emulate flexible arrays in C89 code.
4640static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4641 const NamedDecl *ND) {
4642 if (Size != 1 || !ND) return false;
4643
4644 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4645 if (!FD) return false;
4646
4647 // Don't consider sizes resulting from macro expansions or template argument
4648 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00004649
4650 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00004651 while (TInfo) {
4652 TypeLoc TL = TInfo->getTypeLoc();
4653 // Look through typedefs.
4654 const TypedefTypeLoc *TTL = dyn_cast<TypedefTypeLoc>(&TL);
4655 if (TTL) {
4656 const TypedefNameDecl *TDL = TTL->getTypedefNameDecl();
4657 TInfo = TDL->getTypeSourceInfo();
4658 continue;
4659 }
4660 ConstantArrayTypeLoc CTL = cast<ConstantArrayTypeLoc>(TL);
4661 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Sean Callanand2cf3482012-05-04 18:22:53 +00004662 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4663 return false;
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00004664 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00004665 }
Chandler Carruthc2684342011-08-05 09:10:50 +00004666
4667 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00004668 if (!RD) return false;
4669 if (RD->isUnion()) return false;
4670 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
4671 if (!CRD->isStandardLayout()) return false;
4672 }
Chandler Carruthc2684342011-08-05 09:10:50 +00004673
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00004674 // See if this is the last field decl in the record.
4675 const Decl *D = FD;
4676 while ((D = D->getNextDeclInContext()))
4677 if (isa<FieldDecl>(D))
4678 return false;
4679 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00004680}
4681
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004682void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004683 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00004684 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00004685 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004686 if (IndexExpr->isValueDependent())
4687 return;
4688
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00004689 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004690 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00004691 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004692 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00004693 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00004694 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00004695
Chandler Carruth34064582011-02-17 20:55:08 +00004696 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004697 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00004698 return;
Richard Smith25b009a2011-12-16 19:31:14 +00004699 if (IndexNegated)
4700 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004701
Chandler Carruthba447122011-08-05 08:07:29 +00004702 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00004703 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4704 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00004705 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00004706 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00004707
Ted Kremenek9e060ca2011-02-23 23:06:04 +00004708 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00004709 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00004710 if (!size.isStrictlyPositive())
4711 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004712
4713 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00004714 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004715 // Make sure we're comparing apples to apples when comparing index to size
4716 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4717 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00004718 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00004719 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004720 if (ptrarith_typesize != array_typesize) {
4721 // There's a cast to a different size type involved
4722 uint64_t ratio = array_typesize / ptrarith_typesize;
4723 // TODO: Be smarter about handling cases where array_typesize is not a
4724 // multiple of ptrarith_typesize
4725 if (ptrarith_typesize * ratio == array_typesize)
4726 size *= llvm::APInt(size.getBitWidth(), ratio);
4727 }
4728 }
4729
Chandler Carruth34064582011-02-17 20:55:08 +00004730 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00004731 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004732 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00004733 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004734
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004735 // For array subscripting the index must be less than size, but for pointer
4736 // arithmetic also allow the index (offset) to be equal to size since
4737 // computing the next address after the end of the array is legal and
4738 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00004739 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00004740 return;
4741
4742 // Also don't warn for arrays of size 1 which are members of some
4743 // structure. These are often used to approximate flexible arrays in C89
4744 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004745 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004746 return;
Chandler Carruth34064582011-02-17 20:55:08 +00004747
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004748 // Suppress the warning if the subscript expression (as identified by the
4749 // ']' location) and the index expression are both from macro expansions
4750 // within a system header.
4751 if (ASE) {
4752 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
4753 ASE->getRBracketLoc());
4754 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
4755 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
4756 IndexExpr->getLocStart());
4757 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
4758 return;
4759 }
4760 }
4761
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004762 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004763 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004764 DiagID = diag::warn_array_index_exceeds_bounds;
4765
4766 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4767 PDiag(DiagID) << index.toString(10, true)
4768 << size.toString(10, true)
4769 << (unsigned)size.getLimitedValue(~0U)
4770 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00004771 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004772 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004773 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004774 DiagID = diag::warn_ptr_arith_precedes_bounds;
4775 if (index.isNegative()) index = -index;
4776 }
4777
4778 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4779 PDiag(DiagID) << index.toString(10, true)
4780 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004781 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00004782
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00004783 if (!ND) {
4784 // Try harder to find a NamedDecl to point at in the note.
4785 while (const ArraySubscriptExpr *ASE =
4786 dyn_cast<ArraySubscriptExpr>(BaseExpr))
4787 BaseExpr = ASE->getBase()->IgnoreParenCasts();
4788 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4789 ND = dyn_cast<NamedDecl>(DRE->getDecl());
4790 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
4791 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
4792 }
4793
Chandler Carruth35001ca2011-02-17 21:10:52 +00004794 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004795 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4796 PDiag(diag::note_array_index_out_of_bounds)
4797 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004798}
4799
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004800void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004801 int AllowOnePastEnd = 0;
4802 while (expr) {
4803 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004804 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004805 case Stmt::ArraySubscriptExprClass: {
4806 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004807 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004808 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004809 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004810 }
4811 case Stmt::UnaryOperatorClass: {
4812 // Only unwrap the * and & unary operators
4813 const UnaryOperator *UO = cast<UnaryOperator>(expr);
4814 expr = UO->getSubExpr();
4815 switch (UO->getOpcode()) {
4816 case UO_AddrOf:
4817 AllowOnePastEnd++;
4818 break;
4819 case UO_Deref:
4820 AllowOnePastEnd--;
4821 break;
4822 default:
4823 return;
4824 }
4825 break;
4826 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004827 case Stmt::ConditionalOperatorClass: {
4828 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4829 if (const Expr *lhs = cond->getLHS())
4830 CheckArrayAccess(lhs);
4831 if (const Expr *rhs = cond->getRHS())
4832 CheckArrayAccess(rhs);
4833 return;
4834 }
4835 default:
4836 return;
4837 }
Peter Collingbournef111d932011-04-15 00:35:48 +00004838 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004839}
John McCallf85e1932011-06-15 23:02:42 +00004840
4841//===--- CHECK: Objective-C retain cycles ----------------------------------//
4842
4843namespace {
4844 struct RetainCycleOwner {
4845 RetainCycleOwner() : Variable(0), Indirect(false) {}
4846 VarDecl *Variable;
4847 SourceRange Range;
4848 SourceLocation Loc;
4849 bool Indirect;
4850
4851 void setLocsFrom(Expr *e) {
4852 Loc = e->getExprLoc();
4853 Range = e->getSourceRange();
4854 }
4855 };
4856}
4857
4858/// Consider whether capturing the given variable can possibly lead to
4859/// a retain cycle.
4860static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4861 // In ARC, it's captured strongly iff the variable has __strong
4862 // lifetime. In MRR, it's captured strongly if the variable is
4863 // __block and has an appropriate type.
4864 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4865 return false;
4866
4867 owner.Variable = var;
4868 owner.setLocsFrom(ref);
4869 return true;
4870}
4871
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004872static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00004873 while (true) {
4874 e = e->IgnoreParens();
4875 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4876 switch (cast->getCastKind()) {
4877 case CK_BitCast:
4878 case CK_LValueBitCast:
4879 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00004880 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00004881 e = cast->getSubExpr();
4882 continue;
4883
John McCallf85e1932011-06-15 23:02:42 +00004884 default:
4885 return false;
4886 }
4887 }
4888
4889 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4890 ObjCIvarDecl *ivar = ref->getDecl();
4891 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4892 return false;
4893
4894 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004895 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00004896 return false;
4897
4898 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4899 owner.Indirect = true;
4900 return true;
4901 }
4902
4903 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4904 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4905 if (!var) return false;
4906 return considerVariable(var, ref, owner);
4907 }
4908
John McCallf85e1932011-06-15 23:02:42 +00004909 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4910 if (member->isArrow()) return false;
4911
4912 // Don't count this as an indirect ownership.
4913 e = member->getBase();
4914 continue;
4915 }
4916
John McCall4b9c2d22011-11-06 09:01:30 +00004917 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
4918 // Only pay attention to pseudo-objects on property references.
4919 ObjCPropertyRefExpr *pre
4920 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
4921 ->IgnoreParens());
4922 if (!pre) return false;
4923 if (pre->isImplicitProperty()) return false;
4924 ObjCPropertyDecl *property = pre->getExplicitProperty();
4925 if (!property->isRetaining() &&
4926 !(property->getPropertyIvarDecl() &&
4927 property->getPropertyIvarDecl()->getType()
4928 .getObjCLifetime() == Qualifiers::OCL_Strong))
4929 return false;
4930
4931 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004932 if (pre->isSuperReceiver()) {
4933 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
4934 if (!owner.Variable)
4935 return false;
4936 owner.Loc = pre->getLocation();
4937 owner.Range = pre->getSourceRange();
4938 return true;
4939 }
John McCall4b9c2d22011-11-06 09:01:30 +00004940 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
4941 ->getSourceExpr());
4942 continue;
4943 }
4944
John McCallf85e1932011-06-15 23:02:42 +00004945 // Array ivars?
4946
4947 return false;
4948 }
4949}
4950
4951namespace {
4952 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4953 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4954 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4955 Variable(variable), Capturer(0) {}
4956
4957 VarDecl *Variable;
4958 Expr *Capturer;
4959
4960 void VisitDeclRefExpr(DeclRefExpr *ref) {
4961 if (ref->getDecl() == Variable && !Capturer)
4962 Capturer = ref;
4963 }
4964
John McCallf85e1932011-06-15 23:02:42 +00004965 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4966 if (Capturer) return;
4967 Visit(ref->getBase());
4968 if (Capturer && ref->isFreeIvar())
4969 Capturer = ref;
4970 }
4971
4972 void VisitBlockExpr(BlockExpr *block) {
4973 // Look inside nested blocks
4974 if (block->getBlockDecl()->capturesVariable(Variable))
4975 Visit(block->getBlockDecl()->getBody());
4976 }
4977 };
4978}
4979
4980/// Check whether the given argument is a block which captures a
4981/// variable.
4982static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4983 assert(owner.Variable && owner.Loc.isValid());
4984
4985 e = e->IgnoreParenCasts();
4986 BlockExpr *block = dyn_cast<BlockExpr>(e);
4987 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4988 return 0;
4989
4990 FindCaptureVisitor visitor(S.Context, owner.Variable);
4991 visitor.Visit(block->getBlockDecl()->getBody());
4992 return visitor.Capturer;
4993}
4994
4995static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4996 RetainCycleOwner &owner) {
4997 assert(capturer);
4998 assert(owner.Variable && owner.Loc.isValid());
4999
5000 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
5001 << owner.Variable << capturer->getSourceRange();
5002 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
5003 << owner.Indirect << owner.Range;
5004}
5005
5006/// Check for a keyword selector that starts with the word 'add' or
5007/// 'set'.
5008static bool isSetterLikeSelector(Selector sel) {
5009 if (sel.isUnarySelector()) return false;
5010
Chris Lattner5f9e2722011-07-23 10:55:15 +00005011 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00005012 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00005013 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00005014 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00005015 else if (str.startswith("add")) {
5016 // Specially whitelist 'addOperationWithBlock:'.
5017 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
5018 return false;
5019 str = str.substr(3);
5020 }
John McCallf85e1932011-06-15 23:02:42 +00005021 else
5022 return false;
5023
5024 if (str.empty()) return true;
5025 return !islower(str.front());
5026}
5027
5028/// Check a message send to see if it's likely to cause a retain cycle.
5029void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
5030 // Only check instance methods whose selector looks like a setter.
5031 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
5032 return;
5033
5034 // Try to find a variable that the receiver is strongly owned by.
5035 RetainCycleOwner owner;
5036 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005037 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00005038 return;
5039 } else {
5040 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
5041 owner.Variable = getCurMethodDecl()->getSelfDecl();
5042 owner.Loc = msg->getSuperLoc();
5043 owner.Range = msg->getSuperLoc();
5044 }
5045
5046 // Check whether the receiver is captured by any of the arguments.
5047 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
5048 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
5049 return diagnoseRetainCycle(*this, capturer, owner);
5050}
5051
5052/// Check a property assign to see if it's likely to cause a retain cycle.
5053void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
5054 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005055 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00005056 return;
5057
5058 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
5059 diagnoseRetainCycle(*this, capturer, owner);
5060}
5061
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005062bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00005063 QualType LHS, Expr *RHS) {
5064 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
5065 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005066 return false;
5067 // strip off any implicit cast added to get to the one arc-specific
5068 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005069 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00005070 Diag(Loc, diag::warn_arc_retained_assign)
5071 << (LT == Qualifiers::OCL_ExplicitNone)
5072 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005073 return true;
5074 }
5075 RHS = cast->getSubExpr();
5076 }
5077 return false;
John McCallf85e1932011-06-15 23:02:42 +00005078}
5079
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005080void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
5081 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005082 QualType LHSType;
5083 // PropertyRef on LHS type need be directly obtained from
5084 // its declaration as it has a PsuedoType.
5085 ObjCPropertyRefExpr *PRE
5086 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
5087 if (PRE && !PRE->isImplicitProperty()) {
5088 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5089 if (PD)
5090 LHSType = PD->getType();
5091 }
5092
5093 if (LHSType.isNull())
5094 LHSType = LHS->getType();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005095 if (checkUnsafeAssigns(Loc, LHSType, RHS))
5096 return;
5097 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
5098 // FIXME. Check for other life times.
5099 if (LT != Qualifiers::OCL_None)
5100 return;
5101
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005102 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005103 if (PRE->isImplicitProperty())
5104 return;
5105 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5106 if (!PD)
5107 return;
5108
5109 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005110 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
5111 // when 'assign' attribute was not explicitly specified
5112 // by user, ignore it and rely on property type itself
5113 // for lifetime info.
5114 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
5115 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
5116 LHSType->isObjCRetainableType())
5117 return;
5118
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005119 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005120 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005121 Diag(Loc, diag::warn_arc_retained_property_assign)
5122 << RHS->getSourceRange();
5123 return;
5124 }
5125 RHS = cast->getSubExpr();
5126 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005127 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005128 }
5129}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00005130
5131//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
5132
5133namespace {
5134bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
5135 SourceLocation StmtLoc,
5136 const NullStmt *Body) {
5137 // Do not warn if the body is a macro that expands to nothing, e.g:
5138 //
5139 // #define CALL(x)
5140 // if (condition)
5141 // CALL(0);
5142 //
5143 if (Body->hasLeadingEmptyMacro())
5144 return false;
5145
5146 // Get line numbers of statement and body.
5147 bool StmtLineInvalid;
5148 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
5149 &StmtLineInvalid);
5150 if (StmtLineInvalid)
5151 return false;
5152
5153 bool BodyLineInvalid;
5154 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
5155 &BodyLineInvalid);
5156 if (BodyLineInvalid)
5157 return false;
5158
5159 // Warn if null statement and body are on the same line.
5160 if (StmtLine != BodyLine)
5161 return false;
5162
5163 return true;
5164}
5165} // Unnamed namespace
5166
5167void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
5168 const Stmt *Body,
5169 unsigned DiagID) {
5170 // Since this is a syntactic check, don't emit diagnostic for template
5171 // instantiations, this just adds noise.
5172 if (CurrentInstantiationScope)
5173 return;
5174
5175 // The body should be a null statement.
5176 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5177 if (!NBody)
5178 return;
5179
5180 // Do the usual checks.
5181 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5182 return;
5183
5184 Diag(NBody->getSemiLoc(), DiagID);
5185 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5186}
5187
5188void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
5189 const Stmt *PossibleBody) {
5190 assert(!CurrentInstantiationScope); // Ensured by caller
5191
5192 SourceLocation StmtLoc;
5193 const Stmt *Body;
5194 unsigned DiagID;
5195 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
5196 StmtLoc = FS->getRParenLoc();
5197 Body = FS->getBody();
5198 DiagID = diag::warn_empty_for_body;
5199 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
5200 StmtLoc = WS->getCond()->getSourceRange().getEnd();
5201 Body = WS->getBody();
5202 DiagID = diag::warn_empty_while_body;
5203 } else
5204 return; // Neither `for' nor `while'.
5205
5206 // The body should be a null statement.
5207 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5208 if (!NBody)
5209 return;
5210
5211 // Skip expensive checks if diagnostic is disabled.
5212 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
5213 DiagnosticsEngine::Ignored)
5214 return;
5215
5216 // Do the usual checks.
5217 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5218 return;
5219
5220 // `for(...);' and `while(...);' are popular idioms, so in order to keep
5221 // noise level low, emit diagnostics only if for/while is followed by a
5222 // CompoundStmt, e.g.:
5223 // for (int i = 0; i < n; i++);
5224 // {
5225 // a(i);
5226 // }
5227 // or if for/while is followed by a statement with more indentation
5228 // than for/while itself:
5229 // for (int i = 0; i < n; i++);
5230 // a(i);
5231 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
5232 if (!ProbableTypo) {
5233 bool BodyColInvalid;
5234 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
5235 PossibleBody->getLocStart(),
5236 &BodyColInvalid);
5237 if (BodyColInvalid)
5238 return;
5239
5240 bool StmtColInvalid;
5241 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
5242 S->getLocStart(),
5243 &StmtColInvalid);
5244 if (StmtColInvalid)
5245 return;
5246
5247 if (BodyCol > StmtCol)
5248 ProbableTypo = true;
5249 }
5250
5251 if (ProbableTypo) {
5252 Diag(NBody->getSemiLoc(), DiagID);
5253 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5254 }
5255}