blob: dbb0a0efaa4c9f831794694486a49820b914f4c5 [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"
Ted Kremenek23245122007-08-20 16:18:38 +000025#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000026#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000027#include "clang/AST/EvaluatedExprVisitor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000028#include "clang/AST/DeclObjC.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/StmtObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000031#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000032#include "llvm/ADT/BitVector.h"
33#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000034#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000035#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000036#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000037#include "clang/Basic/ConvertUTF.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000038#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000039using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000040using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000041
Chris Lattner60800082009-02-18 17:49:48 +000042SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
43 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000044 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
45 PP.getLangOptions(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000046}
47
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +000048bool Sema::CheckablePrintfAttr(const FormatAttr *Format, Expr **Args,
49 unsigned NumArgs, bool IsCXXMemberCall) {
50 StringRef Type = Format->getType();
51 // FIXME: add support for "CFString" Type. They are not string literal though,
52 // so they need special handling.
53 if (Type == "printf" || Type == "NSString") return true;
54 if (Type == "printf0") {
Ryan Flynn4403a5e2009-08-06 03:00:50 +000055 // printf0 allows null "format" string; if so don't check format/args
56 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl4a2614e2009-11-17 18:02:24 +000057 // Does the index refer to the implicit object argument?
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +000058 if (IsCXXMemberCall) {
Sebastian Redl4a2614e2009-11-17 18:02:24 +000059 if (format_idx == 0)
60 return false;
61 --format_idx;
62 }
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +000063 if (format_idx < NumArgs) {
64 Expr *Format = Args[format_idx]->IgnoreParenCasts();
Ted Kremenekefaff192010-02-27 01:41:03 +000065 if (!Format->isNullPointerConstant(Context,
66 Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +000067 return true;
68 }
69 }
70 return false;
71}
Chris Lattner60800082009-02-18 17:49:48 +000072
John McCall8e10f3b2011-02-26 05:39:39 +000073/// Checks that a call expression's argument count is the desired number.
74/// This is useful when doing custom type-checking. Returns true on error.
75static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
76 unsigned argCount = call->getNumArgs();
77 if (argCount == desiredArgCount) return false;
78
79 if (argCount < desiredArgCount)
80 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
81 << 0 /*function call*/ << desiredArgCount << argCount
82 << call->getSourceRange();
83
84 // Highlight all the excess arguments.
85 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
86 call->getArg(argCount - 1)->getLocEnd());
87
88 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
89 << 0 /*function call*/ << desiredArgCount << argCount
90 << call->getArg(1)->getSourceRange();
91}
92
Julien Lerouge77f68bb2011-09-09 22:41:49 +000093/// CheckBuiltinAnnotationString - Checks that string argument to the builtin
94/// annotation is a non wide string literal.
95static bool CheckBuiltinAnnotationString(Sema &S, Expr *Arg) {
96 Arg = Arg->IgnoreParenCasts();
97 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
98 if (!Literal || !Literal->isAscii()) {
99 S.Diag(Arg->getLocStart(), diag::err_builtin_annotation_not_string_constant)
100 << Arg->getSourceRange();
101 return true;
102 }
103 return false;
104}
105
John McCall60d7b3a2010-08-24 06:29:42 +0000106ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000107Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +0000108 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000109
Chris Lattner946928f2010-10-01 23:23:24 +0000110 // Find out if any arguments are required to be integer constant expressions.
111 unsigned ICEArguments = 0;
112 ASTContext::GetBuiltinTypeError Error;
113 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
114 if (Error != ASTContext::GE_None)
115 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
116
117 // If any arguments are required to be ICE's, check and diagnose.
118 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
119 // Skip arguments not required to be ICE's.
120 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
121
122 llvm::APSInt Result;
123 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
124 return true;
125 ICEArguments &= ~(1 << ArgNo);
126 }
127
Anders Carlssond406bf02009-08-16 01:56:34 +0000128 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000129 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000130 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000131 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000132 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000133 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000134 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000135 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000136 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000137 if (SemaBuiltinVAStart(TheCall))
138 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000139 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000140 case Builtin::BI__builtin_isgreater:
141 case Builtin::BI__builtin_isgreaterequal:
142 case Builtin::BI__builtin_isless:
143 case Builtin::BI__builtin_islessequal:
144 case Builtin::BI__builtin_islessgreater:
145 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000146 if (SemaBuiltinUnorderedCompare(TheCall))
147 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000148 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000149 case Builtin::BI__builtin_fpclassify:
150 if (SemaBuiltinFPClassification(TheCall, 6))
151 return ExprError();
152 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000153 case Builtin::BI__builtin_isfinite:
154 case Builtin::BI__builtin_isinf:
155 case Builtin::BI__builtin_isinf_sign:
156 case Builtin::BI__builtin_isnan:
157 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000158 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000159 return ExprError();
160 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000161 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000162 return SemaBuiltinShuffleVector(TheCall);
163 // TheCall will be freed by the smart pointer here, but that's fine, since
164 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000165 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000166 if (SemaBuiltinPrefetch(TheCall))
167 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000168 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000169 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000170 if (SemaBuiltinObjectSize(TheCall))
171 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000172 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000173 case Builtin::BI__builtin_longjmp:
174 if (SemaBuiltinLongjmp(TheCall))
175 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000176 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000177
178 case Builtin::BI__builtin_classify_type:
179 if (checkArgCount(*this, TheCall, 1)) return true;
180 TheCall->setType(Context.IntTy);
181 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000182 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000183 if (checkArgCount(*this, TheCall, 1)) return true;
184 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000185 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000186 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000187 case Builtin::BI__sync_fetch_and_add_1:
188 case Builtin::BI__sync_fetch_and_add_2:
189 case Builtin::BI__sync_fetch_and_add_4:
190 case Builtin::BI__sync_fetch_and_add_8:
191 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000192 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000193 case Builtin::BI__sync_fetch_and_sub_1:
194 case Builtin::BI__sync_fetch_and_sub_2:
195 case Builtin::BI__sync_fetch_and_sub_4:
196 case Builtin::BI__sync_fetch_and_sub_8:
197 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000198 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000199 case Builtin::BI__sync_fetch_and_or_1:
200 case Builtin::BI__sync_fetch_and_or_2:
201 case Builtin::BI__sync_fetch_and_or_4:
202 case Builtin::BI__sync_fetch_and_or_8:
203 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000204 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000205 case Builtin::BI__sync_fetch_and_and_1:
206 case Builtin::BI__sync_fetch_and_and_2:
207 case Builtin::BI__sync_fetch_and_and_4:
208 case Builtin::BI__sync_fetch_and_and_8:
209 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000210 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000211 case Builtin::BI__sync_fetch_and_xor_1:
212 case Builtin::BI__sync_fetch_and_xor_2:
213 case Builtin::BI__sync_fetch_and_xor_4:
214 case Builtin::BI__sync_fetch_and_xor_8:
215 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000216 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000217 case Builtin::BI__sync_add_and_fetch_1:
218 case Builtin::BI__sync_add_and_fetch_2:
219 case Builtin::BI__sync_add_and_fetch_4:
220 case Builtin::BI__sync_add_and_fetch_8:
221 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000222 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000223 case Builtin::BI__sync_sub_and_fetch_1:
224 case Builtin::BI__sync_sub_and_fetch_2:
225 case Builtin::BI__sync_sub_and_fetch_4:
226 case Builtin::BI__sync_sub_and_fetch_8:
227 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000228 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000229 case Builtin::BI__sync_and_and_fetch_1:
230 case Builtin::BI__sync_and_and_fetch_2:
231 case Builtin::BI__sync_and_and_fetch_4:
232 case Builtin::BI__sync_and_and_fetch_8:
233 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000234 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000235 case Builtin::BI__sync_or_and_fetch_1:
236 case Builtin::BI__sync_or_and_fetch_2:
237 case Builtin::BI__sync_or_and_fetch_4:
238 case Builtin::BI__sync_or_and_fetch_8:
239 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000240 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000241 case Builtin::BI__sync_xor_and_fetch_1:
242 case Builtin::BI__sync_xor_and_fetch_2:
243 case Builtin::BI__sync_xor_and_fetch_4:
244 case Builtin::BI__sync_xor_and_fetch_8:
245 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000246 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000247 case Builtin::BI__sync_val_compare_and_swap_1:
248 case Builtin::BI__sync_val_compare_and_swap_2:
249 case Builtin::BI__sync_val_compare_and_swap_4:
250 case Builtin::BI__sync_val_compare_and_swap_8:
251 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000252 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000253 case Builtin::BI__sync_bool_compare_and_swap_1:
254 case Builtin::BI__sync_bool_compare_and_swap_2:
255 case Builtin::BI__sync_bool_compare_and_swap_4:
256 case Builtin::BI__sync_bool_compare_and_swap_8:
257 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000258 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000259 case Builtin::BI__sync_lock_test_and_set_1:
260 case Builtin::BI__sync_lock_test_and_set_2:
261 case Builtin::BI__sync_lock_test_and_set_4:
262 case Builtin::BI__sync_lock_test_and_set_8:
263 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000264 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000265 case Builtin::BI__sync_lock_release_1:
266 case Builtin::BI__sync_lock_release_2:
267 case Builtin::BI__sync_lock_release_4:
268 case Builtin::BI__sync_lock_release_8:
269 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000270 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000271 case Builtin::BI__sync_swap_1:
272 case Builtin::BI__sync_swap_2:
273 case Builtin::BI__sync_swap_4:
274 case Builtin::BI__sync_swap_8:
275 case Builtin::BI__sync_swap_16:
Chandler Carruthd2014572010-07-09 18:59:35 +0000276 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Eli Friedman276b0612011-10-11 02:20:01 +0000277 case Builtin::BI__atomic_load:
278 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Load);
279 case Builtin::BI__atomic_store:
280 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Store);
David Chisnall7a7ee302012-01-16 17:27:18 +0000281 case Builtin::BI__atomic_init:
282 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Init);
Eli Friedman276b0612011-10-11 02:20:01 +0000283 case Builtin::BI__atomic_exchange:
284 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg);
285 case Builtin::BI__atomic_compare_exchange_strong:
286 return SemaAtomicOpsOverloaded(move(TheCallResult),
287 AtomicExpr::CmpXchgStrong);
288 case Builtin::BI__atomic_compare_exchange_weak:
289 return SemaAtomicOpsOverloaded(move(TheCallResult),
290 AtomicExpr::CmpXchgWeak);
291 case Builtin::BI__atomic_fetch_add:
292 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add);
293 case Builtin::BI__atomic_fetch_sub:
294 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub);
295 case Builtin::BI__atomic_fetch_and:
296 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And);
297 case Builtin::BI__atomic_fetch_or:
298 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or);
299 case Builtin::BI__atomic_fetch_xor:
300 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor);
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000301 case Builtin::BI__builtin_annotation:
302 if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1)))
303 return ExprError();
304 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000305 }
306
307 // Since the target specific builtins for each arch overlap, only check those
308 // of the arch we are compiling for.
309 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000310 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000311 case llvm::Triple::arm:
312 case llvm::Triple::thumb:
313 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
314 return ExprError();
315 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000316 default:
317 break;
318 }
319 }
320
321 return move(TheCallResult);
322}
323
Nate Begeman61eecf52010-06-14 05:21:25 +0000324// Get the valid immediate range for the specified NEON type code.
325static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000326 NeonTypeFlags Type(t);
327 int IsQuad = Type.isQuad();
328 switch (Type.getEltType()) {
329 case NeonTypeFlags::Int8:
330 case NeonTypeFlags::Poly8:
331 return shift ? 7 : (8 << IsQuad) - 1;
332 case NeonTypeFlags::Int16:
333 case NeonTypeFlags::Poly16:
334 return shift ? 15 : (4 << IsQuad) - 1;
335 case NeonTypeFlags::Int32:
336 return shift ? 31 : (2 << IsQuad) - 1;
337 case NeonTypeFlags::Int64:
338 return shift ? 63 : (1 << IsQuad) - 1;
339 case NeonTypeFlags::Float16:
340 assert(!shift && "cannot shift float types!");
341 return (4 << IsQuad) - 1;
342 case NeonTypeFlags::Float32:
343 assert(!shift && "cannot shift float types!");
344 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000345 }
David Blaikie7530c032012-01-17 06:56:22 +0000346 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000347}
348
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000349/// getNeonEltType - Return the QualType corresponding to the elements of
350/// the vector type specified by the NeonTypeFlags. This is used to check
351/// the pointer arguments for Neon load/store intrinsics.
352static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
353 switch (Flags.getEltType()) {
354 case NeonTypeFlags::Int8:
355 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
356 case NeonTypeFlags::Int16:
357 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
358 case NeonTypeFlags::Int32:
359 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
360 case NeonTypeFlags::Int64:
361 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
362 case NeonTypeFlags::Poly8:
363 return Context.SignedCharTy;
364 case NeonTypeFlags::Poly16:
365 return Context.ShortTy;
366 case NeonTypeFlags::Float16:
367 return Context.UnsignedShortTy;
368 case NeonTypeFlags::Float32:
369 return Context.FloatTy;
370 }
David Blaikie7530c032012-01-17 06:56:22 +0000371 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000372}
373
Nate Begeman26a31422010-06-08 02:47:44 +0000374bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000375 llvm::APSInt Result;
376
Nate Begeman0d15c532010-06-13 04:47:52 +0000377 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000378 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000379 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000380 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000381 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000382#define GET_NEON_OVERLOAD_CHECK
383#include "clang/Basic/arm_neon.inc"
384#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000385 }
386
Nate Begeman0d15c532010-06-13 04:47:52 +0000387 // For NEON intrinsics which are overloaded on vector element type, validate
388 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000389 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000390 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000391 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000392 return true;
393
Bob Wilsonda95f732011-11-08 01:16:11 +0000394 TV = Result.getLimitedValue(64);
395 if ((TV > 63) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000396 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000397 << TheCall->getArg(ImmArg)->getSourceRange();
398 }
399
Bob Wilson46482552011-11-16 21:32:23 +0000400 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000401 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000402 Expr *Arg = TheCall->getArg(PtrArgNum);
403 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
404 Arg = ICE->getSubExpr();
405 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
406 QualType RHSTy = RHS.get()->getType();
407 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
408 if (HasConstPtr)
409 EltTy = EltTy.withConst();
410 QualType LHSTy = Context.getPointerType(EltTy);
411 AssignConvertType ConvTy;
412 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
413 if (RHS.isInvalid())
414 return true;
415 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
416 RHS.get(), AA_Assigning))
417 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000418 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000419
Nate Begeman0d15c532010-06-13 04:47:52 +0000420 // For NEON intrinsics which take an immediate value as part of the
421 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000422 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000423 switch (BuiltinID) {
424 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000425 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
426 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000427 case ARM::BI__builtin_arm_vcvtr_f:
428 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000429#define GET_NEON_IMMEDIATE_CHECK
430#include "clang/Basic/arm_neon.inc"
431#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000432 };
433
Nate Begeman61eecf52010-06-14 05:21:25 +0000434 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000435 if (SemaBuiltinConstantArg(TheCall, i, Result))
436 return true;
437
Nate Begeman61eecf52010-06-14 05:21:25 +0000438 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000439 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000440 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000441 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000442 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000443
Nate Begeman99c40bb2010-08-03 21:32:34 +0000444 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000445 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000446}
Daniel Dunbarde454282008-10-02 18:44:07 +0000447
Anders Carlssond406bf02009-08-16 01:56:34 +0000448/// CheckFunctionCall - Check a direct function call for various correctness
449/// and safety properties not strictly enforced by the C type system.
450bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
451 // Get the IdentifierInfo* for the called function.
452 IdentifierInfo *FnInfo = FDecl->getIdentifier();
453
454 // None of the checks below are needed for functions that don't have
455 // simple names (e.g., C++ conversion functions).
456 if (!FnInfo)
457 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Daniel Dunbarde454282008-10-02 18:44:07 +0000459 // FIXME: This mechanism should be abstracted to be less fragile and
460 // more efficient. For example, just map function ids to custom
461 // handlers.
462
Ted Kremenekc82faca2010-09-09 04:33:05 +0000463 // Printf and scanf checking.
464 for (specific_attr_iterator<FormatAttr>
465 i = FDecl->specific_attr_begin<FormatAttr>(),
466 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000467 CheckFormatArguments(*i, TheCall);
Chris Lattner59907c42007-08-10 20:18:51 +0000468 }
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Ted Kremenekc82faca2010-09-09 04:33:05 +0000470 for (specific_attr_iterator<NonNullAttr>
471 i = FDecl->specific_attr_begin<NonNullAttr>(),
472 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +0000473 CheckNonNullArguments(*i, TheCall->getArgs(),
474 TheCall->getCallee()->getLocStart());
Ted Kremenekc82faca2010-09-09 04:33:05 +0000475 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000476
Anna Zaks0a151a12012-01-17 00:37:07 +0000477 unsigned CMId = FDecl->getMemoryFunctionKind();
478 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000479 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000480
Anna Zaksd9b859a2012-01-13 21:52:01 +0000481 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000482 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000483 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000484 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000485 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000486
Anders Carlssond406bf02009-08-16 01:56:34 +0000487 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000488}
489
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000490bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
491 Expr **Args, unsigned NumArgs) {
492 for (specific_attr_iterator<FormatAttr>
493 i = Method->specific_attr_begin<FormatAttr>(),
494 e = Method->specific_attr_end<FormatAttr>(); i != e ; ++i) {
495
496 CheckFormatArguments(*i, Args, NumArgs, false, lbrac,
497 Method->getSourceRange());
498 }
499
500 // diagnose nonnull arguments.
501 for (specific_attr_iterator<NonNullAttr>
502 i = Method->specific_attr_begin<NonNullAttr>(),
503 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
504 CheckNonNullArguments(*i, Args, lbrac);
505 }
506
507 return false;
508}
509
Anders Carlssond406bf02009-08-16 01:56:34 +0000510bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000511 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000512 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000513 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000514 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000516 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
517 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000518 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000519
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000520 QualType Ty = V->getType();
521 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000522 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000523
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000524 CheckFormatArguments(Format, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +0000525
526 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000527}
528
Eli Friedman276b0612011-10-11 02:20:01 +0000529ExprResult
530Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) {
531 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
532 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000533
534 // All these operations take one of the following four forms:
535 // T __atomic_load(_Atomic(T)*, int) (loads)
536 // T* __atomic_add(_Atomic(T*)*, ptrdiff_t, int) (pointer add/sub)
537 // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
538 // (cmpxchg)
539 // T __atomic_exchange(_Atomic(T)*, T, int) (everything else)
540 // where T is an appropriate type, and the int paremeterss are for orderings.
541 unsigned NumVals = 1;
542 unsigned NumOrders = 1;
543 if (Op == AtomicExpr::Load) {
544 NumVals = 0;
545 } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) {
546 NumVals = 2;
547 NumOrders = 2;
548 }
David Chisnall7a7ee302012-01-16 17:27:18 +0000549 if (Op == AtomicExpr::Init)
550 NumOrders = 0;
Eli Friedman276b0612011-10-11 02:20:01 +0000551
552 if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
553 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
554 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
555 << TheCall->getCallee()->getSourceRange();
556 return ExprError();
557 } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
558 Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
559 diag::err_typecheck_call_too_many_args)
560 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
561 << TheCall->getCallee()->getSourceRange();
562 return ExprError();
563 }
564
565 // Inspect the first argument of the atomic operation. This should always be
566 // a pointer to an _Atomic type.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000567 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000568 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
569 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
570 if (!pointerType) {
571 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
572 << Ptr->getType() << Ptr->getSourceRange();
573 return ExprError();
574 }
575
576 QualType AtomTy = pointerType->getPointeeType();
577 if (!AtomTy->isAtomicType()) {
578 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
579 << Ptr->getType() << Ptr->getSourceRange();
580 return ExprError();
581 }
582 QualType ValType = AtomTy->getAs<AtomicType>()->getValueType();
583
584 if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) &&
585 !ValType->isIntegerType() && !ValType->isPointerType()) {
586 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
587 << Ptr->getType() << Ptr->getSourceRange();
588 return ExprError();
589 }
590
591 if (!ValType->isIntegerType() &&
592 (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){
593 Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
594 << Ptr->getType() << Ptr->getSourceRange();
595 return ExprError();
596 }
597
598 switch (ValType.getObjCLifetime()) {
599 case Qualifiers::OCL_None:
600 case Qualifiers::OCL_ExplicitNone:
601 // okay
602 break;
603
604 case Qualifiers::OCL_Weak:
605 case Qualifiers::OCL_Strong:
606 case Qualifiers::OCL_Autoreleasing:
607 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
608 << ValType << Ptr->getSourceRange();
609 return ExprError();
610 }
611
612 QualType ResultType = ValType;
David Chisnall7a7ee302012-01-16 17:27:18 +0000613 if (Op == AtomicExpr::Store || Op == AtomicExpr::Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000614 ResultType = Context.VoidTy;
615 else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong)
616 ResultType = Context.BoolTy;
617
618 // The first argument --- the pointer --- has a fixed type; we
619 // deduce the types of the rest of the arguments accordingly. Walk
620 // the remaining arguments, converting them to the deduced value type.
621 for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) {
622 ExprResult Arg = TheCall->getArg(i);
623 QualType Ty;
624 if (i < NumVals+1) {
625 // The second argument to a cmpxchg is a pointer to the data which will
626 // be exchanged. The second argument to a pointer add/subtract is the
627 // amount to add/subtract, which must be a ptrdiff_t. The third
628 // argument to a cmpxchg and the second argument in all other cases
629 // is the type of the value.
630 if (i == 1 && (Op == AtomicExpr::CmpXchgWeak ||
631 Op == AtomicExpr::CmpXchgStrong))
632 Ty = Context.getPointerType(ValType.getUnqualifiedType());
633 else if (!ValType->isIntegerType() &&
634 (Op == AtomicExpr::Add || Op == AtomicExpr::Sub))
635 Ty = Context.getPointerDiffType();
636 else
637 Ty = ValType;
638 } else {
639 // The order(s) are always converted to int.
640 Ty = Context.IntTy;
641 }
642 InitializedEntity Entity =
643 InitializedEntity::InitializeParameter(Context, Ty, false);
644 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
645 if (Arg.isInvalid())
646 return true;
647 TheCall->setArg(i, Arg.get());
648 }
649
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000650 SmallVector<Expr*, 5> SubExprs;
651 SubExprs.push_back(Ptr);
Eli Friedman276b0612011-10-11 02:20:01 +0000652 if (Op == AtomicExpr::Load) {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000653 SubExprs.push_back(TheCall->getArg(1)); // Order
David Chisnall7a7ee302012-01-16 17:27:18 +0000654 } else if (Op == AtomicExpr::Init) {
655 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman276b0612011-10-11 02:20:01 +0000656 } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000657 SubExprs.push_back(TheCall->getArg(2)); // Order
658 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman276b0612011-10-11 02:20:01 +0000659 } else {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000660 SubExprs.push_back(TheCall->getArg(3)); // Order
661 SubExprs.push_back(TheCall->getArg(1)); // Val1
662 SubExprs.push_back(TheCall->getArg(2)); // Val2
663 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
Eli Friedman276b0612011-10-11 02:20:01 +0000664 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000665
666 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
667 SubExprs.data(), SubExprs.size(),
668 ResultType, Op,
669 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000670}
671
672
John McCall5f8d6042011-08-27 01:09:30 +0000673/// checkBuiltinArgument - Given a call to a builtin function, perform
674/// normal type-checking on the given argument, updating the call in
675/// place. This is useful when a builtin function requires custom
676/// type-checking for some of its arguments but not necessarily all of
677/// them.
678///
679/// Returns true on error.
680static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
681 FunctionDecl *Fn = E->getDirectCallee();
682 assert(Fn && "builtin call without direct callee!");
683
684 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
685 InitializedEntity Entity =
686 InitializedEntity::InitializeParameter(S.Context, Param);
687
688 ExprResult Arg = E->getArg(0);
689 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
690 if (Arg.isInvalid())
691 return true;
692
693 E->setArg(ArgIndex, Arg.take());
694 return false;
695}
696
Chris Lattner5caa3702009-05-08 06:58:22 +0000697/// SemaBuiltinAtomicOverloaded - We have a call to a function like
698/// __sync_fetch_and_add, which is an overloaded function based on the pointer
699/// type of its first argument. The main ActOnCallExpr routines have already
700/// promoted the types of arguments because all of these calls are prototyped as
701/// void(...).
702///
703/// This function goes through and does final semantic checking for these
704/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000705ExprResult
706Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000707 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000708 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
709 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
710
711 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000712 if (TheCall->getNumArgs() < 1) {
713 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
714 << 0 << 1 << TheCall->getNumArgs()
715 << TheCall->getCallee()->getSourceRange();
716 return ExprError();
717 }
Mike Stump1eb44332009-09-09 15:08:12 +0000718
Chris Lattner5caa3702009-05-08 06:58:22 +0000719 // Inspect the first argument of the atomic builtin. This should always be
720 // a pointer type, whose element is an integral scalar or pointer type.
721 // Because it is a pointer type, we don't have to worry about any implicit
722 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000723 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000724 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +0000725 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
726 if (FirstArgResult.isInvalid())
727 return ExprError();
728 FirstArg = FirstArgResult.take();
729 TheCall->setArg(0, FirstArg);
730
John McCallf85e1932011-06-15 23:02:42 +0000731 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
732 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000733 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
734 << FirstArg->getType() << FirstArg->getSourceRange();
735 return ExprError();
736 }
Mike Stump1eb44332009-09-09 15:08:12 +0000737
John McCallf85e1932011-06-15 23:02:42 +0000738 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000739 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000740 !ValType->isBlockPointerType()) {
741 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
742 << FirstArg->getType() << FirstArg->getSourceRange();
743 return ExprError();
744 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000745
John McCallf85e1932011-06-15 23:02:42 +0000746 switch (ValType.getObjCLifetime()) {
747 case Qualifiers::OCL_None:
748 case Qualifiers::OCL_ExplicitNone:
749 // okay
750 break;
751
752 case Qualifiers::OCL_Weak:
753 case Qualifiers::OCL_Strong:
754 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000755 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000756 << ValType << FirstArg->getSourceRange();
757 return ExprError();
758 }
759
John McCallb45ae252011-10-05 07:41:44 +0000760 // Strip any qualifiers off ValType.
761 ValType = ValType.getUnqualifiedType();
762
Chandler Carruth8d13d222010-07-18 20:54:12 +0000763 // The majority of builtins return a value, but a few have special return
764 // types, so allow them to override appropriately below.
765 QualType ResultType = ValType;
766
Chris Lattner5caa3702009-05-08 06:58:22 +0000767 // We need to figure out which concrete builtin this maps onto. For example,
768 // __sync_fetch_and_add with a 2 byte object turns into
769 // __sync_fetch_and_add_2.
770#define BUILTIN_ROW(x) \
771 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
772 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000773
Chris Lattner5caa3702009-05-08 06:58:22 +0000774 static const unsigned BuiltinIndices[][5] = {
775 BUILTIN_ROW(__sync_fetch_and_add),
776 BUILTIN_ROW(__sync_fetch_and_sub),
777 BUILTIN_ROW(__sync_fetch_and_or),
778 BUILTIN_ROW(__sync_fetch_and_and),
779 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000780
Chris Lattner5caa3702009-05-08 06:58:22 +0000781 BUILTIN_ROW(__sync_add_and_fetch),
782 BUILTIN_ROW(__sync_sub_and_fetch),
783 BUILTIN_ROW(__sync_and_and_fetch),
784 BUILTIN_ROW(__sync_or_and_fetch),
785 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000786
Chris Lattner5caa3702009-05-08 06:58:22 +0000787 BUILTIN_ROW(__sync_val_compare_and_swap),
788 BUILTIN_ROW(__sync_bool_compare_and_swap),
789 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000790 BUILTIN_ROW(__sync_lock_release),
791 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000792 };
Mike Stump1eb44332009-09-09 15:08:12 +0000793#undef BUILTIN_ROW
794
Chris Lattner5caa3702009-05-08 06:58:22 +0000795 // Determine the index of the size.
796 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000797 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000798 case 1: SizeIndex = 0; break;
799 case 2: SizeIndex = 1; break;
800 case 4: SizeIndex = 2; break;
801 case 8: SizeIndex = 3; break;
802 case 16: SizeIndex = 4; break;
803 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000804 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
805 << FirstArg->getType() << FirstArg->getSourceRange();
806 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000807 }
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Chris Lattner5caa3702009-05-08 06:58:22 +0000809 // Each of these builtins has one pointer argument, followed by some number of
810 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
811 // that we ignore. Find out which row of BuiltinIndices to read from as well
812 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000813 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000814 unsigned BuiltinIndex, NumFixed = 1;
815 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000816 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +0000817 case Builtin::BI__sync_fetch_and_add:
818 case Builtin::BI__sync_fetch_and_add_1:
819 case Builtin::BI__sync_fetch_and_add_2:
820 case Builtin::BI__sync_fetch_and_add_4:
821 case Builtin::BI__sync_fetch_and_add_8:
822 case Builtin::BI__sync_fetch_and_add_16:
823 BuiltinIndex = 0;
824 break;
825
826 case Builtin::BI__sync_fetch_and_sub:
827 case Builtin::BI__sync_fetch_and_sub_1:
828 case Builtin::BI__sync_fetch_and_sub_2:
829 case Builtin::BI__sync_fetch_and_sub_4:
830 case Builtin::BI__sync_fetch_and_sub_8:
831 case Builtin::BI__sync_fetch_and_sub_16:
832 BuiltinIndex = 1;
833 break;
834
835 case Builtin::BI__sync_fetch_and_or:
836 case Builtin::BI__sync_fetch_and_or_1:
837 case Builtin::BI__sync_fetch_and_or_2:
838 case Builtin::BI__sync_fetch_and_or_4:
839 case Builtin::BI__sync_fetch_and_or_8:
840 case Builtin::BI__sync_fetch_and_or_16:
841 BuiltinIndex = 2;
842 break;
843
844 case Builtin::BI__sync_fetch_and_and:
845 case Builtin::BI__sync_fetch_and_and_1:
846 case Builtin::BI__sync_fetch_and_and_2:
847 case Builtin::BI__sync_fetch_and_and_4:
848 case Builtin::BI__sync_fetch_and_and_8:
849 case Builtin::BI__sync_fetch_and_and_16:
850 BuiltinIndex = 3;
851 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Douglas Gregora9766412011-11-28 16:30:08 +0000853 case Builtin::BI__sync_fetch_and_xor:
854 case Builtin::BI__sync_fetch_and_xor_1:
855 case Builtin::BI__sync_fetch_and_xor_2:
856 case Builtin::BI__sync_fetch_and_xor_4:
857 case Builtin::BI__sync_fetch_and_xor_8:
858 case Builtin::BI__sync_fetch_and_xor_16:
859 BuiltinIndex = 4;
860 break;
861
862 case Builtin::BI__sync_add_and_fetch:
863 case Builtin::BI__sync_add_and_fetch_1:
864 case Builtin::BI__sync_add_and_fetch_2:
865 case Builtin::BI__sync_add_and_fetch_4:
866 case Builtin::BI__sync_add_and_fetch_8:
867 case Builtin::BI__sync_add_and_fetch_16:
868 BuiltinIndex = 5;
869 break;
870
871 case Builtin::BI__sync_sub_and_fetch:
872 case Builtin::BI__sync_sub_and_fetch_1:
873 case Builtin::BI__sync_sub_and_fetch_2:
874 case Builtin::BI__sync_sub_and_fetch_4:
875 case Builtin::BI__sync_sub_and_fetch_8:
876 case Builtin::BI__sync_sub_and_fetch_16:
877 BuiltinIndex = 6;
878 break;
879
880 case Builtin::BI__sync_and_and_fetch:
881 case Builtin::BI__sync_and_and_fetch_1:
882 case Builtin::BI__sync_and_and_fetch_2:
883 case Builtin::BI__sync_and_and_fetch_4:
884 case Builtin::BI__sync_and_and_fetch_8:
885 case Builtin::BI__sync_and_and_fetch_16:
886 BuiltinIndex = 7;
887 break;
888
889 case Builtin::BI__sync_or_and_fetch:
890 case Builtin::BI__sync_or_and_fetch_1:
891 case Builtin::BI__sync_or_and_fetch_2:
892 case Builtin::BI__sync_or_and_fetch_4:
893 case Builtin::BI__sync_or_and_fetch_8:
894 case Builtin::BI__sync_or_and_fetch_16:
895 BuiltinIndex = 8;
896 break;
897
898 case Builtin::BI__sync_xor_and_fetch:
899 case Builtin::BI__sync_xor_and_fetch_1:
900 case Builtin::BI__sync_xor_and_fetch_2:
901 case Builtin::BI__sync_xor_and_fetch_4:
902 case Builtin::BI__sync_xor_and_fetch_8:
903 case Builtin::BI__sync_xor_and_fetch_16:
904 BuiltinIndex = 9;
905 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000906
Chris Lattner5caa3702009-05-08 06:58:22 +0000907 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000908 case Builtin::BI__sync_val_compare_and_swap_1:
909 case Builtin::BI__sync_val_compare_and_swap_2:
910 case Builtin::BI__sync_val_compare_and_swap_4:
911 case Builtin::BI__sync_val_compare_and_swap_8:
912 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000913 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000914 NumFixed = 2;
915 break;
Douglas Gregora9766412011-11-28 16:30:08 +0000916
Chris Lattner5caa3702009-05-08 06:58:22 +0000917 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000918 case Builtin::BI__sync_bool_compare_and_swap_1:
919 case Builtin::BI__sync_bool_compare_and_swap_2:
920 case Builtin::BI__sync_bool_compare_and_swap_4:
921 case Builtin::BI__sync_bool_compare_and_swap_8:
922 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000923 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000924 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000925 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000926 break;
Douglas Gregora9766412011-11-28 16:30:08 +0000927
928 case Builtin::BI__sync_lock_test_and_set:
929 case Builtin::BI__sync_lock_test_and_set_1:
930 case Builtin::BI__sync_lock_test_and_set_2:
931 case Builtin::BI__sync_lock_test_and_set_4:
932 case Builtin::BI__sync_lock_test_and_set_8:
933 case Builtin::BI__sync_lock_test_and_set_16:
934 BuiltinIndex = 12;
935 break;
936
Chris Lattner5caa3702009-05-08 06:58:22 +0000937 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000938 case Builtin::BI__sync_lock_release_1:
939 case Builtin::BI__sync_lock_release_2:
940 case Builtin::BI__sync_lock_release_4:
941 case Builtin::BI__sync_lock_release_8:
942 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000943 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000944 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000945 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000946 break;
Douglas Gregora9766412011-11-28 16:30:08 +0000947
948 case Builtin::BI__sync_swap:
949 case Builtin::BI__sync_swap_1:
950 case Builtin::BI__sync_swap_2:
951 case Builtin::BI__sync_swap_4:
952 case Builtin::BI__sync_swap_8:
953 case Builtin::BI__sync_swap_16:
954 BuiltinIndex = 14;
955 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000956 }
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Chris Lattner5caa3702009-05-08 06:58:22 +0000958 // Now that we know how many fixed arguments we expect, first check that we
959 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000960 if (TheCall->getNumArgs() < 1+NumFixed) {
961 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
962 << 0 << 1+NumFixed << TheCall->getNumArgs()
963 << TheCall->getCallee()->getSourceRange();
964 return ExprError();
965 }
Mike Stump1eb44332009-09-09 15:08:12 +0000966
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000967 // Get the decl for the concrete builtin from this, we can tell what the
968 // concrete integer type we should convert to is.
969 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
970 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
971 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000972 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000973 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
974 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000975
John McCallf871d0c2010-08-07 06:22:56 +0000976 // The first argument --- the pointer --- has a fixed type; we
977 // deduce the types of the rest of the arguments accordingly. Walk
978 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000979 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +0000980 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000981
Chris Lattner5caa3702009-05-08 06:58:22 +0000982 // GCC does an implicit conversion to the pointer or integer ValType. This
983 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +0000984 // Initialize the argument.
985 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
986 ValType, /*consume*/ false);
987 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +0000988 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +0000989 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000990
Chris Lattner5caa3702009-05-08 06:58:22 +0000991 // Okay, we have something that *can* be converted to the right type. Check
992 // to see if there is a potentially weird extension going on here. This can
993 // happen when you do an atomic operation on something like an char* and
994 // pass in 42. The 42 gets converted to char. This is even more strange
995 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000996 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +0000997 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +0000998 }
Mike Stump1eb44332009-09-09 15:08:12 +0000999
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001000 ASTContext& Context = this->getASTContext();
1001
1002 // Create a new DeclRefExpr to refer to the new decl.
1003 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1004 Context,
1005 DRE->getQualifierLoc(),
1006 NewBuiltinDecl,
1007 DRE->getLocation(),
1008 NewBuiltinDecl->getType(),
1009 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001010
Chris Lattner5caa3702009-05-08 06:58:22 +00001011 // Set the callee in the CallExpr.
1012 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001013 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley429bb272011-04-08 18:41:53 +00001014 if (PromotedCall.isInvalid())
1015 return ExprError();
1016 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001017
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001018 // Change the result type of the call to match the original value type. This
1019 // is arbitrary, but the codegen for these builtins ins design to handle it
1020 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001021 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001022
1023 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +00001024}
1025
Chris Lattner69039812009-02-18 06:01:06 +00001026/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001027/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001028/// Note: It might also make sense to do the UTF-16 conversion here (would
1029/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001030bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001031 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001032 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1033
Douglas Gregor5cee1192011-07-27 05:40:30 +00001034 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001035 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1036 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001037 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001038 }
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001040 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001041 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001042 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001043 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001044 const UTF8 *FromPtr = (UTF8 *)String.data();
1045 UTF16 *ToPtr = &ToBuf[0];
1046
1047 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1048 &ToPtr, ToPtr + NumBytes,
1049 strictConversion);
1050 // Check for conversion failure.
1051 if (Result != conversionOK)
1052 Diag(Arg->getLocStart(),
1053 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1054 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001055 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001056}
1057
Chris Lattnerc27c6652007-12-20 00:05:45 +00001058/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1059/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001060bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1061 Expr *Fn = TheCall->getCallee();
1062 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001063 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001064 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001065 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1066 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001067 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001068 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001069 return true;
1070 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001071
1072 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001073 return Diag(TheCall->getLocEnd(),
1074 diag::err_typecheck_call_too_few_args_at_least)
1075 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001076 }
1077
John McCall5f8d6042011-08-27 01:09:30 +00001078 // Type-check the first argument normally.
1079 if (checkBuiltinArgument(*this, TheCall, 0))
1080 return true;
1081
Chris Lattnerc27c6652007-12-20 00:05:45 +00001082 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001083 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001084 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001085 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001086 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001087 else if (FunctionDecl *FD = getCurFunctionDecl())
1088 isVariadic = FD->isVariadic();
1089 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001090 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001091
Chris Lattnerc27c6652007-12-20 00:05:45 +00001092 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001093 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1094 return true;
1095 }
Mike Stump1eb44332009-09-09 15:08:12 +00001096
Chris Lattner30ce3442007-12-19 23:59:04 +00001097 // Verify that the second argument to the builtin is the last argument of the
1098 // current function or method.
1099 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001100 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001101
Anders Carlsson88cf2262008-02-11 04:20:54 +00001102 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1103 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001104 // FIXME: This isn't correct for methods (results in bogus warning).
1105 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001106 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001107 if (CurBlock)
1108 LastArg = *(CurBlock->TheDecl->param_end()-1);
1109 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001110 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001111 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001112 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001113 SecondArgIsLastNamedArgument = PV == LastArg;
1114 }
1115 }
Mike Stump1eb44332009-09-09 15:08:12 +00001116
Chris Lattner30ce3442007-12-19 23:59:04 +00001117 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001118 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001119 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1120 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001121}
Chris Lattner30ce3442007-12-19 23:59:04 +00001122
Chris Lattner1b9a0792007-12-20 00:26:33 +00001123/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1124/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001125bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1126 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001127 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001128 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001129 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001130 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001131 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001132 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001133 << SourceRange(TheCall->getArg(2)->getLocStart(),
1134 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001135
John Wiegley429bb272011-04-08 18:41:53 +00001136 ExprResult OrigArg0 = TheCall->getArg(0);
1137 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001138
Chris Lattner1b9a0792007-12-20 00:26:33 +00001139 // Do standard promotions between the two arguments, returning their common
1140 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001141 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001142 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1143 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001144
1145 // Make sure any conversions are pushed back into the call; this is
1146 // type safe since unordered compare builtins are declared as "_Bool
1147 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001148 TheCall->setArg(0, OrigArg0.get());
1149 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001150
John Wiegley429bb272011-04-08 18:41:53 +00001151 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001152 return false;
1153
Chris Lattner1b9a0792007-12-20 00:26:33 +00001154 // If the common type isn't a real floating type, then the arguments were
1155 // invalid for this operation.
1156 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001157 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001158 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001159 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1160 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001161
Chris Lattner1b9a0792007-12-20 00:26:33 +00001162 return false;
1163}
1164
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001165/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1166/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001167/// to check everything. We expect the last argument to be a floating point
1168/// value.
1169bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1170 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001171 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001172 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001173 if (TheCall->getNumArgs() > NumArgs)
1174 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001175 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001176 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001177 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001178 (*(TheCall->arg_end()-1))->getLocEnd());
1179
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001180 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Eli Friedman9ac6f622009-08-31 20:06:00 +00001182 if (OrigArg->isTypeDependent())
1183 return false;
1184
Chris Lattner81368fb2010-05-06 05:50:07 +00001185 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001186 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001187 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001188 diag::err_typecheck_call_invalid_unary_fp)
1189 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001190
Chris Lattner81368fb2010-05-06 05:50:07 +00001191 // If this is an implicit conversion from float -> double, remove it.
1192 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1193 Expr *CastArg = Cast->getSubExpr();
1194 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1195 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1196 "promotion from float to double is the only expected cast here");
1197 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001198 TheCall->setArg(NumArgs-1, CastArg);
1199 OrigArg = CastArg;
1200 }
1201 }
1202
Eli Friedman9ac6f622009-08-31 20:06:00 +00001203 return false;
1204}
1205
Eli Friedmand38617c2008-05-14 19:38:39 +00001206/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1207// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001208ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001209 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001210 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001211 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001212 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001213 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001214
Nate Begeman37b6a572010-06-08 00:16:34 +00001215 // Determine which of the following types of shufflevector we're checking:
1216 // 1) unary, vector mask: (lhs, mask)
1217 // 2) binary, vector mask: (lhs, rhs, mask)
1218 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1219 QualType resType = TheCall->getArg(0)->getType();
1220 unsigned numElements = 0;
1221
Douglas Gregorcde01732009-05-19 22:10:17 +00001222 if (!TheCall->getArg(0)->isTypeDependent() &&
1223 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001224 QualType LHSType = TheCall->getArg(0)->getType();
1225 QualType RHSType = TheCall->getArg(1)->getType();
1226
1227 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001228 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001229 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001230 TheCall->getArg(1)->getLocEnd());
1231 return ExprError();
1232 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001233
1234 numElements = LHSType->getAs<VectorType>()->getNumElements();
1235 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001236
Nate Begeman37b6a572010-06-08 00:16:34 +00001237 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1238 // with mask. If so, verify that RHS is an integer vector type with the
1239 // same number of elts as lhs.
1240 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001241 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001242 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1243 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1244 << SourceRange(TheCall->getArg(1)->getLocStart(),
1245 TheCall->getArg(1)->getLocEnd());
1246 numResElements = numElements;
1247 }
1248 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001249 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001250 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001251 TheCall->getArg(1)->getLocEnd());
1252 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001253 } else if (numElements != numResElements) {
1254 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001255 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001256 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001257 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001258 }
1259
1260 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001261 if (TheCall->getArg(i)->isTypeDependent() ||
1262 TheCall->getArg(i)->isValueDependent())
1263 continue;
1264
Nate Begeman37b6a572010-06-08 00:16:34 +00001265 llvm::APSInt Result(32);
1266 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1267 return ExprError(Diag(TheCall->getLocStart(),
1268 diag::err_shufflevector_nonconstant_argument)
1269 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001270
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001271 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001272 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001273 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001274 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001275 }
1276
Chris Lattner5f9e2722011-07-23 10:55:15 +00001277 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001278
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001279 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001280 exprs.push_back(TheCall->getArg(i));
1281 TheCall->setArg(i, 0);
1282 }
1283
Nate Begemana88dc302009-08-12 02:10:25 +00001284 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +00001285 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001286 TheCall->getCallee()->getLocStart(),
1287 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001288}
Chris Lattner30ce3442007-12-19 23:59:04 +00001289
Daniel Dunbar4493f792008-07-21 22:59:13 +00001290/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1291// This is declared to take (const void*, ...) and can take two
1292// optional constant int args.
1293bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001294 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001295
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001296 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001297 return Diag(TheCall->getLocEnd(),
1298 diag::err_typecheck_call_too_many_args_at_most)
1299 << 0 /*function call*/ << 3 << NumArgs
1300 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001301
1302 // Argument 0 is checked for us and the remaining arguments must be
1303 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001304 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001305 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +00001306
Eli Friedman9aef7262009-12-04 00:30:06 +00001307 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001308 if (SemaBuiltinConstantArg(TheCall, i, Result))
1309 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001310
Daniel Dunbar4493f792008-07-21 22:59:13 +00001311 // FIXME: gcc issues a warning and rewrites these to 0. These
1312 // seems especially odd for the third argument since the default
1313 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001314 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001315 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001316 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001317 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001318 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001319 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001320 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001321 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001322 }
1323 }
1324
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001325 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001326}
1327
Eric Christopher691ebc32010-04-17 02:26:23 +00001328/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1329/// TheCall is a constant expression.
1330bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1331 llvm::APSInt &Result) {
1332 Expr *Arg = TheCall->getArg(ArgNum);
1333 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1334 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1335
1336 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1337
1338 if (!Arg->isIntegerConstantExpr(Result, Context))
1339 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001340 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001341
Chris Lattner21fb98e2009-09-23 06:06:36 +00001342 return false;
1343}
1344
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001345/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1346/// int type). This simply type checks that type is one of the defined
1347/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001348// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001349bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001350 llvm::APSInt Result;
1351
1352 // Check constant-ness first.
1353 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1354 return true;
1355
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001356 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001357 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001358 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1359 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001360 }
1361
1362 return false;
1363}
1364
Eli Friedman586d6a82009-05-03 06:04:26 +00001365/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001366/// This checks that val is a constant 1.
1367bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1368 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001369 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001370
Eric Christopher691ebc32010-04-17 02:26:23 +00001371 // TODO: This is less than ideal. Overload this to take a value.
1372 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1373 return true;
1374
1375 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001376 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1377 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1378
1379 return false;
1380}
1381
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001382// Handle i > 1 ? "x" : "y", recursively.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001383bool Sema::SemaCheckStringLiteral(const Expr *E, Expr **Args,
1384 unsigned NumArgs, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001385 unsigned format_idx, unsigned firstDataArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001386 bool isPrintf, bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001387 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001388 if (E->isTypeDependent() || E->isValueDependent())
1389 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001390
Peter Collingbournef111d932011-04-15 00:35:48 +00001391 E = E->IgnoreParens();
1392
Ted Kremenekd30ef872009-01-12 23:09:09 +00001393 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001394 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001395 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +00001396 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001397 return SemaCheckStringLiteral(C->getTrueExpr(), Args, NumArgs, HasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001398 format_idx, firstDataArg, isPrintf,
1399 inFunctionCall)
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001400 && SemaCheckStringLiteral(C->getFalseExpr(), Args, NumArgs, HasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001401 format_idx, firstDataArg, isPrintf,
1402 inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001403 }
1404
Ted Kremenek95355bb2010-09-09 03:51:42 +00001405 case Stmt::IntegerLiteralClass:
1406 // Technically -Wformat-nonliteral does not warn about this case.
1407 // The behavior of printf and friends in this case is implementation
1408 // dependent. Ideally if the format string cannot be null then
1409 // it should have a 'nonnull' attribute in the function prototype.
1410 return true;
1411
Ted Kremenekd30ef872009-01-12 23:09:09 +00001412 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001413 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1414 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001415 }
1416
John McCall56ca35d2011-02-17 10:25:35 +00001417 case Stmt::OpaqueValueExprClass:
1418 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1419 E = src;
1420 goto tryAgain;
1421 }
1422 return false;
1423
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001424 case Stmt::PredefinedExprClass:
1425 // While __func__, etc., are technically not string literals, they
1426 // cannot contain format specifiers and thus are not a security
1427 // liability.
1428 return true;
1429
Ted Kremenek082d9362009-03-20 21:35:28 +00001430 case Stmt::DeclRefExprClass: {
1431 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001432
Ted Kremenek082d9362009-03-20 21:35:28 +00001433 // As an exception, do not flag errors for variables binding to
1434 // const string literals.
1435 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1436 bool isConstant = false;
1437 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001438
Ted Kremenek082d9362009-03-20 21:35:28 +00001439 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1440 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001441 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001442 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001443 PT->getPointeeType().isConstant(Context);
1444 }
Mike Stump1eb44332009-09-09 15:08:12 +00001445
Ted Kremenek082d9362009-03-20 21:35:28 +00001446 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001447 if (const Expr *Init = VD->getAnyInitializer())
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001448 return SemaCheckStringLiteral(Init, Args, NumArgs,
Ted Kremenek826a3452010-07-16 02:11:22 +00001449 HasVAListArg, format_idx, firstDataArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001450 isPrintf, /*inFunctionCall*/false);
Ted Kremenek082d9362009-03-20 21:35:28 +00001451 }
Mike Stump1eb44332009-09-09 15:08:12 +00001452
Anders Carlssond966a552009-06-28 19:55:58 +00001453 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1454 // special check to see if the format string is a function parameter
1455 // of the function calling the printf function. If the function
1456 // has an attribute indicating it is a printf-like function, then we
1457 // should suppress warnings concerning non-literals being used in a call
1458 // to a vprintf function. For example:
1459 //
1460 // void
1461 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1462 // va_list ap;
1463 // va_start(ap, fmt);
1464 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1465 // ...
1466 //
1467 //
1468 // FIXME: We don't have full attribute support yet, so just check to see
1469 // if the argument is a DeclRefExpr that references a parameter. We'll
1470 // add proper support for checking the attribute later.
1471 if (HasVAListArg)
1472 if (isa<ParmVarDecl>(VD))
1473 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +00001474 }
Mike Stump1eb44332009-09-09 15:08:12 +00001475
Ted Kremenek082d9362009-03-20 21:35:28 +00001476 return false;
1477 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001478
Anders Carlsson8f031b32009-06-27 04:05:33 +00001479 case Stmt::CallExprClass: {
1480 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001481 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +00001482 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1483 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1484 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001485 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001486 unsigned ArgIndex = FA->getFormatIdx();
1487 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001488
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001489 return SemaCheckStringLiteral(Arg, Args, NumArgs, HasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001490 format_idx, firstDataArg, isPrintf,
1491 inFunctionCall);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001492 }
1493 }
1494 }
1495 }
Mike Stump1eb44332009-09-09 15:08:12 +00001496
Anders Carlsson8f031b32009-06-27 04:05:33 +00001497 return false;
1498 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001499 case Stmt::ObjCStringLiteralClass:
1500 case Stmt::StringLiteralClass: {
1501 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001502
Ted Kremenek082d9362009-03-20 21:35:28 +00001503 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001504 StrE = ObjCFExpr->getString();
1505 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001506 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001507
Ted Kremenekd30ef872009-01-12 23:09:09 +00001508 if (StrE) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001509 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00001510 firstDataArg, isPrintf, inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001511 return true;
1512 }
Mike Stump1eb44332009-09-09 15:08:12 +00001513
Ted Kremenekd30ef872009-01-12 23:09:09 +00001514 return false;
1515 }
Mike Stump1eb44332009-09-09 15:08:12 +00001516
Ted Kremenek082d9362009-03-20 21:35:28 +00001517 default:
1518 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001519 }
1520}
1521
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001522void
Mike Stump1eb44332009-09-09 15:08:12 +00001523Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001524 const Expr * const *ExprArgs,
1525 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001526 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1527 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001528 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001529 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001530 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001531 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001532 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001533 }
1534}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001535
Ted Kremenek826a3452010-07-16 02:11:22 +00001536/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1537/// functions) for correct use of format strings.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001538void Sema::CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCall) {
1539 bool IsCXXMember = false;
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001540 // The way the format attribute works in GCC, the implicit this argument
1541 // of member functions is counted. However, it doesn't appear in our own
1542 // lists, so decrement format_idx in that case.
1543 if (isa<CXXMemberCallExpr>(TheCall)) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001544 const CXXMethodDecl *method_decl =
1545 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1546 IsCXXMember = method_decl && method_decl->isInstance();
1547 }
1548 CheckFormatArguments(Format, TheCall->getArgs(), TheCall->getNumArgs(),
1549 IsCXXMember, TheCall->getRParenLoc(),
1550 TheCall->getCallee()->getSourceRange());
1551}
1552
1553void Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
1554 unsigned NumArgs, bool IsCXXMember,
1555 SourceLocation Loc, SourceRange Range) {
1556 const bool b = Format->getType() == "scanf";
1557 if (b || CheckablePrintfAttr(Format, Args, NumArgs, IsCXXMember)) {
1558 bool HasVAListArg = Format->getFirstArg() == 0;
1559 unsigned format_idx = Format->getFormatIdx() - 1;
1560 unsigned firstDataArg = HasVAListArg ? 0 : Format->getFirstArg() - 1;
1561 if (IsCXXMember) {
Chandler Carruth9263a302010-11-16 08:49:43 +00001562 if (format_idx == 0)
1563 return;
1564 --format_idx;
1565 if(firstDataArg != 0)
1566 --firstDataArg;
1567 }
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001568 CheckPrintfScanfArguments(Args, NumArgs, HasVAListArg, format_idx,
1569 firstDataArg, !b, Loc, Range);
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001570 }
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001571}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001572
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001573void Sema::CheckPrintfScanfArguments(Expr **Args, unsigned NumArgs,
1574 bool HasVAListArg, unsigned format_idx,
1575 unsigned firstDataArg, bool isPrintf,
1576 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001577 // CHECK: printf/scanf-like function is called with no format string.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001578 if (format_idx >= NumArgs) {
1579 Diag(Loc, diag::warn_missing_format_string) << Range;
Ted Kremenek71895b92007-08-14 17:39:48 +00001580 return;
1581 }
Mike Stump1eb44332009-09-09 15:08:12 +00001582
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001583 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001584
Chris Lattner59907c42007-08-10 20:18:51 +00001585 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001586 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001587 // Dynamically generated format strings are difficult to
1588 // automatically vet at compile time. Requiring that format strings
1589 // are string literals: (1) permits the checking of format strings by
1590 // the compiler and thereby (2) can practically remove the source of
1591 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001592
Mike Stump1eb44332009-09-09 15:08:12 +00001593 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001594 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001595 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001596 // the same format string checking logic for both ObjC and C strings.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001597 if (SemaCheckStringLiteral(OrigFormatExpr, Args, NumArgs, HasVAListArg,
1598 format_idx, firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001599 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001600
Chris Lattner655f1412009-04-29 04:59:47 +00001601 // If there are no arguments specified, warn with -Wformat-security, otherwise
1602 // warn only with -Wformat-nonliteral.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001603 if (NumArgs == format_idx+1)
1604 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001605 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001606 << OrigFormatExpr->getSourceRange();
1607 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001608 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001609 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001610 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001611}
Ted Kremenek71895b92007-08-14 17:39:48 +00001612
Ted Kremeneke0e53132010-01-28 23:39:18 +00001613namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001614class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1615protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001616 Sema &S;
1617 const StringLiteral *FExpr;
1618 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001619 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001620 const unsigned NumDataArgs;
1621 const bool IsObjCLiteral;
1622 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001623 const bool HasVAListArg;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001624 const Expr * const *Args;
1625 const unsigned NumArgs;
Ted Kremenek0d277352010-01-29 01:06:55 +00001626 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001627 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001628 bool usesPositionalArgs;
1629 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001630 bool inFunctionCall;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001631public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001632 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001633 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001634 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001635 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001636 Expr **args, unsigned numArgs,
1637 unsigned formatIdx, bool inFunctionCall)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001638 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001639 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001640 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001641 IsObjCLiteral(isObjCLiteral), Beg(beg),
1642 HasVAListArg(hasVAListArg),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001643 Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001644 usesPositionalArgs(false), atFirstArg(true),
1645 inFunctionCall(inFunctionCall) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001646 CoveredArgs.resize(numDataArgs);
1647 CoveredArgs.reset();
1648 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001649
Ted Kremenek07d161f2010-01-29 01:50:07 +00001650 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001651
Ted Kremenek826a3452010-07-16 02:11:22 +00001652 void HandleIncompleteSpecifier(const char *startSpecifier,
1653 unsigned specifierLen);
1654
Ted Kremenekefaff192010-02-27 01:41:03 +00001655 virtual void HandleInvalidPosition(const char *startSpecifier,
1656 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001657 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001658
1659 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1660
Ted Kremeneke0e53132010-01-28 23:39:18 +00001661 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001662
Richard Trieu55733de2011-10-28 00:41:25 +00001663 template <typename Range>
1664 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1665 const Expr *ArgumentExpr,
1666 PartialDiagnostic PDiag,
1667 SourceLocation StringLoc,
1668 bool IsStringLocation, Range StringRange,
1669 FixItHint Fixit = FixItHint());
1670
Ted Kremenek826a3452010-07-16 02:11:22 +00001671protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001672 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1673 const char *startSpec,
1674 unsigned specifierLen,
1675 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00001676
1677 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1678 const char *startSpec,
1679 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001680
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001681 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001682 CharSourceRange getSpecifierRange(const char *startSpecifier,
1683 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001684 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001685
Ted Kremenek0d277352010-01-29 01:06:55 +00001686 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001687
1688 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1689 const analyze_format_string::ConversionSpecifier &CS,
1690 const char *startSpecifier, unsigned specifierLen,
1691 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00001692
1693 template <typename Range>
1694 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1695 bool IsStringLocation, Range StringRange,
1696 FixItHint Fixit = FixItHint());
1697
1698 void CheckPositionalAndNonpositionalArgs(
1699 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001700};
1701}
1702
Ted Kremenek826a3452010-07-16 02:11:22 +00001703SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001704 return OrigFormatExpr->getSourceRange();
1705}
1706
Ted Kremenek826a3452010-07-16 02:11:22 +00001707CharSourceRange CheckFormatHandler::
1708getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001709 SourceLocation Start = getLocationOfByte(startSpecifier);
1710 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1711
1712 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001713 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00001714
1715 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001716}
1717
Ted Kremenek826a3452010-07-16 02:11:22 +00001718SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001719 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001720}
1721
Ted Kremenek826a3452010-07-16 02:11:22 +00001722void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1723 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00001724 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
1725 getLocationOfByte(startSpecifier),
1726 /*IsStringLocation*/true,
1727 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00001728}
1729
Ted Kremenekefaff192010-02-27 01:41:03 +00001730void
Ted Kremenek826a3452010-07-16 02:11:22 +00001731CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1732 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00001733 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
1734 << (unsigned) p,
1735 getLocationOfByte(startPos), /*IsStringLocation*/true,
1736 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001737}
1738
Ted Kremenek826a3452010-07-16 02:11:22 +00001739void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001740 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00001741 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
1742 getLocationOfByte(startPos),
1743 /*IsStringLocation*/true,
1744 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001745}
1746
Ted Kremenek826a3452010-07-16 02:11:22 +00001747void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001748 if (!IsObjCLiteral) {
1749 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00001750 EmitFormatDiagnostic(
1751 S.PDiag(diag::warn_printf_format_string_contains_null_char),
1752 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
1753 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00001754 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001755}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001756
Ted Kremenek826a3452010-07-16 02:11:22 +00001757const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001758 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00001759}
1760
1761void CheckFormatHandler::DoneProcessing() {
1762 // Does the number of data arguments exceed the number of
1763 // format conversions in the format string?
1764 if (!HasVAListArg) {
1765 // Find any arguments that weren't covered.
1766 CoveredArgs.flip();
1767 signed notCoveredArg = CoveredArgs.find_first();
1768 if (notCoveredArg >= 0) {
1769 assert((unsigned)notCoveredArg < NumDataArgs);
Richard Trieu55733de2011-10-28 00:41:25 +00001770 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
1771 getDataArg((unsigned) notCoveredArg)->getLocStart(),
1772 /*IsStringLocation*/false, getFormatStringRange());
Ted Kremenek826a3452010-07-16 02:11:22 +00001773 }
1774 }
1775}
1776
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001777bool
1778CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1779 SourceLocation Loc,
1780 const char *startSpec,
1781 unsigned specifierLen,
1782 const char *csStart,
1783 unsigned csLen) {
1784
1785 bool keepGoing = true;
1786 if (argIndex < NumDataArgs) {
1787 // Consider the argument coverered, even though the specifier doesn't
1788 // make sense.
1789 CoveredArgs.set(argIndex);
1790 }
1791 else {
1792 // If argIndex exceeds the number of data arguments we
1793 // don't issue a warning because that is just a cascade of warnings (and
1794 // they may have intended '%%' anyway). We don't want to continue processing
1795 // the format string after this point, however, as we will like just get
1796 // gibberish when trying to match arguments.
1797 keepGoing = false;
1798 }
1799
Richard Trieu55733de2011-10-28 00:41:25 +00001800 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
1801 << StringRef(csStart, csLen),
1802 Loc, /*IsStringLocation*/true,
1803 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001804
1805 return keepGoing;
1806}
1807
Richard Trieu55733de2011-10-28 00:41:25 +00001808void
1809CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
1810 const char *startSpec,
1811 unsigned specifierLen) {
1812 EmitFormatDiagnostic(
1813 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
1814 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
1815}
1816
Ted Kremenek666a1972010-07-26 19:45:42 +00001817bool
1818CheckFormatHandler::CheckNumArgs(
1819 const analyze_format_string::FormatSpecifier &FS,
1820 const analyze_format_string::ConversionSpecifier &CS,
1821 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1822
1823 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00001824 PartialDiagnostic PDiag = FS.usesPositionalArg()
1825 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
1826 << (argIndex+1) << NumDataArgs)
1827 : S.PDiag(diag::warn_printf_insufficient_data_args);
1828 EmitFormatDiagnostic(
1829 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
1830 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00001831 return false;
1832 }
1833 return true;
1834}
1835
Richard Trieu55733de2011-10-28 00:41:25 +00001836template<typename Range>
1837void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
1838 SourceLocation Loc,
1839 bool IsStringLocation,
1840 Range StringRange,
1841 FixItHint FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001842 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00001843 Loc, IsStringLocation, StringRange, FixIt);
1844}
1845
1846/// \brief If the format string is not within the funcion call, emit a note
1847/// so that the function call and string are in diagnostic messages.
1848///
1849/// \param inFunctionCall if true, the format string is within the function
1850/// call and only one diagnostic message will be produced. Otherwise, an
1851/// extra note will be emitted pointing to location of the format string.
1852///
1853/// \param ArgumentExpr the expression that is passed as the format string
1854/// argument in the function call. Used for getting locations when two
1855/// diagnostics are emitted.
1856///
1857/// \param PDiag the callee should already have provided any strings for the
1858/// diagnostic message. This function only adds locations and fixits
1859/// to diagnostics.
1860///
1861/// \param Loc primary location for diagnostic. If two diagnostics are
1862/// required, one will be at Loc and a new SourceLocation will be created for
1863/// the other one.
1864///
1865/// \param IsStringLocation if true, Loc points to the format string should be
1866/// used for the note. Otherwise, Loc points to the argument list and will
1867/// be used with PDiag.
1868///
1869/// \param StringRange some or all of the string to highlight. This is
1870/// templated so it can accept either a CharSourceRange or a SourceRange.
1871///
1872/// \param Fixit optional fix it hint for the format string.
1873template<typename Range>
1874void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
1875 const Expr *ArgumentExpr,
1876 PartialDiagnostic PDiag,
1877 SourceLocation Loc,
1878 bool IsStringLocation,
1879 Range StringRange,
1880 FixItHint FixIt) {
1881 if (InFunctionCall)
1882 S.Diag(Loc, PDiag) << StringRange << FixIt;
1883 else {
1884 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
1885 << ArgumentExpr->getSourceRange();
1886 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
1887 diag::note_format_string_defined)
1888 << StringRange << FixIt;
1889 }
1890}
1891
Ted Kremenek826a3452010-07-16 02:11:22 +00001892//===--- CHECK: Printf format string checking ------------------------------===//
1893
1894namespace {
1895class CheckPrintfHandler : public CheckFormatHandler {
1896public:
1897 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1898 const Expr *origFormatExpr, unsigned firstDataArg,
1899 unsigned numDataArgs, bool isObjCLiteral,
1900 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001901 Expr **Args, unsigned NumArgs,
1902 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00001903 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1904 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001905 Args, NumArgs, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00001906
1907
1908 bool HandleInvalidPrintfConversionSpecifier(
1909 const analyze_printf::PrintfSpecifier &FS,
1910 const char *startSpecifier,
1911 unsigned specifierLen);
1912
1913 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1914 const char *startSpecifier,
1915 unsigned specifierLen);
1916
1917 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1918 const char *startSpecifier, unsigned specifierLen);
1919 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1920 const analyze_printf::OptionalAmount &Amt,
1921 unsigned type,
1922 const char *startSpecifier, unsigned specifierLen);
1923 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1924 const analyze_printf::OptionalFlag &flag,
1925 const char *startSpecifier, unsigned specifierLen);
1926 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1927 const analyze_printf::OptionalFlag &ignoredFlag,
1928 const analyze_printf::OptionalFlag &flag,
1929 const char *startSpecifier, unsigned specifierLen);
1930};
1931}
1932
1933bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1934 const analyze_printf::PrintfSpecifier &FS,
1935 const char *startSpecifier,
1936 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001937 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001938 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001939
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001940 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1941 getLocationOfByte(CS.getStart()),
1942 startSpecifier, specifierLen,
1943 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001944}
1945
Ted Kremenek826a3452010-07-16 02:11:22 +00001946bool CheckPrintfHandler::HandleAmount(
1947 const analyze_format_string::OptionalAmount &Amt,
1948 unsigned k, const char *startSpecifier,
1949 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001950
1951 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001952 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001953 unsigned argIndex = Amt.getArgIndex();
1954 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00001955 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
1956 << k,
1957 getLocationOfByte(Amt.getStart()),
1958 /*IsStringLocation*/true,
1959 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00001960 // Don't do any more checking. We will just emit
1961 // spurious errors.
1962 return false;
1963 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001964
Ted Kremenek0d277352010-01-29 01:06:55 +00001965 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001966 // Although not in conformance with C99, we also allow the argument to be
1967 // an 'unsigned int' as that is a reasonably safe case. GCC also
1968 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001969 CoveredArgs.set(argIndex);
1970 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001971 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001972
1973 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1974 assert(ATR.isValid());
1975
1976 if (!ATR.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00001977 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborga792aff2011-12-07 10:33:11 +00001978 << k << ATR.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00001979 << T << Arg->getSourceRange(),
1980 getLocationOfByte(Amt.getStart()),
1981 /*IsStringLocation*/true,
1982 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00001983 // Don't do any more checking. We will just emit
1984 // spurious errors.
1985 return false;
1986 }
1987 }
1988 }
1989 return true;
1990}
Ted Kremenek0d277352010-01-29 01:06:55 +00001991
Tom Caree4ee9662010-06-17 19:00:27 +00001992void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001993 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001994 const analyze_printf::OptionalAmount &Amt,
1995 unsigned type,
1996 const char *startSpecifier,
1997 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001998 const analyze_printf::PrintfConversionSpecifier &CS =
1999 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002000
Richard Trieu55733de2011-10-28 00:41:25 +00002001 FixItHint fixit =
2002 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2003 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2004 Amt.getConstantLength()))
2005 : FixItHint();
2006
2007 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2008 << type << CS.toString(),
2009 getLocationOfByte(Amt.getStart()),
2010 /*IsStringLocation*/true,
2011 getSpecifierRange(startSpecifier, specifierLen),
2012 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002013}
2014
Ted Kremenek826a3452010-07-16 02:11:22 +00002015void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002016 const analyze_printf::OptionalFlag &flag,
2017 const char *startSpecifier,
2018 unsigned specifierLen) {
2019 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002020 const analyze_printf::PrintfConversionSpecifier &CS =
2021 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002022 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2023 << flag.toString() << CS.toString(),
2024 getLocationOfByte(flag.getPosition()),
2025 /*IsStringLocation*/true,
2026 getSpecifierRange(startSpecifier, specifierLen),
2027 FixItHint::CreateRemoval(
2028 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002029}
2030
2031void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002032 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002033 const analyze_printf::OptionalFlag &ignoredFlag,
2034 const analyze_printf::OptionalFlag &flag,
2035 const char *startSpecifier,
2036 unsigned specifierLen) {
2037 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002038 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2039 << ignoredFlag.toString() << flag.toString(),
2040 getLocationOfByte(ignoredFlag.getPosition()),
2041 /*IsStringLocation*/true,
2042 getSpecifierRange(startSpecifier, specifierLen),
2043 FixItHint::CreateRemoval(
2044 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002045}
2046
Ted Kremeneke0e53132010-01-28 23:39:18 +00002047bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002048CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002049 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002050 const char *startSpecifier,
2051 unsigned specifierLen) {
2052
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002053 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002054 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002055 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002056
Ted Kremenekbaa40062010-07-19 22:01:06 +00002057 if (FS.consumesDataArgument()) {
2058 if (atFirstArg) {
2059 atFirstArg = false;
2060 usesPositionalArgs = FS.usesPositionalArg();
2061 }
2062 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002063 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2064 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002065 return false;
2066 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002067 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002068
Ted Kremenekefaff192010-02-27 01:41:03 +00002069 // First check if the field width, precision, and conversion specifier
2070 // have matching data arguments.
2071 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2072 startSpecifier, specifierLen)) {
2073 return false;
2074 }
2075
2076 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2077 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002078 return false;
2079 }
2080
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002081 if (!CS.consumesDataArgument()) {
2082 // FIXME: Technically specifying a precision or field width here
2083 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002084 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002085 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002086
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002087 // Consume the argument.
2088 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002089 if (argIndex < NumDataArgs) {
2090 // The check to see if the argIndex is valid will come later.
2091 // We set the bit here because we may exit early from this
2092 // function if we encounter some other error.
2093 CoveredArgs.set(argIndex);
2094 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002095
2096 // Check for using an Objective-C specific conversion specifier
2097 // in a non-ObjC literal.
2098 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002099 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2100 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002101 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002102
Tom Caree4ee9662010-06-17 19:00:27 +00002103 // Check for invalid use of field width
2104 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002105 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002106 startSpecifier, specifierLen);
2107 }
2108
2109 // Check for invalid use of precision
2110 if (!FS.hasValidPrecision()) {
2111 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2112 startSpecifier, specifierLen);
2113 }
2114
2115 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002116 if (!FS.hasValidThousandsGroupingPrefix())
2117 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002118 if (!FS.hasValidLeadingZeros())
2119 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2120 if (!FS.hasValidPlusPrefix())
2121 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002122 if (!FS.hasValidSpacePrefix())
2123 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002124 if (!FS.hasValidAlternativeForm())
2125 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2126 if (!FS.hasValidLeftJustified())
2127 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2128
2129 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002130 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2131 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2132 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002133 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2134 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2135 startSpecifier, specifierLen);
2136
2137 // Check the length modifier is valid with the given conversion specifier.
2138 const LengthModifier &LM = FS.getLengthModifier();
2139 if (!FS.hasValidLengthModifier())
Richard Trieu55733de2011-10-28 00:41:25 +00002140 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2141 << LM.toString() << CS.toString(),
2142 getLocationOfByte(LM.getStart()),
2143 /*IsStringLocation*/true,
2144 getSpecifierRange(startSpecifier, specifierLen),
2145 FixItHint::CreateRemoval(
2146 getSpecifierRange(LM.getStart(),
2147 LM.getLength())));
Tom Caree4ee9662010-06-17 19:00:27 +00002148
2149 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00002150 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00002151 // Issue a warning about this being a possible security issue.
Richard Trieu55733de2011-10-28 00:41:25 +00002152 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
2153 getLocationOfByte(CS.getStart()),
2154 /*IsStringLocation*/true,
2155 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremeneke82d8042010-01-29 01:35:25 +00002156 // Continue checking the other format specifiers.
2157 return true;
2158 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002159
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002160 // The remaining checks depend on the data arguments.
2161 if (HasVAListArg)
2162 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002163
Ted Kremenek666a1972010-07-26 19:45:42 +00002164 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002165 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002166
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002167 // Now type check the data expression that matches the
2168 // format specifier.
2169 const Expr *Ex = getDataArg(argIndex);
Nick Lewycky687b5df2011-12-02 23:21:43 +00002170 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002171 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2172 // Check if we didn't match because of an implicit cast from a 'char'
2173 // or 'short' to an 'int'. This is done because printf is a varargs
2174 // function.
2175 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002176 if (ICE->getType() == S.Context.IntTy) {
2177 // All further checking is done on the subexpression.
2178 Ex = ICE->getSubExpr();
2179 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002180 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002181 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002182
2183 // We may be able to offer a FixItHint if it is a supported type.
2184 PrintfSpecifier fixedFS = FS;
Hans Wennborga7da2152011-10-18 08:10:06 +00002185 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions());
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002186
2187 if (success) {
2188 // Get the fix string from the fixed format specifier
2189 llvm::SmallString<128> buf;
2190 llvm::raw_svector_ostream os(buf);
2191 fixedFS.toString(os);
2192
Richard Trieu55733de2011-10-28 00:41:25 +00002193 EmitFormatDiagnostic(
2194 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborga792aff2011-12-07 10:33:11 +00002195 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Richard Trieu55733de2011-10-28 00:41:25 +00002196 << Ex->getSourceRange(),
2197 getLocationOfByte(CS.getStart()),
2198 /*IsStringLocation*/true,
2199 getSpecifierRange(startSpecifier, specifierLen),
2200 FixItHint::CreateReplacement(
2201 getSpecifierRange(startSpecifier, specifierLen),
2202 os.str()));
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002203 }
2204 else {
2205 S.Diag(getLocationOfByte(CS.getStart()),
2206 diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborga792aff2011-12-07 10:33:11 +00002207 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002208 << getSpecifierRange(startSpecifier, specifierLen)
2209 << Ex->getSourceRange();
2210 }
2211 }
2212
Ted Kremeneke0e53132010-01-28 23:39:18 +00002213 return true;
2214}
2215
Ted Kremenek826a3452010-07-16 02:11:22 +00002216//===--- CHECK: Scanf format string checking ------------------------------===//
2217
2218namespace {
2219class CheckScanfHandler : public CheckFormatHandler {
2220public:
2221 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2222 const Expr *origFormatExpr, unsigned firstDataArg,
2223 unsigned numDataArgs, bool isObjCLiteral,
2224 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002225 Expr **Args, unsigned NumArgs,
2226 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00002227 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2228 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002229 Args, NumArgs, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002230
2231 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2232 const char *startSpecifier,
2233 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002234
2235 bool HandleInvalidScanfConversionSpecifier(
2236 const analyze_scanf::ScanfSpecifier &FS,
2237 const char *startSpecifier,
2238 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002239
2240 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002241};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002242}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002243
Ted Kremenekb7c21012010-07-16 18:28:03 +00002244void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2245 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002246 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2247 getLocationOfByte(end), /*IsStringLocation*/true,
2248 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002249}
2250
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002251bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2252 const analyze_scanf::ScanfSpecifier &FS,
2253 const char *startSpecifier,
2254 unsigned specifierLen) {
2255
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002256 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002257 FS.getConversionSpecifier();
2258
2259 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2260 getLocationOfByte(CS.getStart()),
2261 startSpecifier, specifierLen,
2262 CS.getStart(), CS.getLength());
2263}
2264
Ted Kremenek826a3452010-07-16 02:11:22 +00002265bool CheckScanfHandler::HandleScanfSpecifier(
2266 const analyze_scanf::ScanfSpecifier &FS,
2267 const char *startSpecifier,
2268 unsigned specifierLen) {
2269
2270 using namespace analyze_scanf;
2271 using namespace analyze_format_string;
2272
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002273 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002274
Ted Kremenekbaa40062010-07-19 22:01:06 +00002275 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2276 // be used to decide if we are using positional arguments consistently.
2277 if (FS.consumesDataArgument()) {
2278 if (atFirstArg) {
2279 atFirstArg = false;
2280 usesPositionalArgs = FS.usesPositionalArg();
2281 }
2282 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002283 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2284 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002285 return false;
2286 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002287 }
2288
2289 // Check if the field with is non-zero.
2290 const OptionalAmount &Amt = FS.getFieldWidth();
2291 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2292 if (Amt.getConstantAmount() == 0) {
2293 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2294 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00002295 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2296 getLocationOfByte(Amt.getStart()),
2297 /*IsStringLocation*/true, R,
2298 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00002299 }
2300 }
2301
2302 if (!FS.consumesDataArgument()) {
2303 // FIXME: Technically specifying a precision or field width here
2304 // makes no sense. Worth issuing a warning at some point.
2305 return true;
2306 }
2307
2308 // Consume the argument.
2309 unsigned argIndex = FS.getArgIndex();
2310 if (argIndex < NumDataArgs) {
2311 // The check to see if the argIndex is valid will come later.
2312 // We set the bit here because we may exit early from this
2313 // function if we encounter some other error.
2314 CoveredArgs.set(argIndex);
2315 }
2316
Ted Kremenek1e51c202010-07-20 20:04:47 +00002317 // Check the length modifier is valid with the given conversion specifier.
2318 const LengthModifier &LM = FS.getLengthModifier();
2319 if (!FS.hasValidLengthModifier()) {
2320 S.Diag(getLocationOfByte(LM.getStart()),
2321 diag::warn_format_nonsensical_length)
2322 << LM.toString() << CS.toString()
2323 << getSpecifierRange(startSpecifier, specifierLen)
2324 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
2325 LM.getLength()));
2326 }
2327
Ted Kremenek826a3452010-07-16 02:11:22 +00002328 // The remaining checks depend on the data arguments.
2329 if (HasVAListArg)
2330 return true;
2331
Ted Kremenek666a1972010-07-26 19:45:42 +00002332 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002333 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002334
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002335 // Check that the argument type matches the format specifier.
2336 const Expr *Ex = getDataArg(argIndex);
2337 const analyze_scanf::ScanfArgTypeResult &ATR = FS.getArgType(S.Context);
2338 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2339 ScanfSpecifier fixedFS = FS;
2340 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions());
2341
2342 if (success) {
2343 // Get the fix string from the fixed format specifier.
2344 llvm::SmallString<128> buf;
2345 llvm::raw_svector_ostream os(buf);
2346 fixedFS.toString(os);
2347
2348 EmitFormatDiagnostic(
2349 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2350 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2351 << Ex->getSourceRange(),
2352 getLocationOfByte(CS.getStart()),
2353 /*IsStringLocation*/true,
2354 getSpecifierRange(startSpecifier, specifierLen),
2355 FixItHint::CreateReplacement(
2356 getSpecifierRange(startSpecifier, specifierLen),
2357 os.str()));
2358 } else {
2359 S.Diag(getLocationOfByte(CS.getStart()),
2360 diag::warn_printf_conversion_argument_type_mismatch)
2361 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2362 << getSpecifierRange(startSpecifier, specifierLen)
2363 << Ex->getSourceRange();
2364 }
2365 }
2366
Ted Kremenek826a3452010-07-16 02:11:22 +00002367 return true;
2368}
2369
2370void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002371 const Expr *OrigFormatExpr,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002372 Expr **Args, unsigned NumArgs,
2373 bool HasVAListArg, unsigned format_idx,
2374 unsigned firstDataArg, bool isPrintf,
2375 bool inFunctionCall) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002376
Ted Kremeneke0e53132010-01-28 23:39:18 +00002377 // CHECK: is the format string a wide literal?
Douglas Gregor5cee1192011-07-27 05:40:30 +00002378 if (!FExpr->isAscii()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002379 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002380 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002381 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2382 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002383 return;
2384 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002385
Ted Kremeneke0e53132010-01-28 23:39:18 +00002386 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00002387 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002388 const char *Str = StrRef.data();
2389 unsigned StrLen = StrRef.size();
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002390 const unsigned numDataArgs = NumArgs - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00002391
Ted Kremeneke0e53132010-01-28 23:39:18 +00002392 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00002393 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00002394 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002395 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002396 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2397 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002398 return;
2399 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002400
2401 if (isPrintf) {
2402 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002403 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002404 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00002405 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002406
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002407 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
2408 getLangOptions()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002409 H.DoneProcessing();
2410 }
2411 else {
2412 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002413 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002414 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00002415 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002416
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002417 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
2418 getLangOptions()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002419 H.DoneProcessing();
2420 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00002421}
2422
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002423//===--- CHECK: Standard memory functions ---------------------------------===//
2424
Douglas Gregor2a053a32011-05-03 20:05:22 +00002425/// \brief Determine whether the given type is a dynamic class type (e.g.,
2426/// whether it has a vtable).
2427static bool isDynamicClassType(QualType T) {
2428 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2429 if (CXXRecordDecl *Definition = Record->getDefinition())
2430 if (Definition->isDynamicClass())
2431 return true;
2432
2433 return false;
2434}
2435
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002436/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00002437/// otherwise returns NULL.
2438static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00002439 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00002440 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2441 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2442 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002443
Chandler Carruth000d4282011-06-16 09:09:40 +00002444 return 0;
2445}
2446
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002447/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00002448static QualType getSizeOfArgType(const Expr* E) {
2449 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2450 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2451 if (SizeOf->getKind() == clang::UETT_SizeOf)
2452 return SizeOf->getTypeOfArgument();
2453
2454 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00002455}
2456
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002457/// \brief Check for dangerous or invalid arguments to memset().
2458///
Chandler Carruth929f0132011-06-03 06:23:57 +00002459/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002460/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2461/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002462///
2463/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002464void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00002465 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002466 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00002467 assert(BId != 0);
2468
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002469 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00002470 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00002471 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00002472 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002473 return;
2474
Anna Zaks0a151a12012-01-17 00:37:07 +00002475 unsigned LastArg = (BId == Builtin::BImemset ||
2476 BId == Builtin::BIstrndup ? 1 : 2);
2477 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00002478 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00002479
2480 // We have special checking when the length is a sizeof expression.
2481 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2482 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2483 llvm::FoldingSetNodeID SizeOfArgID;
2484
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002485 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2486 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002487 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002488
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002489 QualType DestTy = Dest->getType();
2490 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2491 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002492
Chandler Carruth000d4282011-06-16 09:09:40 +00002493 // Never warn about void type pointers. This can be used to suppress
2494 // false positives.
2495 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002496 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002497
Chandler Carruth000d4282011-06-16 09:09:40 +00002498 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2499 // actually comparing the expressions for equality. Because computing the
2500 // expression IDs can be expensive, we only do this if the diagnostic is
2501 // enabled.
2502 if (SizeOfArg &&
2503 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2504 SizeOfArg->getExprLoc())) {
2505 // We only compute IDs for expressions if the warning is enabled, and
2506 // cache the sizeof arg's ID.
2507 if (SizeOfArgID == llvm::FoldingSetNodeID())
2508 SizeOfArg->Profile(SizeOfArgID, Context, true);
2509 llvm::FoldingSetNodeID DestID;
2510 Dest->Profile(DestID, Context, true);
2511 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00002512 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2513 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00002514 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2515 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2516 if (UnaryOp->getOpcode() == UO_AddrOf)
2517 ActionIdx = 1; // If its an address-of operator, just remove it.
2518 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2519 ActionIdx = 2; // If the pointee's size is sizeof(char),
2520 // suggest an explicit length.
Anna Zaksd9b859a2012-01-13 21:52:01 +00002521 unsigned DestSrcSelect =
Anna Zaks0a151a12012-01-17 00:37:07 +00002522 (BId == Builtin::BIstrndup ? 1 : ArgIdx);
Chandler Carruth000d4282011-06-16 09:09:40 +00002523 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2524 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Nico Webercda57822011-10-13 22:30:23 +00002525 << FnName << DestSrcSelect << ActionIdx
Chandler Carruth000d4282011-06-16 09:09:40 +00002526 << Dest->getSourceRange()
2527 << SizeOfArg->getSourceRange());
2528 break;
2529 }
2530 }
2531
2532 // Also check for cases where the sizeof argument is the exact same
2533 // type as the memory argument, and where it points to a user-defined
2534 // record type.
2535 if (SizeOfArgTy != QualType()) {
2536 if (PointeeTy->isRecordType() &&
2537 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2538 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2539 PDiag(diag::warn_sizeof_pointer_type_memaccess)
2540 << FnName << SizeOfArgTy << ArgIdx
2541 << PointeeTy << Dest->getSourceRange()
2542 << LenExpr->getSourceRange());
2543 break;
2544 }
Nico Webere4a1c642011-06-14 16:14:58 +00002545 }
2546
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002547 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00002548 if (isDynamicClassType(PointeeTy)) {
2549
2550 unsigned OperationType = 0;
2551 // "overwritten" if we're warning about the destination for any call
2552 // but memcmp; otherwise a verb appropriate to the call.
2553 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
2554 if (BId == Builtin::BImemcpy)
2555 OperationType = 1;
2556 else if(BId == Builtin::BImemmove)
2557 OperationType = 2;
2558 else if (BId == Builtin::BImemcmp)
2559 OperationType = 3;
2560 }
2561
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002562 DiagRuntimeBehavior(
2563 Dest->getExprLoc(), Dest,
2564 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00002565 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00002566 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00002567 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002568 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00002569 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
2570 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002571 DiagRuntimeBehavior(
2572 Dest->getExprLoc(), Dest,
2573 PDiag(diag::warn_arc_object_memaccess)
2574 << ArgIdx << FnName << PointeeTy
2575 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00002576 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002577 continue;
John McCallf85e1932011-06-15 23:02:42 +00002578
2579 DiagRuntimeBehavior(
2580 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00002581 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002582 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2583 break;
2584 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002585 }
2586}
2587
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002588// A little helper routine: ignore addition and subtraction of integer literals.
2589// This intentionally does not ignore all integer constant expressions because
2590// we don't want to remove sizeof().
2591static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2592 Ex = Ex->IgnoreParenCasts();
2593
2594 for (;;) {
2595 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2596 if (!BO || !BO->isAdditiveOp())
2597 break;
2598
2599 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2600 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2601
2602 if (isa<IntegerLiteral>(RHS))
2603 Ex = LHS;
2604 else if (isa<IntegerLiteral>(LHS))
2605 Ex = RHS;
2606 else
2607 break;
2608 }
2609
2610 return Ex;
2611}
2612
2613// Warn if the user has made the 'size' argument to strlcpy or strlcat
2614// be the size of the source, instead of the destination.
2615void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2616 IdentifierInfo *FnName) {
2617
2618 // Don't crash if the user has the wrong number of arguments
2619 if (Call->getNumArgs() != 3)
2620 return;
2621
2622 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2623 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2624 const Expr *CompareWithSrc = NULL;
2625
2626 // Look for 'strlcpy(dst, x, sizeof(x))'
2627 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2628 CompareWithSrc = Ex;
2629 else {
2630 // Look for 'strlcpy(dst, x, strlen(x))'
2631 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00002632 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002633 && SizeCall->getNumArgs() == 1)
2634 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2635 }
2636 }
2637
2638 if (!CompareWithSrc)
2639 return;
2640
2641 // Determine if the argument to sizeof/strlen is equal to the source
2642 // argument. In principle there's all kinds of things you could do
2643 // here, for instance creating an == expression and evaluating it with
2644 // EvaluateAsBooleanCondition, but this uses a more direct technique:
2645 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2646 if (!SrcArgDRE)
2647 return;
2648
2649 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2650 if (!CompareWithSrcDRE ||
2651 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2652 return;
2653
2654 const Expr *OriginalSizeArg = Call->getArg(2);
2655 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2656 << OriginalSizeArg->getSourceRange() << FnName;
2657
2658 // Output a FIXIT hint if the destination is an array (rather than a
2659 // pointer to an array). This could be enhanced to handle some
2660 // pointers if we know the actual size, like if DstArg is 'array+2'
2661 // we could say 'sizeof(array)-2'.
2662 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek8f746222011-08-18 22:48:41 +00002663 QualType DstArgTy = DstArg->getType();
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002664
Ted Kremenek8f746222011-08-18 22:48:41 +00002665 // Only handle constant-sized or VLAs, but not flexible members.
2666 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2667 // Only issue the FIXIT for arrays of size > 1.
2668 if (CAT->getSize().getSExtValue() <= 1)
2669 return;
2670 } else if (!DstArgTy->isVariableArrayType()) {
2671 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002672 }
Ted Kremenek8f746222011-08-18 22:48:41 +00002673
2674 llvm::SmallString<128> sizeString;
2675 llvm::raw_svector_ostream OS(sizeString);
2676 OS << "sizeof(";
Douglas Gregor8987b232011-09-27 23:30:47 +00002677 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00002678 OS << ")";
2679
2680 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2681 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2682 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002683}
2684
Ted Kremenek06de2762007-08-17 16:46:58 +00002685//===--- CHECK: Return Address of Stack Variable --------------------------===//
2686
Chris Lattner5f9e2722011-07-23 10:55:15 +00002687static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2688static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002689
2690/// CheckReturnStackAddr - Check if a return statement returns the address
2691/// of a stack variable.
2692void
2693Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2694 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00002695
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002696 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002697 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002698
2699 // Perform checking for returned stack addresses, local blocks,
2700 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00002701 if (lhsType->isPointerType() ||
2702 (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002703 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002704 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002705 stackE = EvalVal(RetValExp, refVars);
2706 }
2707
2708 if (stackE == 0)
2709 return; // Nothing suspicious was found.
2710
2711 SourceLocation diagLoc;
2712 SourceRange diagRange;
2713 if (refVars.empty()) {
2714 diagLoc = stackE->getLocStart();
2715 diagRange = stackE->getSourceRange();
2716 } else {
2717 // We followed through a reference variable. 'stackE' contains the
2718 // problematic expression but we will warn at the return statement pointing
2719 // at the reference variable. We will later display the "trail" of
2720 // reference variables using notes.
2721 diagLoc = refVars[0]->getLocStart();
2722 diagRange = refVars[0]->getSourceRange();
2723 }
2724
2725 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2726 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2727 : diag::warn_ret_stack_addr)
2728 << DR->getDecl()->getDeclName() << diagRange;
2729 } else if (isa<BlockExpr>(stackE)) { // local block.
2730 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2731 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2732 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2733 } else { // local temporary.
2734 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2735 : diag::warn_ret_local_temp_addr)
2736 << diagRange;
2737 }
2738
2739 // Display the "trail" of reference variables that we followed until we
2740 // found the problematic expression using notes.
2741 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2742 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2743 // If this var binds to another reference var, show the range of the next
2744 // var, otherwise the var binds to the problematic expression, in which case
2745 // show the range of the expression.
2746 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2747 : stackE->getSourceRange();
2748 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2749 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00002750 }
2751}
2752
2753/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2754/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002755/// to a location on the stack, a local block, an address of a label, or a
2756/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00002757/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002758/// encounter a subexpression that (1) clearly does not lead to one of the
2759/// above problematic expressions (2) is something we cannot determine leads to
2760/// a problematic expression based on such local checking.
2761///
2762/// Both EvalAddr and EvalVal follow through reference variables to evaluate
2763/// the expression that they point to. Such variables are added to the
2764/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00002765///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002766/// EvalAddr processes expressions that are pointers that are used as
2767/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002768/// At the base case of the recursion is a check for the above problematic
2769/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00002770///
2771/// This implementation handles:
2772///
2773/// * pointer-to-pointer casts
2774/// * implicit conversions from array references to pointers
2775/// * taking the address of fields
2776/// * arbitrary interplay between "&" and "*" operators
2777/// * pointer arithmetic from an address of a stack variable
2778/// * taking the address of an array element where the array is on the stack
Chris Lattner5f9e2722011-07-23 10:55:15 +00002779static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002780 if (E->isTypeDependent())
2781 return NULL;
2782
Ted Kremenek06de2762007-08-17 16:46:58 +00002783 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00002784 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00002785 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002786 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002787 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00002788
Peter Collingbournef111d932011-04-15 00:35:48 +00002789 E = E->IgnoreParens();
2790
Ted Kremenek06de2762007-08-17 16:46:58 +00002791 // Our "symbolic interpreter" is just a dispatch off the currently
2792 // viewed AST node. We then recursively traverse the AST by calling
2793 // EvalAddr and EvalVal appropriately.
2794 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002795 case Stmt::DeclRefExprClass: {
2796 DeclRefExpr *DR = cast<DeclRefExpr>(E);
2797
2798 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2799 // If this is a reference variable, follow through to the expression that
2800 // it points to.
2801 if (V->hasLocalStorage() &&
2802 V->getType()->isReferenceType() && V->hasInit()) {
2803 // Add the reference variable to the "trail".
2804 refVars.push_back(DR);
2805 return EvalAddr(V->getInit(), refVars);
2806 }
2807
2808 return NULL;
2809 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002810
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002811 case Stmt::UnaryOperatorClass: {
2812 // The only unary operator that make sense to handle here
2813 // is AddrOf. All others don't make sense as pointers.
2814 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002815
John McCall2de56d12010-08-25 11:45:40 +00002816 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002817 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002818 else
Ted Kremenek06de2762007-08-17 16:46:58 +00002819 return NULL;
2820 }
Mike Stump1eb44332009-09-09 15:08:12 +00002821
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002822 case Stmt::BinaryOperatorClass: {
2823 // Handle pointer arithmetic. All other binary operators are not valid
2824 // in this context.
2825 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00002826 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00002827
John McCall2de56d12010-08-25 11:45:40 +00002828 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002829 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002830
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002831 Expr *Base = B->getLHS();
2832
2833 // Determine which argument is the real pointer base. It could be
2834 // the RHS argument instead of the LHS.
2835 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00002836
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002837 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002838 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002839 }
Steve Naroff61f40a22008-09-10 19:17:48 +00002840
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002841 // For conditional operators we need to see if either the LHS or RHS are
2842 // valid DeclRefExpr*s. If one of them is valid, we return it.
2843 case Stmt::ConditionalOperatorClass: {
2844 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002845
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002846 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002847 if (Expr *lhsExpr = C->getLHS()) {
2848 // In C++, we can have a throw-expression, which has 'void' type.
2849 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002850 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002851 return LHS;
2852 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002853
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002854 // In C++, we can have a throw-expression, which has 'void' type.
2855 if (C->getRHS()->getType()->isVoidType())
2856 return NULL;
2857
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002858 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002859 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002860
2861 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00002862 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002863 return E; // local block.
2864 return NULL;
2865
2866 case Stmt::AddrLabelExprClass:
2867 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00002868
John McCall80ee6e82011-11-10 05:35:25 +00002869 case Stmt::ExprWithCleanupsClass:
2870 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
2871
Ted Kremenek54b52742008-08-07 00:49:01 +00002872 // For casts, we need to handle conversions from arrays to
2873 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00002874 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002875 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002876 case Stmt::CXXFunctionalCastExprClass:
2877 case Stmt::ObjCBridgedCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002878 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00002879 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002880
Steve Naroffdd972f22008-09-05 22:11:13 +00002881 if (SubExpr->getType()->isPointerType() ||
2882 SubExpr->getType()->isBlockPointerType() ||
2883 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002884 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00002885 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002886 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002887 else
Ted Kremenek54b52742008-08-07 00:49:01 +00002888 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002889 }
Mike Stump1eb44332009-09-09 15:08:12 +00002890
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002891 // C++ casts. For dynamic casts, static casts, and const casts, we
2892 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00002893 // through the cast. In the case the dynamic cast doesn't fail (and
2894 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002895 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00002896 // FIXME: The comment about is wrong; we're not always converting
2897 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00002898 // handle references to objects.
2899 case Stmt::CXXStaticCastExprClass:
2900 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002901 case Stmt::CXXConstCastExprClass:
2902 case Stmt::CXXReinterpretCastExprClass: {
2903 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00002904 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002905 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002906 else
2907 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002908 }
Mike Stump1eb44332009-09-09 15:08:12 +00002909
Douglas Gregor03e80032011-06-21 17:03:29 +00002910 case Stmt::MaterializeTemporaryExprClass:
2911 if (Expr *Result = EvalAddr(
2912 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2913 refVars))
2914 return Result;
2915
2916 return E;
2917
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002918 // Everything else: we simply don't reason about them.
2919 default:
2920 return NULL;
2921 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002922}
Mike Stump1eb44332009-09-09 15:08:12 +00002923
Ted Kremenek06de2762007-08-17 16:46:58 +00002924
2925/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2926/// See the comments for EvalAddr for more details.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002927static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002928do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002929 // We should only be called for evaluating non-pointer expressions, or
2930 // expressions with a pointer type that are not used as references but instead
2931 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002932
Ted Kremenek06de2762007-08-17 16:46:58 +00002933 // Our "symbolic interpreter" is just a dispatch off the currently
2934 // viewed AST node. We then recursively traverse the AST by calling
2935 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00002936
2937 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00002938 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002939 case Stmt::ImplicitCastExprClass: {
2940 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002941 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002942 E = IE->getSubExpr();
2943 continue;
2944 }
2945 return NULL;
2946 }
2947
John McCall80ee6e82011-11-10 05:35:25 +00002948 case Stmt::ExprWithCleanupsClass:
2949 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
2950
Douglas Gregora2813ce2009-10-23 18:54:35 +00002951 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002952 // When we hit a DeclRefExpr we are looking at code that refers to a
2953 // variable's name. If it's not a reference variable we check if it has
2954 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00002955 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002956
Ted Kremenek06de2762007-08-17 16:46:58 +00002957 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002958 if (V->hasLocalStorage()) {
2959 if (!V->getType()->isReferenceType())
2960 return DR;
2961
2962 // Reference variable, follow through to the expression that
2963 // it points to.
2964 if (V->hasInit()) {
2965 // Add the reference variable to the "trail".
2966 refVars.push_back(DR);
2967 return EvalVal(V->getInit(), refVars);
2968 }
2969 }
Mike Stump1eb44332009-09-09 15:08:12 +00002970
Ted Kremenek06de2762007-08-17 16:46:58 +00002971 return NULL;
2972 }
Mike Stump1eb44332009-09-09 15:08:12 +00002973
Ted Kremenek06de2762007-08-17 16:46:58 +00002974 case Stmt::UnaryOperatorClass: {
2975 // The only unary operator that make sense to handle here
2976 // is Deref. All others don't resolve to a "name." This includes
2977 // handling all sorts of rvalues passed to a unary operator.
2978 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002979
John McCall2de56d12010-08-25 11:45:40 +00002980 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002981 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002982
2983 return NULL;
2984 }
Mike Stump1eb44332009-09-09 15:08:12 +00002985
Ted Kremenek06de2762007-08-17 16:46:58 +00002986 case Stmt::ArraySubscriptExprClass: {
2987 // Array subscripts are potential references to data on the stack. We
2988 // retrieve the DeclRefExpr* for the array variable if it indeed
2989 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002990 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002991 }
Mike Stump1eb44332009-09-09 15:08:12 +00002992
Ted Kremenek06de2762007-08-17 16:46:58 +00002993 case Stmt::ConditionalOperatorClass: {
2994 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002995 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00002996 ConditionalOperator *C = cast<ConditionalOperator>(E);
2997
Anders Carlsson39073232007-11-30 19:04:31 +00002998 // Handle the GNU extension for missing LHS.
2999 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003000 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00003001 return LHS;
3002
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003003 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003004 }
Mike Stump1eb44332009-09-09 15:08:12 +00003005
Ted Kremenek06de2762007-08-17 16:46:58 +00003006 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003007 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003008 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003009
Ted Kremenek06de2762007-08-17 16:46:58 +00003010 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003011 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003012 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003013
3014 // Check whether the member type is itself a reference, in which case
3015 // we're not going to refer to the member, but to what the member refers to.
3016 if (M->getMemberDecl()->getType()->isReferenceType())
3017 return NULL;
3018
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003019 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003020 }
Mike Stump1eb44332009-09-09 15:08:12 +00003021
Douglas Gregor03e80032011-06-21 17:03:29 +00003022 case Stmt::MaterializeTemporaryExprClass:
3023 if (Expr *Result = EvalVal(
3024 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
3025 refVars))
3026 return Result;
3027
3028 return E;
3029
Ted Kremenek06de2762007-08-17 16:46:58 +00003030 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003031 // Check that we don't return or take the address of a reference to a
3032 // temporary. This is only useful in C++.
3033 if (!E->isTypeDependent() && E->isRValue())
3034 return E;
3035
3036 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003037 return NULL;
3038 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003039} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003040}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003041
3042//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3043
3044/// Check for comparisons of floating point operands using != and ==.
3045/// Issue a warning if these are no self-comparisons, as they are not likely
3046/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003047void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003048 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003049
Richard Trieudd225092011-09-15 21:56:47 +00003050 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3051 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003052
3053 // Special case: check for x == x (which is OK).
3054 // Do not emit warnings for such cases.
3055 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3056 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3057 if (DRL->getDecl() == DRR->getDecl())
3058 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003059
3060
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003061 // Special case: check for comparisons against literals that can be exactly
3062 // represented by APFloat. In such cases, do not emit a warning. This
3063 // is a heuristic: often comparison against such literals are used to
3064 // detect if a value in a variable has not changed. This clearly can
3065 // lead to false negatives.
3066 if (EmitWarning) {
3067 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3068 if (FLL->isExact())
3069 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003070 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003071 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
3072 if (FLR->isExact())
3073 EmitWarning = false;
3074 }
3075 }
Mike Stump1eb44332009-09-09 15:08:12 +00003076
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003077 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003078 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003079 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003080 if (CL->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003081 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003082
Sebastian Redl0eb23302009-01-19 00:08:26 +00003083 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003084 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003085 if (CR->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003086 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003087
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003088 // Emit the diagnostic.
3089 if (EmitWarning)
Richard Trieudd225092011-09-15 21:56:47 +00003090 Diag(Loc, diag::warn_floatingpoint_eq)
3091 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003092}
John McCallba26e582010-01-04 23:21:16 +00003093
John McCallf2370c92010-01-06 05:24:50 +00003094//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3095//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003096
John McCallf2370c92010-01-06 05:24:50 +00003097namespace {
John McCallba26e582010-01-04 23:21:16 +00003098
John McCallf2370c92010-01-06 05:24:50 +00003099/// Structure recording the 'active' range of an integer-valued
3100/// expression.
3101struct IntRange {
3102 /// The number of bits active in the int.
3103 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003104
John McCallf2370c92010-01-06 05:24:50 +00003105 /// True if the int is known not to have negative values.
3106 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003107
John McCallf2370c92010-01-06 05:24:50 +00003108 IntRange(unsigned Width, bool NonNegative)
3109 : Width(Width), NonNegative(NonNegative)
3110 {}
John McCallba26e582010-01-04 23:21:16 +00003111
John McCall1844a6e2010-11-10 23:38:19 +00003112 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00003113 static IntRange forBoolType() {
3114 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00003115 }
3116
John McCall1844a6e2010-11-10 23:38:19 +00003117 /// Returns the range of an opaque value of the given integral type.
3118 static IntRange forValueOfType(ASTContext &C, QualType T) {
3119 return forValueOfCanonicalType(C,
3120 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00003121 }
3122
John McCall1844a6e2010-11-10 23:38:19 +00003123 /// Returns the range of an opaque value of a canonical integral type.
3124 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00003125 assert(T->isCanonicalUnqualified());
3126
3127 if (const VectorType *VT = dyn_cast<VectorType>(T))
3128 T = VT->getElementType().getTypePtr();
3129 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3130 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00003131
John McCall091f23f2010-11-09 22:22:12 +00003132 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00003133 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3134 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00003135 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00003136 return IntRange(C.getIntWidth(QualType(T, 0)), false);
3137
John McCall323ed742010-05-06 08:58:33 +00003138 unsigned NumPositive = Enum->getNumPositiveBits();
3139 unsigned NumNegative = Enum->getNumNegativeBits();
3140
3141 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3142 }
John McCallf2370c92010-01-06 05:24:50 +00003143
3144 const BuiltinType *BT = cast<BuiltinType>(T);
3145 assert(BT->isInteger());
3146
3147 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3148 }
3149
John McCall1844a6e2010-11-10 23:38:19 +00003150 /// Returns the "target" range of a canonical integral type, i.e.
3151 /// the range of values expressible in the type.
3152 ///
3153 /// This matches forValueOfCanonicalType except that enums have the
3154 /// full range of their type, not the range of their enumerators.
3155 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3156 assert(T->isCanonicalUnqualified());
3157
3158 if (const VectorType *VT = dyn_cast<VectorType>(T))
3159 T = VT->getElementType().getTypePtr();
3160 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3161 T = CT->getElementType().getTypePtr();
3162 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00003163 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00003164
3165 const BuiltinType *BT = cast<BuiltinType>(T);
3166 assert(BT->isInteger());
3167
3168 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3169 }
3170
3171 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003172 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00003173 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00003174 L.NonNegative && R.NonNegative);
3175 }
3176
John McCall1844a6e2010-11-10 23:38:19 +00003177 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003178 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00003179 return IntRange(std::min(L.Width, R.Width),
3180 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00003181 }
3182};
3183
3184IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
3185 if (value.isSigned() && value.isNegative())
3186 return IntRange(value.getMinSignedBits(), false);
3187
3188 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003189 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003190
3191 // isNonNegative() just checks the sign bit without considering
3192 // signedness.
3193 return IntRange(value.getActiveBits(), true);
3194}
3195
John McCall0acc3112010-01-06 22:57:21 +00003196IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00003197 unsigned MaxWidth) {
3198 if (result.isInt())
3199 return GetValueRange(C, result.getInt(), MaxWidth);
3200
3201 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00003202 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3203 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3204 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3205 R = IntRange::join(R, El);
3206 }
John McCallf2370c92010-01-06 05:24:50 +00003207 return R;
3208 }
3209
3210 if (result.isComplexInt()) {
3211 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3212 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3213 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00003214 }
3215
3216 // This can happen with lossless casts to intptr_t of "based" lvalues.
3217 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00003218 // FIXME: The only reason we need to pass the type in here is to get
3219 // the sign right on this one case. It would be nice if APValue
3220 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00003221 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003222 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00003223}
John McCallf2370c92010-01-06 05:24:50 +00003224
3225/// Pseudo-evaluate the given integer expression, estimating the
3226/// range of values it might take.
3227///
3228/// \param MaxWidth - the width to which the value will be truncated
3229IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
3230 E = E->IgnoreParens();
3231
3232 // Try a full evaluation first.
3233 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003234 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00003235 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003236
3237 // I think we only want to look through implicit casts here; if the
3238 // user has an explicit widening cast, we should treat the value as
3239 // being of the new, wider type.
3240 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00003241 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00003242 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3243
John McCall1844a6e2010-11-10 23:38:19 +00003244 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00003245
John McCall2de56d12010-08-25 11:45:40 +00003246 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00003247
John McCallf2370c92010-01-06 05:24:50 +00003248 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00003249 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00003250 return OutputTypeRange;
3251
3252 IntRange SubRange
3253 = GetExprRange(C, CE->getSubExpr(),
3254 std::min(MaxWidth, OutputTypeRange.Width));
3255
3256 // Bail out if the subexpr's range is as wide as the cast type.
3257 if (SubRange.Width >= OutputTypeRange.Width)
3258 return OutputTypeRange;
3259
3260 // Otherwise, we take the smaller width, and we're non-negative if
3261 // either the output type or the subexpr is.
3262 return IntRange(SubRange.Width,
3263 SubRange.NonNegative || OutputTypeRange.NonNegative);
3264 }
3265
3266 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3267 // If we can fold the condition, just take that operand.
3268 bool CondResult;
3269 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3270 return GetExprRange(C, CondResult ? CO->getTrueExpr()
3271 : CO->getFalseExpr(),
3272 MaxWidth);
3273
3274 // Otherwise, conservatively merge.
3275 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3276 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3277 return IntRange::join(L, R);
3278 }
3279
3280 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3281 switch (BO->getOpcode()) {
3282
3283 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00003284 case BO_LAnd:
3285 case BO_LOr:
3286 case BO_LT:
3287 case BO_GT:
3288 case BO_LE:
3289 case BO_GE:
3290 case BO_EQ:
3291 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00003292 return IntRange::forBoolType();
3293
John McCall862ff872011-07-13 06:35:24 +00003294 // The type of the assignments is the type of the LHS, so the RHS
3295 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00003296 case BO_MulAssign:
3297 case BO_DivAssign:
3298 case BO_RemAssign:
3299 case BO_AddAssign:
3300 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00003301 case BO_XorAssign:
3302 case BO_OrAssign:
3303 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00003304 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00003305
John McCall862ff872011-07-13 06:35:24 +00003306 // Simple assignments just pass through the RHS, which will have
3307 // been coerced to the LHS type.
3308 case BO_Assign:
3309 // TODO: bitfields?
3310 return GetExprRange(C, BO->getRHS(), MaxWidth);
3311
John McCallf2370c92010-01-06 05:24:50 +00003312 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003313 case BO_PtrMemD:
3314 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00003315 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003316
John McCall60fad452010-01-06 22:07:33 +00003317 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00003318 case BO_And:
3319 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00003320 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3321 GetExprRange(C, BO->getRHS(), MaxWidth));
3322
John McCallf2370c92010-01-06 05:24:50 +00003323 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00003324 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00003325 // ...except that we want to treat '1 << (blah)' as logically
3326 // positive. It's an important idiom.
3327 if (IntegerLiteral *I
3328 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3329 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00003330 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00003331 return IntRange(R.Width, /*NonNegative*/ true);
3332 }
3333 }
3334 // fallthrough
3335
John McCall2de56d12010-08-25 11:45:40 +00003336 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00003337 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003338
John McCall60fad452010-01-06 22:07:33 +00003339 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00003340 case BO_Shr:
3341 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00003342 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3343
3344 // If the shift amount is a positive constant, drop the width by
3345 // that much.
3346 llvm::APSInt shift;
3347 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3348 shift.isNonNegative()) {
3349 unsigned zext = shift.getZExtValue();
3350 if (zext >= L.Width)
3351 L.Width = (L.NonNegative ? 0 : 1);
3352 else
3353 L.Width -= zext;
3354 }
3355
3356 return L;
3357 }
3358
3359 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00003360 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00003361 return GetExprRange(C, BO->getRHS(), MaxWidth);
3362
John McCall60fad452010-01-06 22:07:33 +00003363 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00003364 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00003365 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00003366 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00003367 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003368
John McCall00fe7612011-07-14 22:39:48 +00003369 // The width of a division result is mostly determined by the size
3370 // of the LHS.
3371 case BO_Div: {
3372 // Don't 'pre-truncate' the operands.
3373 unsigned opWidth = C.getIntWidth(E->getType());
3374 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3375
3376 // If the divisor is constant, use that.
3377 llvm::APSInt divisor;
3378 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3379 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3380 if (log2 >= L.Width)
3381 L.Width = (L.NonNegative ? 0 : 1);
3382 else
3383 L.Width = std::min(L.Width - log2, MaxWidth);
3384 return L;
3385 }
3386
3387 // Otherwise, just use the LHS's width.
3388 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3389 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3390 }
3391
3392 // The result of a remainder can't be larger than the result of
3393 // either side.
3394 case BO_Rem: {
3395 // Don't 'pre-truncate' the operands.
3396 unsigned opWidth = C.getIntWidth(E->getType());
3397 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3398 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3399
3400 IntRange meet = IntRange::meet(L, R);
3401 meet.Width = std::min(meet.Width, MaxWidth);
3402 return meet;
3403 }
3404
3405 // The default behavior is okay for these.
3406 case BO_Mul:
3407 case BO_Add:
3408 case BO_Xor:
3409 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00003410 break;
3411 }
3412
John McCall00fe7612011-07-14 22:39:48 +00003413 // The default case is to treat the operation as if it were closed
3414 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00003415 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3416 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3417 return IntRange::join(L, R);
3418 }
3419
3420 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3421 switch (UO->getOpcode()) {
3422 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00003423 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00003424 return IntRange::forBoolType();
3425
3426 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003427 case UO_Deref:
3428 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00003429 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003430
3431 default:
3432 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3433 }
3434 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003435
3436 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00003437 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003438 }
John McCallf2370c92010-01-06 05:24:50 +00003439
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003440 if (FieldDecl *BitField = E->getBitField())
3441 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003442 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00003443
John McCall1844a6e2010-11-10 23:38:19 +00003444 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003445}
John McCall51313c32010-01-04 23:31:57 +00003446
John McCall323ed742010-05-06 08:58:33 +00003447IntRange GetExprRange(ASTContext &C, Expr *E) {
3448 return GetExprRange(C, E, C.getIntWidth(E->getType()));
3449}
3450
John McCall51313c32010-01-04 23:31:57 +00003451/// Checks whether the given value, which currently has the given
3452/// source semantics, has the same value when coerced through the
3453/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00003454bool IsSameFloatAfterCast(const llvm::APFloat &value,
3455 const llvm::fltSemantics &Src,
3456 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003457 llvm::APFloat truncated = value;
3458
3459 bool ignored;
3460 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3461 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3462
3463 return truncated.bitwiseIsEqual(value);
3464}
3465
3466/// Checks whether the given value, which currently has the given
3467/// source semantics, has the same value when coerced through the
3468/// target semantics.
3469///
3470/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00003471bool IsSameFloatAfterCast(const APValue &value,
3472 const llvm::fltSemantics &Src,
3473 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003474 if (value.isFloat())
3475 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3476
3477 if (value.isVector()) {
3478 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3479 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3480 return false;
3481 return true;
3482 }
3483
3484 assert(value.isComplexFloat());
3485 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3486 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3487}
3488
John McCallb4eb64d2010-10-08 02:01:28 +00003489void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00003490
Ted Kremeneke3b159c2010-09-23 21:43:44 +00003491static bool IsZero(Sema &S, Expr *E) {
3492 // Suppress cases where we are comparing against an enum constant.
3493 if (const DeclRefExpr *DR =
3494 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3495 if (isa<EnumConstantDecl>(DR->getDecl()))
3496 return false;
3497
3498 // Suppress cases where the '0' value is expanded from a macro.
3499 if (E->getLocStart().isMacroID())
3500 return false;
3501
John McCall323ed742010-05-06 08:58:33 +00003502 llvm::APSInt Value;
3503 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3504}
3505
John McCall372e1032010-10-06 00:25:24 +00003506static bool HasEnumType(Expr *E) {
3507 // Strip off implicit integral promotions.
3508 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003509 if (ICE->getCastKind() != CK_IntegralCast &&
3510 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00003511 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003512 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00003513 }
3514
3515 return E->getType()->isEnumeralType();
3516}
3517
John McCall323ed742010-05-06 08:58:33 +00003518void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003519 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00003520 if (E->isValueDependent())
3521 return;
3522
John McCall2de56d12010-08-25 11:45:40 +00003523 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003524 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003525 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003526 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003527 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003528 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003529 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003530 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003531 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003532 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003533 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003534 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003535 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003536 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003537 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003538 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3539 }
3540}
3541
3542/// Analyze the operands of the given comparison. Implements the
3543/// fallback case from AnalyzeComparison.
3544void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00003545 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3546 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00003547}
John McCall51313c32010-01-04 23:31:57 +00003548
John McCallba26e582010-01-04 23:21:16 +00003549/// \brief Implements -Wsign-compare.
3550///
Richard Trieudd225092011-09-15 21:56:47 +00003551/// \param E the binary operator to check for warnings
John McCall323ed742010-05-06 08:58:33 +00003552void AnalyzeComparison(Sema &S, BinaryOperator *E) {
3553 // The type the comparison is being performed in.
3554 QualType T = E->getLHS()->getType();
3555 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3556 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00003557
John McCall323ed742010-05-06 08:58:33 +00003558 // We don't do anything special if this isn't an unsigned integral
3559 // comparison: we're only interested in integral comparisons, and
3560 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00003561 //
3562 // We also don't care about value-dependent expressions or expressions
3563 // whose result is a constant.
3564 if (!T->hasUnsignedIntegerRepresentation()
3565 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00003566 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00003567
Richard Trieudd225092011-09-15 21:56:47 +00003568 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3569 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00003570
John McCall323ed742010-05-06 08:58:33 +00003571 // Check to see if one of the (unmodified) operands is of different
3572 // signedness.
3573 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00003574 if (LHS->getType()->hasSignedIntegerRepresentation()) {
3575 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00003576 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00003577 signedOperand = LHS;
3578 unsignedOperand = RHS;
3579 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3580 signedOperand = RHS;
3581 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00003582 } else {
John McCall323ed742010-05-06 08:58:33 +00003583 CheckTrivialUnsignedComparison(S, E);
3584 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003585 }
3586
John McCall323ed742010-05-06 08:58:33 +00003587 // Otherwise, calculate the effective range of the signed operand.
3588 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00003589
John McCall323ed742010-05-06 08:58:33 +00003590 // Go ahead and analyze implicit conversions in the operands. Note
3591 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00003592 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3593 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00003594
John McCall323ed742010-05-06 08:58:33 +00003595 // If the signed range is non-negative, -Wsign-compare won't fire,
3596 // but we should still check for comparisons which are always true
3597 // or false.
3598 if (signedRange.NonNegative)
3599 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003600
3601 // For (in)equality comparisons, if the unsigned operand is a
3602 // constant which cannot collide with a overflowed signed operand,
3603 // then reinterpreting the signed operand as unsigned will not
3604 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00003605 if (E->isEqualityOp()) {
3606 unsigned comparisonWidth = S.Context.getIntWidth(T);
3607 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00003608
John McCall323ed742010-05-06 08:58:33 +00003609 // We should never be unable to prove that the unsigned operand is
3610 // non-negative.
3611 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3612
3613 if (unsignedRange.Width < comparisonWidth)
3614 return;
3615 }
3616
3617 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
Richard Trieudd225092011-09-15 21:56:47 +00003618 << LHS->getType() << RHS->getType()
3619 << LHS->getSourceRange() << RHS->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00003620}
3621
John McCall15d7d122010-11-11 03:21:53 +00003622/// Analyzes an attempt to assign the given value to a bitfield.
3623///
3624/// Returns true if there was something fishy about the attempt.
3625bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3626 SourceLocation InitLoc) {
3627 assert(Bitfield->isBitField());
3628 if (Bitfield->isInvalidDecl())
3629 return false;
3630
John McCall91b60142010-11-11 05:33:51 +00003631 // White-list bool bitfields.
3632 if (Bitfield->getType()->isBooleanType())
3633 return false;
3634
Douglas Gregor46ff3032011-02-04 13:09:01 +00003635 // Ignore value- or type-dependent expressions.
3636 if (Bitfield->getBitWidth()->isValueDependent() ||
3637 Bitfield->getBitWidth()->isTypeDependent() ||
3638 Init->isValueDependent() ||
3639 Init->isTypeDependent())
3640 return false;
3641
John McCall15d7d122010-11-11 03:21:53 +00003642 Expr *OriginalInit = Init->IgnoreParenImpCasts();
3643
Richard Smith80d4b552011-12-28 19:48:30 +00003644 llvm::APSInt Value;
3645 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00003646 return false;
3647
John McCall15d7d122010-11-11 03:21:53 +00003648 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003649 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00003650
3651 if (OriginalWidth <= FieldWidth)
3652 return false;
3653
Jay Foad9f71a8f2010-12-07 08:25:34 +00003654 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall15d7d122010-11-11 03:21:53 +00003655
3656 // It's fairly common to write values into signed bitfields
3657 // that, if sign-extended, would end up becoming a different
3658 // value. We don't want to warn about that.
3659 if (Value.isSigned() && Value.isNegative())
Jay Foad9f71a8f2010-12-07 08:25:34 +00003660 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003661 else
Jay Foad9f71a8f2010-12-07 08:25:34 +00003662 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003663
3664 if (Value == TruncatedValue)
3665 return false;
3666
3667 std::string PrettyValue = Value.toString(10);
3668 std::string PrettyTrunc = TruncatedValue.toString(10);
3669
3670 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3671 << PrettyValue << PrettyTrunc << OriginalInit->getType()
3672 << Init->getSourceRange();
3673
3674 return true;
3675}
3676
John McCallbeb22aa2010-11-09 23:24:47 +00003677/// Analyze the given simple or compound assignment for warning-worthy
3678/// operations.
3679void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
3680 // Just recurse on the LHS.
3681 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3682
3683 // We want to recurse on the RHS as normal unless we're assigning to
3684 // a bitfield.
3685 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00003686 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3687 E->getOperatorLoc())) {
3688 // Recurse, ignoring any implicit conversions on the RHS.
3689 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3690 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00003691 }
3692 }
3693
3694 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3695}
3696
John McCall51313c32010-01-04 23:31:57 +00003697/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003698void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
3699 SourceLocation CContext, unsigned diag) {
3700 S.Diag(E->getExprLoc(), diag)
3701 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3702}
3703
Chandler Carruthe1b02e02011-04-05 06:47:57 +00003704/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
3705void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
3706 unsigned diag) {
3707 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
3708}
3709
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003710/// Diagnose an implicit cast from a literal expression. Does not warn when the
3711/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003712void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3713 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003714 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003715 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003716 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003717 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3718 T->hasUnsignedIntegerRepresentation());
3719 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00003720 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003721 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00003722 return;
3723
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003724 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3725 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00003726}
3727
John McCall091f23f2010-11-09 22:22:12 +00003728std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3729 if (!Range.Width) return "0";
3730
3731 llvm::APSInt ValueInRange = Value;
3732 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00003733 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00003734 return ValueInRange.toString(10);
3735}
3736
John McCall323ed742010-05-06 08:58:33 +00003737void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003738 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00003739 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00003740
John McCall323ed742010-05-06 08:58:33 +00003741 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3742 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3743 if (Source == Target) return;
3744 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00003745
Chandler Carruth108f7562011-07-26 05:40:03 +00003746 // If the conversion context location is invalid don't complain. We also
3747 // don't want to emit a warning if the issue occurs from the expansion of
3748 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3749 // delay this check as long as possible. Once we detect we are in that
3750 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003751 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00003752 return;
3753
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003754 // Diagnose implicit casts to bool.
3755 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
3756 if (isa<StringLiteral>(E))
3757 // Warn on string literal to bool. Checks for string literals in logical
3758 // expressions, for instances, assert(0 && "error here"), is prevented
3759 // by a check in AnalyzeImplicitConversions().
3760 return DiagnoseImpCast(S, E, T, CC,
3761 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00003762 if (Source->isFunctionType()) {
3763 // Warn on function to bool. Checks free functions and static member
3764 // functions. Weakly imported functions are excluded from the check,
3765 // since it's common to test their value to check whether the linker
3766 // found a definition for them.
3767 ValueDecl *D = 0;
3768 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
3769 D = R->getDecl();
3770 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
3771 D = M->getMemberDecl();
3772 }
3773
3774 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00003775 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
3776 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
3777 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00003778 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
3779 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
3780 QualType ReturnType;
3781 UnresolvedSet<4> NonTemplateOverloads;
3782 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
3783 if (!ReturnType.isNull()
3784 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
3785 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
3786 << FixItHint::CreateInsertion(
3787 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00003788 return;
3789 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00003790 }
3791 }
David Blaikiee37cdc42011-09-29 04:06:47 +00003792 return; // Other casts to bool are not checked.
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003793 }
John McCall51313c32010-01-04 23:31:57 +00003794
3795 // Strip vector types.
3796 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003797 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003798 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003799 return;
John McCallb4eb64d2010-10-08 02:01:28 +00003800 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003801 }
Chris Lattnerb792b302011-06-14 04:51:15 +00003802
3803 // If the vector cast is cast between two vectors of the same size, it is
3804 // a bitcast, not a conversion.
3805 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3806 return;
John McCall51313c32010-01-04 23:31:57 +00003807
3808 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3809 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3810 }
3811
3812 // Strip complex types.
3813 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003814 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003815 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003816 return;
3817
John McCallb4eb64d2010-10-08 02:01:28 +00003818 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003819 }
John McCall51313c32010-01-04 23:31:57 +00003820
3821 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3822 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3823 }
3824
3825 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3826 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3827
3828 // If the source is floating point...
3829 if (SourceBT && SourceBT->isFloatingPoint()) {
3830 // ...and the target is floating point...
3831 if (TargetBT && TargetBT->isFloatingPoint()) {
3832 // ...then warn if we're dropping FP rank.
3833
3834 // Builtin FP kinds are ordered by increasing FP rank.
3835 if (SourceBT->getKind() > TargetBT->getKind()) {
3836 // Don't warn about float constants that are precisely
3837 // representable in the target type.
3838 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003839 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00003840 // Value might be a float, a float vector, or a float complex.
3841 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00003842 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3843 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00003844 return;
3845 }
3846
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003847 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003848 return;
3849
John McCallb4eb64d2010-10-08 02:01:28 +00003850 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00003851 }
3852 return;
3853 }
3854
Ted Kremenekef9ff882011-03-10 20:03:42 +00003855 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00003856 if ((TargetBT && TargetBT->isInteger())) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003857 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003858 return;
3859
Chandler Carrutha5b93322011-02-17 11:05:49 +00003860 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00003861 // We also want to warn on, e.g., "int i = -1.234"
3862 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
3863 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
3864 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
3865
Chandler Carruthf65076e2011-04-10 08:36:24 +00003866 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3867 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00003868 } else {
3869 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3870 }
3871 }
John McCall51313c32010-01-04 23:31:57 +00003872
3873 return;
3874 }
3875
John McCallf2370c92010-01-06 05:24:50 +00003876 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00003877 return;
3878
Richard Trieu1838ca52011-05-29 19:59:02 +00003879 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3880 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3881 S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
3882 << E->getSourceRange() << clang::SourceRange(CC);
3883 return;
3884 }
3885
John McCall323ed742010-05-06 08:58:33 +00003886 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00003887 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00003888
3889 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00003890 // If the source is a constant, use a default-on diagnostic.
3891 // TODO: this should happen for bitfield stores, too.
3892 llvm::APSInt Value(32);
3893 if (E->isIntegerConstantExpr(Value, S.Context)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003894 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003895 return;
3896
John McCall091f23f2010-11-09 22:22:12 +00003897 std::string PrettySourceValue = Value.toString(10);
3898 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
3899
Ted Kremenek5e745da2011-10-22 02:37:33 +00003900 S.DiagRuntimeBehavior(E->getExprLoc(), E,
3901 S.PDiag(diag::warn_impcast_integer_precision_constant)
3902 << PrettySourceValue << PrettyTargetValue
3903 << E->getType() << T << E->getSourceRange()
3904 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00003905 return;
3906 }
3907
Chris Lattnerb792b302011-06-14 04:51:15 +00003908 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003909 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003910 return;
3911
John McCallf2370c92010-01-06 05:24:50 +00003912 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00003913 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
3914 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00003915 }
3916
3917 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
3918 (!TargetRange.NonNegative && SourceRange.NonNegative &&
3919 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003920
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003921 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003922 return;
3923
John McCall323ed742010-05-06 08:58:33 +00003924 unsigned DiagID = diag::warn_impcast_integer_sign;
3925
3926 // Traditionally, gcc has warned about this under -Wsign-compare.
3927 // We also want to warn about it in -Wconversion.
3928 // So if -Wconversion is off, use a completely identical diagnostic
3929 // in the sign-compare group.
3930 // The conditional-checking code will
3931 if (ICContext) {
3932 DiagID = diag::warn_impcast_integer_sign_conditional;
3933 *ICContext = true;
3934 }
3935
John McCallb4eb64d2010-10-08 02:01:28 +00003936 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00003937 }
3938
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003939 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003940 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3941 // type, to give us better diagnostics.
3942 QualType SourceType = E->getType();
3943 if (!S.getLangOptions().CPlusPlus) {
3944 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3945 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3946 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
3947 SourceType = S.Context.getTypeDeclType(Enum);
3948 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3949 }
3950 }
3951
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003952 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3953 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3954 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003955 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003956 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003957 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00003958 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003959 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003960 return;
3961
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003962 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003963 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003964 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003965
John McCall51313c32010-01-04 23:31:57 +00003966 return;
3967}
3968
John McCall323ed742010-05-06 08:58:33 +00003969void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3970
3971void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003972 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00003973 E = E->IgnoreParenImpCasts();
3974
3975 if (isa<ConditionalOperator>(E))
3976 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
3977
John McCallb4eb64d2010-10-08 02:01:28 +00003978 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003979 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003980 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00003981 return;
3982}
3983
3984void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00003985 SourceLocation CC = E->getQuestionLoc();
3986
3987 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00003988
3989 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00003990 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3991 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003992
3993 // If -Wconversion would have warned about either of the candidates
3994 // for a signedness conversion to the context type...
3995 if (!Suspicious) return;
3996
3997 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003998 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
3999 CC))
John McCall323ed742010-05-06 08:58:33 +00004000 return;
4001
John McCall323ed742010-05-06 08:58:33 +00004002 // ...then check whether it would have warned about either of the
4003 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00004004 if (E->getType() == T) return;
4005
4006 Suspicious = false;
4007 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
4008 E->getType(), CC, &Suspicious);
4009 if (!Suspicious)
4010 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00004011 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004012}
4013
4014/// AnalyzeImplicitConversions - Find and report any interesting
4015/// implicit conversions in the given expression. There are a couple
4016/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004017void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004018 QualType T = OrigE->getType();
4019 Expr *E = OrigE->IgnoreParenImpCasts();
4020
Douglas Gregorf8b6e152011-10-10 17:38:18 +00004021 if (E->isTypeDependent() || E->isValueDependent())
4022 return;
4023
John McCall323ed742010-05-06 08:58:33 +00004024 // For conditional operators, we analyze the arguments as if they
4025 // were being fed directly into the output.
4026 if (isa<ConditionalOperator>(E)) {
4027 ConditionalOperator *CO = cast<ConditionalOperator>(E);
4028 CheckConditionalOperator(S, CO, T);
4029 return;
4030 }
4031
4032 // Go ahead and check any implicit conversions we might have skipped.
4033 // The non-canonical typecheck is just an optimization;
4034 // CheckImplicitConversion will filter out dead implicit conversions.
4035 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004036 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00004037
4038 // Now continue drilling into this expression.
4039
4040 // Skip past explicit casts.
4041 if (isa<ExplicitCastExpr>(E)) {
4042 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00004043 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004044 }
4045
John McCallbeb22aa2010-11-09 23:24:47 +00004046 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4047 // Do a somewhat different check with comparison operators.
4048 if (BO->isComparisonOp())
4049 return AnalyzeComparison(S, BO);
4050
4051 // And with assignments and compound assignments.
4052 if (BO->isAssignmentOp())
4053 return AnalyzeAssignment(S, BO);
4054 }
John McCall323ed742010-05-06 08:58:33 +00004055
4056 // These break the otherwise-useful invariant below. Fortunately,
4057 // we don't really need to recurse into them, because any internal
4058 // expressions should have been analyzed already when they were
4059 // built into statements.
4060 if (isa<StmtExpr>(E)) return;
4061
4062 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004063 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00004064
4065 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00004066 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004067 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
4068 bool IsLogicalOperator = BO && BO->isLogicalOp();
4069 for (Stmt::child_range I = E->children(); I; ++I) {
4070 Expr *ChildExpr = cast<Expr>(*I);
4071 if (IsLogicalOperator &&
4072 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
4073 // Ignore checking string literals that are in logical operators.
4074 continue;
4075 AnalyzeImplicitConversions(S, ChildExpr, CC);
4076 }
John McCall323ed742010-05-06 08:58:33 +00004077}
4078
4079} // end anonymous namespace
4080
4081/// Diagnoses "dangerous" implicit conversions within the given
4082/// expression (which is a full expression). Implements -Wconversion
4083/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004084///
4085/// \param CC the "context" location of the implicit conversion, i.e.
4086/// the most location of the syntactic entity requiring the implicit
4087/// conversion
4088void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004089 // Don't diagnose in unevaluated contexts.
4090 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
4091 return;
4092
4093 // Don't diagnose for value- or type-dependent expressions.
4094 if (E->isTypeDependent() || E->isValueDependent())
4095 return;
4096
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004097 // Check for array bounds violations in cases where the check isn't triggered
4098 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
4099 // ArraySubscriptExpr is on the RHS of a variable initialization.
4100 CheckArrayAccess(E);
4101
John McCallb4eb64d2010-10-08 02:01:28 +00004102 // This is not the right CC for (e.g.) a variable initialization.
4103 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004104}
4105
John McCall15d7d122010-11-11 03:21:53 +00004106void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
4107 FieldDecl *BitField,
4108 Expr *Init) {
4109 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
4110}
4111
Mike Stumpf8c49212010-01-21 03:59:47 +00004112/// CheckParmsForFunctionDef - Check that the parameters of the given
4113/// function are appropriate for the definition of a function. This
4114/// takes care of any checks that cannot be performed on the
4115/// declaration itself, e.g., that the types of each of the function
4116/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004117bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
4118 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004119 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00004120 for (; P != PEnd; ++P) {
4121 ParmVarDecl *Param = *P;
4122
Mike Stumpf8c49212010-01-21 03:59:47 +00004123 // C99 6.7.5.3p4: the parameters in a parameter type list in a
4124 // function declarator that is part of a function definition of
4125 // that function shall not have incomplete type.
4126 //
4127 // This is also C++ [dcl.fct]p6.
4128 if (!Param->isInvalidDecl() &&
4129 RequireCompleteType(Param->getLocation(), Param->getType(),
4130 diag::err_typecheck_decl_incomplete_type)) {
4131 Param->setInvalidDecl();
4132 HasInvalidParm = true;
4133 }
4134
4135 // C99 6.9.1p5: If the declarator includes a parameter type list, the
4136 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004137 if (CheckParameterNames &&
4138 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00004139 !Param->isImplicit() &&
4140 !getLangOptions().CPlusPlus)
4141 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00004142
4143 // C99 6.7.5.3p12:
4144 // If the function declarator is not part of a definition of that
4145 // function, parameters may have incomplete type and may use the [*]
4146 // notation in their sequences of declarator specifiers to specify
4147 // variable length array types.
4148 QualType PType = Param->getOriginalType();
4149 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
4150 if (AT->getSizeModifier() == ArrayType::Star) {
4151 // FIXME: This diagnosic should point the the '[*]' if source-location
4152 // information is added for it.
4153 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
4154 }
4155 }
Mike Stumpf8c49212010-01-21 03:59:47 +00004156 }
4157
4158 return HasInvalidParm;
4159}
John McCallb7f4ffe2010-08-12 21:44:57 +00004160
4161/// CheckCastAlign - Implements -Wcast-align, which warns when a
4162/// pointer cast increases the alignment requirements.
4163void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
4164 // This is actually a lot of work to potentially be doing on every
4165 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004166 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
4167 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00004168 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00004169 return;
4170
4171 // Ignore dependent types.
4172 if (T->isDependentType() || Op->getType()->isDependentType())
4173 return;
4174
4175 // Require that the destination be a pointer type.
4176 const PointerType *DestPtr = T->getAs<PointerType>();
4177 if (!DestPtr) return;
4178
4179 // If the destination has alignment 1, we're done.
4180 QualType DestPointee = DestPtr->getPointeeType();
4181 if (DestPointee->isIncompleteType()) return;
4182 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
4183 if (DestAlign.isOne()) return;
4184
4185 // Require that the source be a pointer type.
4186 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
4187 if (!SrcPtr) return;
4188 QualType SrcPointee = SrcPtr->getPointeeType();
4189
4190 // Whitelist casts from cv void*. We already implicitly
4191 // whitelisted casts to cv void*, since they have alignment 1.
4192 // Also whitelist casts involving incomplete types, which implicitly
4193 // includes 'void'.
4194 if (SrcPointee->isIncompleteType()) return;
4195
4196 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
4197 if (SrcAlign >= DestAlign) return;
4198
4199 Diag(TRange.getBegin(), diag::warn_cast_align)
4200 << Op->getType() << T
4201 << static_cast<unsigned>(SrcAlign.getQuantity())
4202 << static_cast<unsigned>(DestAlign.getQuantity())
4203 << TRange << Op->getSourceRange();
4204}
4205
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004206static const Type* getElementType(const Expr *BaseExpr) {
4207 const Type* EltType = BaseExpr->getType().getTypePtr();
4208 if (EltType->isAnyPointerType())
4209 return EltType->getPointeeType().getTypePtr();
4210 else if (EltType->isArrayType())
4211 return EltType->getBaseElementTypeUnsafe();
4212 return EltType;
4213}
4214
Chandler Carruthc2684342011-08-05 09:10:50 +00004215/// \brief Check whether this array fits the idiom of a size-one tail padded
4216/// array member of a struct.
4217///
4218/// We avoid emitting out-of-bounds access warnings for such arrays as they are
4219/// commonly used to emulate flexible arrays in C89 code.
4220static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4221 const NamedDecl *ND) {
4222 if (Size != 1 || !ND) return false;
4223
4224 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4225 if (!FD) return false;
4226
4227 // Don't consider sizes resulting from macro expansions or template argument
4228 // substitution to form C89 tail-padded arrays.
4229 ConstantArrayTypeLoc TL =
4230 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
4231 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
4232 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4233 return false;
4234
4235 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00004236 if (!RD) return false;
4237 if (RD->isUnion()) return false;
4238 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
4239 if (!CRD->isStandardLayout()) return false;
4240 }
Chandler Carruthc2684342011-08-05 09:10:50 +00004241
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00004242 // See if this is the last field decl in the record.
4243 const Decl *D = FD;
4244 while ((D = D->getNextDeclInContext()))
4245 if (isa<FieldDecl>(D))
4246 return false;
4247 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00004248}
4249
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004250void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004251 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00004252 bool AllowOnePastEnd, bool IndexNegated) {
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004253 IndexExpr = IndexExpr->IgnoreParenCasts();
4254 if (IndexExpr->isValueDependent())
4255 return;
4256
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00004257 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004258 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00004259 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004260 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00004261 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00004262 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00004263
Chandler Carruth34064582011-02-17 20:55:08 +00004264 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004265 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00004266 return;
Richard Smith25b009a2011-12-16 19:31:14 +00004267 if (IndexNegated)
4268 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004269
Chandler Carruthba447122011-08-05 08:07:29 +00004270 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00004271 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4272 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00004273 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00004274 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00004275
Ted Kremenek9e060ca2011-02-23 23:06:04 +00004276 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00004277 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00004278 if (!size.isStrictlyPositive())
4279 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004280
4281 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00004282 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004283 // Make sure we're comparing apples to apples when comparing index to size
4284 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4285 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00004286 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00004287 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004288 if (ptrarith_typesize != array_typesize) {
4289 // There's a cast to a different size type involved
4290 uint64_t ratio = array_typesize / ptrarith_typesize;
4291 // TODO: Be smarter about handling cases where array_typesize is not a
4292 // multiple of ptrarith_typesize
4293 if (ptrarith_typesize * ratio == array_typesize)
4294 size *= llvm::APInt(size.getBitWidth(), ratio);
4295 }
4296 }
4297
Chandler Carruth34064582011-02-17 20:55:08 +00004298 if (size.getBitWidth() > index.getBitWidth())
4299 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004300 else if (size.getBitWidth() < index.getBitWidth())
4301 size = size.sext(index.getBitWidth());
4302
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004303 // For array subscripting the index must be less than size, but for pointer
4304 // arithmetic also allow the index (offset) to be equal to size since
4305 // computing the next address after the end of the array is legal and
4306 // commonly done e.g. in C++ iterators and range-based for loops.
4307 if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
Chandler Carruthba447122011-08-05 08:07:29 +00004308 return;
4309
4310 // Also don't warn for arrays of size 1 which are members of some
4311 // structure. These are often used to approximate flexible arrays in C89
4312 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004313 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004314 return;
Chandler Carruth34064582011-02-17 20:55:08 +00004315
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004316 // Suppress the warning if the subscript expression (as identified by the
4317 // ']' location) and the index expression are both from macro expansions
4318 // within a system header.
4319 if (ASE) {
4320 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
4321 ASE->getRBracketLoc());
4322 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
4323 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
4324 IndexExpr->getLocStart());
4325 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
4326 return;
4327 }
4328 }
4329
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004330 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004331 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004332 DiagID = diag::warn_array_index_exceeds_bounds;
4333
4334 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4335 PDiag(DiagID) << index.toString(10, true)
4336 << size.toString(10, true)
4337 << (unsigned)size.getLimitedValue(~0U)
4338 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00004339 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004340 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004341 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004342 DiagID = diag::warn_ptr_arith_precedes_bounds;
4343 if (index.isNegative()) index = -index;
4344 }
4345
4346 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4347 PDiag(DiagID) << index.toString(10, true)
4348 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004349 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00004350
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00004351 if (!ND) {
4352 // Try harder to find a NamedDecl to point at in the note.
4353 while (const ArraySubscriptExpr *ASE =
4354 dyn_cast<ArraySubscriptExpr>(BaseExpr))
4355 BaseExpr = ASE->getBase()->IgnoreParenCasts();
4356 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4357 ND = dyn_cast<NamedDecl>(DRE->getDecl());
4358 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
4359 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
4360 }
4361
Chandler Carruth35001ca2011-02-17 21:10:52 +00004362 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004363 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4364 PDiag(diag::note_array_index_out_of_bounds)
4365 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004366}
4367
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004368void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004369 int AllowOnePastEnd = 0;
4370 while (expr) {
4371 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004372 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004373 case Stmt::ArraySubscriptExprClass: {
4374 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004375 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004376 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004377 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004378 }
4379 case Stmt::UnaryOperatorClass: {
4380 // Only unwrap the * and & unary operators
4381 const UnaryOperator *UO = cast<UnaryOperator>(expr);
4382 expr = UO->getSubExpr();
4383 switch (UO->getOpcode()) {
4384 case UO_AddrOf:
4385 AllowOnePastEnd++;
4386 break;
4387 case UO_Deref:
4388 AllowOnePastEnd--;
4389 break;
4390 default:
4391 return;
4392 }
4393 break;
4394 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004395 case Stmt::ConditionalOperatorClass: {
4396 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4397 if (const Expr *lhs = cond->getLHS())
4398 CheckArrayAccess(lhs);
4399 if (const Expr *rhs = cond->getRHS())
4400 CheckArrayAccess(rhs);
4401 return;
4402 }
4403 default:
4404 return;
4405 }
Peter Collingbournef111d932011-04-15 00:35:48 +00004406 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004407}
John McCallf85e1932011-06-15 23:02:42 +00004408
4409//===--- CHECK: Objective-C retain cycles ----------------------------------//
4410
4411namespace {
4412 struct RetainCycleOwner {
4413 RetainCycleOwner() : Variable(0), Indirect(false) {}
4414 VarDecl *Variable;
4415 SourceRange Range;
4416 SourceLocation Loc;
4417 bool Indirect;
4418
4419 void setLocsFrom(Expr *e) {
4420 Loc = e->getExprLoc();
4421 Range = e->getSourceRange();
4422 }
4423 };
4424}
4425
4426/// Consider whether capturing the given variable can possibly lead to
4427/// a retain cycle.
4428static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4429 // In ARC, it's captured strongly iff the variable has __strong
4430 // lifetime. In MRR, it's captured strongly if the variable is
4431 // __block and has an appropriate type.
4432 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4433 return false;
4434
4435 owner.Variable = var;
4436 owner.setLocsFrom(ref);
4437 return true;
4438}
4439
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004440static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00004441 while (true) {
4442 e = e->IgnoreParens();
4443 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4444 switch (cast->getCastKind()) {
4445 case CK_BitCast:
4446 case CK_LValueBitCast:
4447 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00004448 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00004449 e = cast->getSubExpr();
4450 continue;
4451
John McCallf85e1932011-06-15 23:02:42 +00004452 default:
4453 return false;
4454 }
4455 }
4456
4457 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4458 ObjCIvarDecl *ivar = ref->getDecl();
4459 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4460 return false;
4461
4462 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004463 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00004464 return false;
4465
4466 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4467 owner.Indirect = true;
4468 return true;
4469 }
4470
4471 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4472 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4473 if (!var) return false;
4474 return considerVariable(var, ref, owner);
4475 }
4476
4477 if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
4478 owner.Variable = ref->getDecl();
4479 owner.setLocsFrom(ref);
4480 return true;
4481 }
4482
4483 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4484 if (member->isArrow()) return false;
4485
4486 // Don't count this as an indirect ownership.
4487 e = member->getBase();
4488 continue;
4489 }
4490
John McCall4b9c2d22011-11-06 09:01:30 +00004491 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
4492 // Only pay attention to pseudo-objects on property references.
4493 ObjCPropertyRefExpr *pre
4494 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
4495 ->IgnoreParens());
4496 if (!pre) return false;
4497 if (pre->isImplicitProperty()) return false;
4498 ObjCPropertyDecl *property = pre->getExplicitProperty();
4499 if (!property->isRetaining() &&
4500 !(property->getPropertyIvarDecl() &&
4501 property->getPropertyIvarDecl()->getType()
4502 .getObjCLifetime() == Qualifiers::OCL_Strong))
4503 return false;
4504
4505 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004506 if (pre->isSuperReceiver()) {
4507 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
4508 if (!owner.Variable)
4509 return false;
4510 owner.Loc = pre->getLocation();
4511 owner.Range = pre->getSourceRange();
4512 return true;
4513 }
John McCall4b9c2d22011-11-06 09:01:30 +00004514 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
4515 ->getSourceExpr());
4516 continue;
4517 }
4518
John McCallf85e1932011-06-15 23:02:42 +00004519 // Array ivars?
4520
4521 return false;
4522 }
4523}
4524
4525namespace {
4526 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4527 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4528 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4529 Variable(variable), Capturer(0) {}
4530
4531 VarDecl *Variable;
4532 Expr *Capturer;
4533
4534 void VisitDeclRefExpr(DeclRefExpr *ref) {
4535 if (ref->getDecl() == Variable && !Capturer)
4536 Capturer = ref;
4537 }
4538
4539 void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
4540 if (ref->getDecl() == Variable && !Capturer)
4541 Capturer = ref;
4542 }
4543
4544 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4545 if (Capturer) return;
4546 Visit(ref->getBase());
4547 if (Capturer && ref->isFreeIvar())
4548 Capturer = ref;
4549 }
4550
4551 void VisitBlockExpr(BlockExpr *block) {
4552 // Look inside nested blocks
4553 if (block->getBlockDecl()->capturesVariable(Variable))
4554 Visit(block->getBlockDecl()->getBody());
4555 }
4556 };
4557}
4558
4559/// Check whether the given argument is a block which captures a
4560/// variable.
4561static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4562 assert(owner.Variable && owner.Loc.isValid());
4563
4564 e = e->IgnoreParenCasts();
4565 BlockExpr *block = dyn_cast<BlockExpr>(e);
4566 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4567 return 0;
4568
4569 FindCaptureVisitor visitor(S.Context, owner.Variable);
4570 visitor.Visit(block->getBlockDecl()->getBody());
4571 return visitor.Capturer;
4572}
4573
4574static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4575 RetainCycleOwner &owner) {
4576 assert(capturer);
4577 assert(owner.Variable && owner.Loc.isValid());
4578
4579 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4580 << owner.Variable << capturer->getSourceRange();
4581 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4582 << owner.Indirect << owner.Range;
4583}
4584
4585/// Check for a keyword selector that starts with the word 'add' or
4586/// 'set'.
4587static bool isSetterLikeSelector(Selector sel) {
4588 if (sel.isUnarySelector()) return false;
4589
Chris Lattner5f9e2722011-07-23 10:55:15 +00004590 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00004591 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00004592 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00004593 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00004594 else if (str.startswith("add")) {
4595 // Specially whitelist 'addOperationWithBlock:'.
4596 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
4597 return false;
4598 str = str.substr(3);
4599 }
John McCallf85e1932011-06-15 23:02:42 +00004600 else
4601 return false;
4602
4603 if (str.empty()) return true;
4604 return !islower(str.front());
4605}
4606
4607/// Check a message send to see if it's likely to cause a retain cycle.
4608void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4609 // Only check instance methods whose selector looks like a setter.
4610 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4611 return;
4612
4613 // Try to find a variable that the receiver is strongly owned by.
4614 RetainCycleOwner owner;
4615 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004616 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00004617 return;
4618 } else {
4619 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4620 owner.Variable = getCurMethodDecl()->getSelfDecl();
4621 owner.Loc = msg->getSuperLoc();
4622 owner.Range = msg->getSuperLoc();
4623 }
4624
4625 // Check whether the receiver is captured by any of the arguments.
4626 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4627 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4628 return diagnoseRetainCycle(*this, capturer, owner);
4629}
4630
4631/// Check a property assign to see if it's likely to cause a retain cycle.
4632void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4633 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004634 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00004635 return;
4636
4637 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4638 diagnoseRetainCycle(*this, capturer, owner);
4639}
4640
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004641bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00004642 QualType LHS, Expr *RHS) {
4643 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4644 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004645 return false;
4646 // strip off any implicit cast added to get to the one arc-specific
4647 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004648 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00004649 Diag(Loc, diag::warn_arc_retained_assign)
4650 << (LT == Qualifiers::OCL_ExplicitNone)
4651 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004652 return true;
4653 }
4654 RHS = cast->getSubExpr();
4655 }
4656 return false;
John McCallf85e1932011-06-15 23:02:42 +00004657}
4658
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004659void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4660 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00004661 QualType LHSType;
4662 // PropertyRef on LHS type need be directly obtained from
4663 // its declaration as it has a PsuedoType.
4664 ObjCPropertyRefExpr *PRE
4665 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
4666 if (PRE && !PRE->isImplicitProperty()) {
4667 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4668 if (PD)
4669 LHSType = PD->getType();
4670 }
4671
4672 if (LHSType.isNull())
4673 LHSType = LHS->getType();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004674 if (checkUnsafeAssigns(Loc, LHSType, RHS))
4675 return;
4676 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4677 // FIXME. Check for other life times.
4678 if (LT != Qualifiers::OCL_None)
4679 return;
4680
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00004681 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004682 if (PRE->isImplicitProperty())
4683 return;
4684 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4685 if (!PD)
4686 return;
4687
4688 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00004689 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
4690 // when 'assign' attribute was not explicitly specified
4691 // by user, ignore it and rely on property type itself
4692 // for lifetime info.
4693 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
4694 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
4695 LHSType->isObjCRetainableType())
4696 return;
4697
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004698 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004699 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004700 Diag(Loc, diag::warn_arc_retained_property_assign)
4701 << RHS->getSourceRange();
4702 return;
4703 }
4704 RHS = cast->getSubExpr();
4705 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00004706 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004707 }
4708}