blob: 77c5717d240cafbe7338b0f841cbb17e7c60666e [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}
Chris Lattner08f92e32010-11-17 07:37:15 +000047
Chris Lattner60800082009-02-18 17:49:48 +000048
Ryan Flynn4403a5e2009-08-06 03:00:50 +000049/// CheckablePrintfAttr - does a function call have a "printf" attribute
50/// and arguments that merit checking?
51bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
52 if (Format->getType() == "printf") return true;
53 if (Format->getType() == "printf0") {
54 // printf0 allows null "format" string; if so don't check format/args
55 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl4a2614e2009-11-17 18:02:24 +000056 // Does the index refer to the implicit object argument?
57 if (isa<CXXMemberCallExpr>(TheCall)) {
58 if (format_idx == 0)
59 return false;
60 --format_idx;
61 }
Ryan Flynn4403a5e2009-08-06 03:00:50 +000062 if (format_idx < TheCall->getNumArgs()) {
63 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Ted Kremenekefaff192010-02-27 01:41:03 +000064 if (!Format->isNullPointerConstant(Context,
65 Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +000066 return true;
67 }
68 }
69 return false;
70}
Chris Lattner60800082009-02-18 17:49:48 +000071
John McCall8e10f3b2011-02-26 05:39:39 +000072/// Checks that a call expression's argument count is the desired number.
73/// This is useful when doing custom type-checking. Returns true on error.
74static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
75 unsigned argCount = call->getNumArgs();
76 if (argCount == desiredArgCount) return false;
77
78 if (argCount < desiredArgCount)
79 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
80 << 0 /*function call*/ << desiredArgCount << argCount
81 << call->getSourceRange();
82
83 // Highlight all the excess arguments.
84 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
85 call->getArg(argCount - 1)->getLocEnd());
86
87 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
88 << 0 /*function call*/ << desiredArgCount << argCount
89 << call->getArg(1)->getSourceRange();
90}
91
Julien Lerouge77f68bb2011-09-09 22:41:49 +000092/// CheckBuiltinAnnotationString - Checks that string argument to the builtin
93/// annotation is a non wide string literal.
94static bool CheckBuiltinAnnotationString(Sema &S, Expr *Arg) {
95 Arg = Arg->IgnoreParenCasts();
96 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
97 if (!Literal || !Literal->isAscii()) {
98 S.Diag(Arg->getLocStart(), diag::err_builtin_annotation_not_string_constant)
99 << Arg->getSourceRange();
100 return true;
101 }
102 return false;
103}
104
John McCall60d7b3a2010-08-24 06:29:42 +0000105ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000106Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +0000107 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000108
Chris Lattner946928f2010-10-01 23:23:24 +0000109 // Find out if any arguments are required to be integer constant expressions.
110 unsigned ICEArguments = 0;
111 ASTContext::GetBuiltinTypeError Error;
112 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
113 if (Error != ASTContext::GE_None)
114 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
115
116 // If any arguments are required to be ICE's, check and diagnose.
117 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
118 // Skip arguments not required to be ICE's.
119 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
120
121 llvm::APSInt Result;
122 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
123 return true;
124 ICEArguments &= ~(1 << ArgNo);
125 }
126
Anders Carlssond406bf02009-08-16 01:56:34 +0000127 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000128 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000129 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000130 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000131 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000132 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000133 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000134 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000135 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000136 if (SemaBuiltinVAStart(TheCall))
137 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000138 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000139 case Builtin::BI__builtin_isgreater:
140 case Builtin::BI__builtin_isgreaterequal:
141 case Builtin::BI__builtin_isless:
142 case Builtin::BI__builtin_islessequal:
143 case Builtin::BI__builtin_islessgreater:
144 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000145 if (SemaBuiltinUnorderedCompare(TheCall))
146 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000147 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000148 case Builtin::BI__builtin_fpclassify:
149 if (SemaBuiltinFPClassification(TheCall, 6))
150 return ExprError();
151 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000152 case Builtin::BI__builtin_isfinite:
153 case Builtin::BI__builtin_isinf:
154 case Builtin::BI__builtin_isinf_sign:
155 case Builtin::BI__builtin_isnan:
156 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000157 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000158 return ExprError();
159 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000160 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000161 return SemaBuiltinShuffleVector(TheCall);
162 // TheCall will be freed by the smart pointer here, but that's fine, since
163 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000164 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000165 if (SemaBuiltinPrefetch(TheCall))
166 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000167 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000168 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000169 if (SemaBuiltinObjectSize(TheCall))
170 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000171 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000172 case Builtin::BI__builtin_longjmp:
173 if (SemaBuiltinLongjmp(TheCall))
174 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000175 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000176
177 case Builtin::BI__builtin_classify_type:
178 if (checkArgCount(*this, TheCall, 1)) return true;
179 TheCall->setType(Context.IntTy);
180 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000181 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000182 if (checkArgCount(*this, TheCall, 1)) return true;
183 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000184 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000185 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000186 case Builtin::BI__sync_fetch_and_add_1:
187 case Builtin::BI__sync_fetch_and_add_2:
188 case Builtin::BI__sync_fetch_and_add_4:
189 case Builtin::BI__sync_fetch_and_add_8:
190 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000191 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000192 case Builtin::BI__sync_fetch_and_sub_1:
193 case Builtin::BI__sync_fetch_and_sub_2:
194 case Builtin::BI__sync_fetch_and_sub_4:
195 case Builtin::BI__sync_fetch_and_sub_8:
196 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000197 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000198 case Builtin::BI__sync_fetch_and_or_1:
199 case Builtin::BI__sync_fetch_and_or_2:
200 case Builtin::BI__sync_fetch_and_or_4:
201 case Builtin::BI__sync_fetch_and_or_8:
202 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000203 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000204 case Builtin::BI__sync_fetch_and_and_1:
205 case Builtin::BI__sync_fetch_and_and_2:
206 case Builtin::BI__sync_fetch_and_and_4:
207 case Builtin::BI__sync_fetch_and_and_8:
208 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000209 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000210 case Builtin::BI__sync_fetch_and_xor_1:
211 case Builtin::BI__sync_fetch_and_xor_2:
212 case Builtin::BI__sync_fetch_and_xor_4:
213 case Builtin::BI__sync_fetch_and_xor_8:
214 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000215 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000216 case Builtin::BI__sync_add_and_fetch_1:
217 case Builtin::BI__sync_add_and_fetch_2:
218 case Builtin::BI__sync_add_and_fetch_4:
219 case Builtin::BI__sync_add_and_fetch_8:
220 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000221 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000222 case Builtin::BI__sync_sub_and_fetch_1:
223 case Builtin::BI__sync_sub_and_fetch_2:
224 case Builtin::BI__sync_sub_and_fetch_4:
225 case Builtin::BI__sync_sub_and_fetch_8:
226 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000227 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000228 case Builtin::BI__sync_and_and_fetch_1:
229 case Builtin::BI__sync_and_and_fetch_2:
230 case Builtin::BI__sync_and_and_fetch_4:
231 case Builtin::BI__sync_and_and_fetch_8:
232 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000233 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000234 case Builtin::BI__sync_or_and_fetch_1:
235 case Builtin::BI__sync_or_and_fetch_2:
236 case Builtin::BI__sync_or_and_fetch_4:
237 case Builtin::BI__sync_or_and_fetch_8:
238 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000239 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000240 case Builtin::BI__sync_xor_and_fetch_1:
241 case Builtin::BI__sync_xor_and_fetch_2:
242 case Builtin::BI__sync_xor_and_fetch_4:
243 case Builtin::BI__sync_xor_and_fetch_8:
244 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000245 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000246 case Builtin::BI__sync_val_compare_and_swap_1:
247 case Builtin::BI__sync_val_compare_and_swap_2:
248 case Builtin::BI__sync_val_compare_and_swap_4:
249 case Builtin::BI__sync_val_compare_and_swap_8:
250 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000251 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000252 case Builtin::BI__sync_bool_compare_and_swap_1:
253 case Builtin::BI__sync_bool_compare_and_swap_2:
254 case Builtin::BI__sync_bool_compare_and_swap_4:
255 case Builtin::BI__sync_bool_compare_and_swap_8:
256 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000257 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000258 case Builtin::BI__sync_lock_test_and_set_1:
259 case Builtin::BI__sync_lock_test_and_set_2:
260 case Builtin::BI__sync_lock_test_and_set_4:
261 case Builtin::BI__sync_lock_test_and_set_8:
262 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000263 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000264 case Builtin::BI__sync_lock_release_1:
265 case Builtin::BI__sync_lock_release_2:
266 case Builtin::BI__sync_lock_release_4:
267 case Builtin::BI__sync_lock_release_8:
268 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000269 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000270 case Builtin::BI__sync_swap_1:
271 case Builtin::BI__sync_swap_2:
272 case Builtin::BI__sync_swap_4:
273 case Builtin::BI__sync_swap_8:
274 case Builtin::BI__sync_swap_16:
Chandler Carruthd2014572010-07-09 18:59:35 +0000275 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Eli Friedman276b0612011-10-11 02:20:01 +0000276 case Builtin::BI__atomic_load:
277 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Load);
278 case Builtin::BI__atomic_store:
279 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Store);
David Chisnall7a7ee302012-01-16 17:27:18 +0000280 case Builtin::BI__atomic_init:
281 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Init);
Eli Friedman276b0612011-10-11 02:20:01 +0000282 case Builtin::BI__atomic_exchange:
283 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg);
284 case Builtin::BI__atomic_compare_exchange_strong:
285 return SemaAtomicOpsOverloaded(move(TheCallResult),
286 AtomicExpr::CmpXchgStrong);
287 case Builtin::BI__atomic_compare_exchange_weak:
288 return SemaAtomicOpsOverloaded(move(TheCallResult),
289 AtomicExpr::CmpXchgWeak);
290 case Builtin::BI__atomic_fetch_add:
291 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add);
292 case Builtin::BI__atomic_fetch_sub:
293 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub);
294 case Builtin::BI__atomic_fetch_and:
295 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And);
296 case Builtin::BI__atomic_fetch_or:
297 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or);
298 case Builtin::BI__atomic_fetch_xor:
299 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor);
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000300 case Builtin::BI__builtin_annotation:
301 if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1)))
302 return ExprError();
303 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000304 }
305
306 // Since the target specific builtins for each arch overlap, only check those
307 // of the arch we are compiling for.
308 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000309 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000310 case llvm::Triple::arm:
311 case llvm::Triple::thumb:
312 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
313 return ExprError();
314 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000315 default:
316 break;
317 }
318 }
319
320 return move(TheCallResult);
321}
322
Nate Begeman61eecf52010-06-14 05:21:25 +0000323// Get the valid immediate range for the specified NEON type code.
324static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000325 NeonTypeFlags Type(t);
326 int IsQuad = Type.isQuad();
327 switch (Type.getEltType()) {
328 case NeonTypeFlags::Int8:
329 case NeonTypeFlags::Poly8:
330 return shift ? 7 : (8 << IsQuad) - 1;
331 case NeonTypeFlags::Int16:
332 case NeonTypeFlags::Poly16:
333 return shift ? 15 : (4 << IsQuad) - 1;
334 case NeonTypeFlags::Int32:
335 return shift ? 31 : (2 << IsQuad) - 1;
336 case NeonTypeFlags::Int64:
337 return shift ? 63 : (1 << IsQuad) - 1;
338 case NeonTypeFlags::Float16:
339 assert(!shift && "cannot shift float types!");
340 return (4 << IsQuad) - 1;
341 case NeonTypeFlags::Float32:
342 assert(!shift && "cannot shift float types!");
343 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000344 }
345 return 0;
346}
347
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000348/// getNeonEltType - Return the QualType corresponding to the elements of
349/// the vector type specified by the NeonTypeFlags. This is used to check
350/// the pointer arguments for Neon load/store intrinsics.
351static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
352 switch (Flags.getEltType()) {
353 case NeonTypeFlags::Int8:
354 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
355 case NeonTypeFlags::Int16:
356 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
357 case NeonTypeFlags::Int32:
358 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
359 case NeonTypeFlags::Int64:
360 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
361 case NeonTypeFlags::Poly8:
362 return Context.SignedCharTy;
363 case NeonTypeFlags::Poly16:
364 return Context.ShortTy;
365 case NeonTypeFlags::Float16:
366 return Context.UnsignedShortTy;
367 case NeonTypeFlags::Float32:
368 return Context.FloatTy;
369 }
370 return QualType();
371}
372
Nate Begeman26a31422010-06-08 02:47:44 +0000373bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000374 llvm::APSInt Result;
375
Nate Begeman0d15c532010-06-13 04:47:52 +0000376 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000377 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000378 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000379 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000380 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000381#define GET_NEON_OVERLOAD_CHECK
382#include "clang/Basic/arm_neon.inc"
383#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000384 }
385
Nate Begeman0d15c532010-06-13 04:47:52 +0000386 // For NEON intrinsics which are overloaded on vector element type, validate
387 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000388 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000389 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000390 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000391 return true;
392
Bob Wilsonda95f732011-11-08 01:16:11 +0000393 TV = Result.getLimitedValue(64);
394 if ((TV > 63) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000395 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000396 << TheCall->getArg(ImmArg)->getSourceRange();
397 }
398
Bob Wilson46482552011-11-16 21:32:23 +0000399 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000400 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000401 Expr *Arg = TheCall->getArg(PtrArgNum);
402 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
403 Arg = ICE->getSubExpr();
404 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
405 QualType RHSTy = RHS.get()->getType();
406 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
407 if (HasConstPtr)
408 EltTy = EltTy.withConst();
409 QualType LHSTy = Context.getPointerType(EltTy);
410 AssignConvertType ConvTy;
411 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
412 if (RHS.isInvalid())
413 return true;
414 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
415 RHS.get(), AA_Assigning))
416 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000417 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000418
Nate Begeman0d15c532010-06-13 04:47:52 +0000419 // For NEON intrinsics which take an immediate value as part of the
420 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000421 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000422 switch (BuiltinID) {
423 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000424 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
425 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000426 case ARM::BI__builtin_arm_vcvtr_f:
427 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000428#define GET_NEON_IMMEDIATE_CHECK
429#include "clang/Basic/arm_neon.inc"
430#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000431 };
432
Nate Begeman61eecf52010-06-14 05:21:25 +0000433 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000434 if (SemaBuiltinConstantArg(TheCall, i, Result))
435 return true;
436
Nate Begeman61eecf52010-06-14 05:21:25 +0000437 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000438 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000439 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000440 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000441 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000442
Nate Begeman99c40bb2010-08-03 21:32:34 +0000443 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000444 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000445}
Daniel Dunbarde454282008-10-02 18:44:07 +0000446
Anders Carlssond406bf02009-08-16 01:56:34 +0000447/// CheckFunctionCall - Check a direct function call for various correctness
448/// and safety properties not strictly enforced by the C type system.
449bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
450 // Get the IdentifierInfo* for the called function.
451 IdentifierInfo *FnInfo = FDecl->getIdentifier();
452
453 // None of the checks below are needed for functions that don't have
454 // simple names (e.g., C++ conversion functions).
455 if (!FnInfo)
456 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Daniel Dunbarde454282008-10-02 18:44:07 +0000458 // FIXME: This mechanism should be abstracted to be less fragile and
459 // more efficient. For example, just map function ids to custom
460 // handlers.
461
Ted Kremenekc82faca2010-09-09 04:33:05 +0000462 // Printf and scanf checking.
463 for (specific_attr_iterator<FormatAttr>
464 i = FDecl->specific_attr_begin<FormatAttr>(),
465 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
466
467 const FormatAttr *Format = *i;
Ted Kremenek826a3452010-07-16 02:11:22 +0000468 const bool b = Format->getType() == "scanf";
469 if (b || CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000470 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000471 CheckPrintfScanfArguments(TheCall, HasVAListArg,
472 Format->getFormatIdx() - 1,
473 HasVAListArg ? 0 : Format->getFirstArg() - 1,
474 !b);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000475 }
Chris Lattner59907c42007-08-10 20:18:51 +0000476 }
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Ted Kremenekc82faca2010-09-09 04:33:05 +0000478 for (specific_attr_iterator<NonNullAttr>
479 i = FDecl->specific_attr_begin<NonNullAttr>(),
480 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +0000481 CheckNonNullArguments(*i, TheCall->getArgs(),
482 TheCall->getCallee()->getLocStart());
Ted Kremenekc82faca2010-09-09 04:33:05 +0000483 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000484
Anna Zaksd9b859a2012-01-13 21:52:01 +0000485 FunctionDecl::MemoryFunctionKind CMF = FDecl->getMemoryFunctionKind();
486 if (CMF == FunctionDecl::MFK_Invalid)
487 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000488
Anna Zaksd9b859a2012-01-13 21:52:01 +0000489 // Handle memory setting and copying functions.
490 if (CMF == FunctionDecl::MFK_Strlcpy || CMF == FunctionDecl::MFK_Strlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000491 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000492 else
493 CheckMemaccessArguments(TheCall, CMF, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000494
Anders Carlssond406bf02009-08-16 01:56:34 +0000495 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000496}
497
Anders Carlssond406bf02009-08-16 01:56:34 +0000498bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000499 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000500 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000501 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000502 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000504 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
505 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000506 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000508 QualType Ty = V->getType();
509 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000510 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Ted Kremenek826a3452010-07-16 02:11:22 +0000512 const bool b = Format->getType() == "scanf";
513 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +0000514 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Anders Carlssond406bf02009-08-16 01:56:34 +0000516 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000517 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
518 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssond406bf02009-08-16 01:56:34 +0000519
520 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000521}
522
Eli Friedman276b0612011-10-11 02:20:01 +0000523ExprResult
524Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) {
525 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
526 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000527
528 // All these operations take one of the following four forms:
529 // T __atomic_load(_Atomic(T)*, int) (loads)
530 // T* __atomic_add(_Atomic(T*)*, ptrdiff_t, int) (pointer add/sub)
531 // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
532 // (cmpxchg)
533 // T __atomic_exchange(_Atomic(T)*, T, int) (everything else)
534 // where T is an appropriate type, and the int paremeterss are for orderings.
535 unsigned NumVals = 1;
536 unsigned NumOrders = 1;
537 if (Op == AtomicExpr::Load) {
538 NumVals = 0;
539 } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) {
540 NumVals = 2;
541 NumOrders = 2;
542 }
David Chisnall7a7ee302012-01-16 17:27:18 +0000543 if (Op == AtomicExpr::Init)
544 NumOrders = 0;
Eli Friedman276b0612011-10-11 02:20:01 +0000545
546 if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
547 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
548 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
549 << TheCall->getCallee()->getSourceRange();
550 return ExprError();
551 } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
552 Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
553 diag::err_typecheck_call_too_many_args)
554 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
555 << TheCall->getCallee()->getSourceRange();
556 return ExprError();
557 }
558
559 // Inspect the first argument of the atomic operation. This should always be
560 // a pointer to an _Atomic type.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000561 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000562 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
563 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
564 if (!pointerType) {
565 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
566 << Ptr->getType() << Ptr->getSourceRange();
567 return ExprError();
568 }
569
570 QualType AtomTy = pointerType->getPointeeType();
571 if (!AtomTy->isAtomicType()) {
572 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
573 << Ptr->getType() << Ptr->getSourceRange();
574 return ExprError();
575 }
576 QualType ValType = AtomTy->getAs<AtomicType>()->getValueType();
577
578 if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) &&
579 !ValType->isIntegerType() && !ValType->isPointerType()) {
580 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
581 << Ptr->getType() << Ptr->getSourceRange();
582 return ExprError();
583 }
584
585 if (!ValType->isIntegerType() &&
586 (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){
587 Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
588 << Ptr->getType() << Ptr->getSourceRange();
589 return ExprError();
590 }
591
592 switch (ValType.getObjCLifetime()) {
593 case Qualifiers::OCL_None:
594 case Qualifiers::OCL_ExplicitNone:
595 // okay
596 break;
597
598 case Qualifiers::OCL_Weak:
599 case Qualifiers::OCL_Strong:
600 case Qualifiers::OCL_Autoreleasing:
601 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
602 << ValType << Ptr->getSourceRange();
603 return ExprError();
604 }
605
606 QualType ResultType = ValType;
David Chisnall7a7ee302012-01-16 17:27:18 +0000607 if (Op == AtomicExpr::Store || Op == AtomicExpr::Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000608 ResultType = Context.VoidTy;
609 else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong)
610 ResultType = Context.BoolTy;
611
612 // The first argument --- the pointer --- has a fixed type; we
613 // deduce the types of the rest of the arguments accordingly. Walk
614 // the remaining arguments, converting them to the deduced value type.
615 for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) {
616 ExprResult Arg = TheCall->getArg(i);
617 QualType Ty;
618 if (i < NumVals+1) {
619 // The second argument to a cmpxchg is a pointer to the data which will
620 // be exchanged. The second argument to a pointer add/subtract is the
621 // amount to add/subtract, which must be a ptrdiff_t. The third
622 // argument to a cmpxchg and the second argument in all other cases
623 // is the type of the value.
624 if (i == 1 && (Op == AtomicExpr::CmpXchgWeak ||
625 Op == AtomicExpr::CmpXchgStrong))
626 Ty = Context.getPointerType(ValType.getUnqualifiedType());
627 else if (!ValType->isIntegerType() &&
628 (Op == AtomicExpr::Add || Op == AtomicExpr::Sub))
629 Ty = Context.getPointerDiffType();
630 else
631 Ty = ValType;
632 } else {
633 // The order(s) are always converted to int.
634 Ty = Context.IntTy;
635 }
636 InitializedEntity Entity =
637 InitializedEntity::InitializeParameter(Context, Ty, false);
638 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
639 if (Arg.isInvalid())
640 return true;
641 TheCall->setArg(i, Arg.get());
642 }
643
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000644 SmallVector<Expr*, 5> SubExprs;
645 SubExprs.push_back(Ptr);
Eli Friedman276b0612011-10-11 02:20:01 +0000646 if (Op == AtomicExpr::Load) {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000647 SubExprs.push_back(TheCall->getArg(1)); // Order
David Chisnall7a7ee302012-01-16 17:27:18 +0000648 } else if (Op == AtomicExpr::Init) {
649 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman276b0612011-10-11 02:20:01 +0000650 } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000651 SubExprs.push_back(TheCall->getArg(2)); // Order
652 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman276b0612011-10-11 02:20:01 +0000653 } else {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000654 SubExprs.push_back(TheCall->getArg(3)); // Order
655 SubExprs.push_back(TheCall->getArg(1)); // Val1
656 SubExprs.push_back(TheCall->getArg(2)); // Val2
657 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
Eli Friedman276b0612011-10-11 02:20:01 +0000658 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000659
660 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
661 SubExprs.data(), SubExprs.size(),
662 ResultType, Op,
663 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000664}
665
666
John McCall5f8d6042011-08-27 01:09:30 +0000667/// checkBuiltinArgument - Given a call to a builtin function, perform
668/// normal type-checking on the given argument, updating the call in
669/// place. This is useful when a builtin function requires custom
670/// type-checking for some of its arguments but not necessarily all of
671/// them.
672///
673/// Returns true on error.
674static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
675 FunctionDecl *Fn = E->getDirectCallee();
676 assert(Fn && "builtin call without direct callee!");
677
678 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
679 InitializedEntity Entity =
680 InitializedEntity::InitializeParameter(S.Context, Param);
681
682 ExprResult Arg = E->getArg(0);
683 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
684 if (Arg.isInvalid())
685 return true;
686
687 E->setArg(ArgIndex, Arg.take());
688 return false;
689}
690
Chris Lattner5caa3702009-05-08 06:58:22 +0000691/// SemaBuiltinAtomicOverloaded - We have a call to a function like
692/// __sync_fetch_and_add, which is an overloaded function based on the pointer
693/// type of its first argument. The main ActOnCallExpr routines have already
694/// promoted the types of arguments because all of these calls are prototyped as
695/// void(...).
696///
697/// This function goes through and does final semantic checking for these
698/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000699ExprResult
700Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000701 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000702 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
703 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
704
705 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000706 if (TheCall->getNumArgs() < 1) {
707 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
708 << 0 << 1 << TheCall->getNumArgs()
709 << TheCall->getCallee()->getSourceRange();
710 return ExprError();
711 }
Mike Stump1eb44332009-09-09 15:08:12 +0000712
Chris Lattner5caa3702009-05-08 06:58:22 +0000713 // Inspect the first argument of the atomic builtin. This should always be
714 // a pointer type, whose element is an integral scalar or pointer type.
715 // Because it is a pointer type, we don't have to worry about any implicit
716 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000717 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000718 Expr *FirstArg = TheCall->getArg(0);
John McCallf85e1932011-06-15 23:02:42 +0000719 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
720 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000721 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
722 << FirstArg->getType() << FirstArg->getSourceRange();
723 return ExprError();
724 }
Mike Stump1eb44332009-09-09 15:08:12 +0000725
John McCallf85e1932011-06-15 23:02:42 +0000726 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000727 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000728 !ValType->isBlockPointerType()) {
729 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
730 << FirstArg->getType() << FirstArg->getSourceRange();
731 return ExprError();
732 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000733
John McCallf85e1932011-06-15 23:02:42 +0000734 switch (ValType.getObjCLifetime()) {
735 case Qualifiers::OCL_None:
736 case Qualifiers::OCL_ExplicitNone:
737 // okay
738 break;
739
740 case Qualifiers::OCL_Weak:
741 case Qualifiers::OCL_Strong:
742 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000743 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000744 << ValType << FirstArg->getSourceRange();
745 return ExprError();
746 }
747
John McCallb45ae252011-10-05 07:41:44 +0000748 // Strip any qualifiers off ValType.
749 ValType = ValType.getUnqualifiedType();
750
Chandler Carruth8d13d222010-07-18 20:54:12 +0000751 // The majority of builtins return a value, but a few have special return
752 // types, so allow them to override appropriately below.
753 QualType ResultType = ValType;
754
Chris Lattner5caa3702009-05-08 06:58:22 +0000755 // We need to figure out which concrete builtin this maps onto. For example,
756 // __sync_fetch_and_add with a 2 byte object turns into
757 // __sync_fetch_and_add_2.
758#define BUILTIN_ROW(x) \
759 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
760 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Chris Lattner5caa3702009-05-08 06:58:22 +0000762 static const unsigned BuiltinIndices[][5] = {
763 BUILTIN_ROW(__sync_fetch_and_add),
764 BUILTIN_ROW(__sync_fetch_and_sub),
765 BUILTIN_ROW(__sync_fetch_and_or),
766 BUILTIN_ROW(__sync_fetch_and_and),
767 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000768
Chris Lattner5caa3702009-05-08 06:58:22 +0000769 BUILTIN_ROW(__sync_add_and_fetch),
770 BUILTIN_ROW(__sync_sub_and_fetch),
771 BUILTIN_ROW(__sync_and_and_fetch),
772 BUILTIN_ROW(__sync_or_and_fetch),
773 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000774
Chris Lattner5caa3702009-05-08 06:58:22 +0000775 BUILTIN_ROW(__sync_val_compare_and_swap),
776 BUILTIN_ROW(__sync_bool_compare_and_swap),
777 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000778 BUILTIN_ROW(__sync_lock_release),
779 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000780 };
Mike Stump1eb44332009-09-09 15:08:12 +0000781#undef BUILTIN_ROW
782
Chris Lattner5caa3702009-05-08 06:58:22 +0000783 // Determine the index of the size.
784 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000785 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000786 case 1: SizeIndex = 0; break;
787 case 2: SizeIndex = 1; break;
788 case 4: SizeIndex = 2; break;
789 case 8: SizeIndex = 3; break;
790 case 16: SizeIndex = 4; break;
791 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000792 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
793 << FirstArg->getType() << FirstArg->getSourceRange();
794 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000795 }
Mike Stump1eb44332009-09-09 15:08:12 +0000796
Chris Lattner5caa3702009-05-08 06:58:22 +0000797 // Each of these builtins has one pointer argument, followed by some number of
798 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
799 // that we ignore. Find out which row of BuiltinIndices to read from as well
800 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000801 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000802 unsigned BuiltinIndex, NumFixed = 1;
803 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000804 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +0000805 case Builtin::BI__sync_fetch_and_add:
806 case Builtin::BI__sync_fetch_and_add_1:
807 case Builtin::BI__sync_fetch_and_add_2:
808 case Builtin::BI__sync_fetch_and_add_4:
809 case Builtin::BI__sync_fetch_and_add_8:
810 case Builtin::BI__sync_fetch_and_add_16:
811 BuiltinIndex = 0;
812 break;
813
814 case Builtin::BI__sync_fetch_and_sub:
815 case Builtin::BI__sync_fetch_and_sub_1:
816 case Builtin::BI__sync_fetch_and_sub_2:
817 case Builtin::BI__sync_fetch_and_sub_4:
818 case Builtin::BI__sync_fetch_and_sub_8:
819 case Builtin::BI__sync_fetch_and_sub_16:
820 BuiltinIndex = 1;
821 break;
822
823 case Builtin::BI__sync_fetch_and_or:
824 case Builtin::BI__sync_fetch_and_or_1:
825 case Builtin::BI__sync_fetch_and_or_2:
826 case Builtin::BI__sync_fetch_and_or_4:
827 case Builtin::BI__sync_fetch_and_or_8:
828 case Builtin::BI__sync_fetch_and_or_16:
829 BuiltinIndex = 2;
830 break;
831
832 case Builtin::BI__sync_fetch_and_and:
833 case Builtin::BI__sync_fetch_and_and_1:
834 case Builtin::BI__sync_fetch_and_and_2:
835 case Builtin::BI__sync_fetch_and_and_4:
836 case Builtin::BI__sync_fetch_and_and_8:
837 case Builtin::BI__sync_fetch_and_and_16:
838 BuiltinIndex = 3;
839 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000840
Douglas Gregora9766412011-11-28 16:30:08 +0000841 case Builtin::BI__sync_fetch_and_xor:
842 case Builtin::BI__sync_fetch_and_xor_1:
843 case Builtin::BI__sync_fetch_and_xor_2:
844 case Builtin::BI__sync_fetch_and_xor_4:
845 case Builtin::BI__sync_fetch_and_xor_8:
846 case Builtin::BI__sync_fetch_and_xor_16:
847 BuiltinIndex = 4;
848 break;
849
850 case Builtin::BI__sync_add_and_fetch:
851 case Builtin::BI__sync_add_and_fetch_1:
852 case Builtin::BI__sync_add_and_fetch_2:
853 case Builtin::BI__sync_add_and_fetch_4:
854 case Builtin::BI__sync_add_and_fetch_8:
855 case Builtin::BI__sync_add_and_fetch_16:
856 BuiltinIndex = 5;
857 break;
858
859 case Builtin::BI__sync_sub_and_fetch:
860 case Builtin::BI__sync_sub_and_fetch_1:
861 case Builtin::BI__sync_sub_and_fetch_2:
862 case Builtin::BI__sync_sub_and_fetch_4:
863 case Builtin::BI__sync_sub_and_fetch_8:
864 case Builtin::BI__sync_sub_and_fetch_16:
865 BuiltinIndex = 6;
866 break;
867
868 case Builtin::BI__sync_and_and_fetch:
869 case Builtin::BI__sync_and_and_fetch_1:
870 case Builtin::BI__sync_and_and_fetch_2:
871 case Builtin::BI__sync_and_and_fetch_4:
872 case Builtin::BI__sync_and_and_fetch_8:
873 case Builtin::BI__sync_and_and_fetch_16:
874 BuiltinIndex = 7;
875 break;
876
877 case Builtin::BI__sync_or_and_fetch:
878 case Builtin::BI__sync_or_and_fetch_1:
879 case Builtin::BI__sync_or_and_fetch_2:
880 case Builtin::BI__sync_or_and_fetch_4:
881 case Builtin::BI__sync_or_and_fetch_8:
882 case Builtin::BI__sync_or_and_fetch_16:
883 BuiltinIndex = 8;
884 break;
885
886 case Builtin::BI__sync_xor_and_fetch:
887 case Builtin::BI__sync_xor_and_fetch_1:
888 case Builtin::BI__sync_xor_and_fetch_2:
889 case Builtin::BI__sync_xor_and_fetch_4:
890 case Builtin::BI__sync_xor_and_fetch_8:
891 case Builtin::BI__sync_xor_and_fetch_16:
892 BuiltinIndex = 9;
893 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000894
Chris Lattner5caa3702009-05-08 06:58:22 +0000895 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000896 case Builtin::BI__sync_val_compare_and_swap_1:
897 case Builtin::BI__sync_val_compare_and_swap_2:
898 case Builtin::BI__sync_val_compare_and_swap_4:
899 case Builtin::BI__sync_val_compare_and_swap_8:
900 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000901 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000902 NumFixed = 2;
903 break;
Douglas Gregora9766412011-11-28 16:30:08 +0000904
Chris Lattner5caa3702009-05-08 06:58:22 +0000905 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000906 case Builtin::BI__sync_bool_compare_and_swap_1:
907 case Builtin::BI__sync_bool_compare_and_swap_2:
908 case Builtin::BI__sync_bool_compare_and_swap_4:
909 case Builtin::BI__sync_bool_compare_and_swap_8:
910 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000911 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000912 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000913 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000914 break;
Douglas Gregora9766412011-11-28 16:30:08 +0000915
916 case Builtin::BI__sync_lock_test_and_set:
917 case Builtin::BI__sync_lock_test_and_set_1:
918 case Builtin::BI__sync_lock_test_and_set_2:
919 case Builtin::BI__sync_lock_test_and_set_4:
920 case Builtin::BI__sync_lock_test_and_set_8:
921 case Builtin::BI__sync_lock_test_and_set_16:
922 BuiltinIndex = 12;
923 break;
924
Chris Lattner5caa3702009-05-08 06:58:22 +0000925 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000926 case Builtin::BI__sync_lock_release_1:
927 case Builtin::BI__sync_lock_release_2:
928 case Builtin::BI__sync_lock_release_4:
929 case Builtin::BI__sync_lock_release_8:
930 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000931 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000932 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000933 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000934 break;
Douglas Gregora9766412011-11-28 16:30:08 +0000935
936 case Builtin::BI__sync_swap:
937 case Builtin::BI__sync_swap_1:
938 case Builtin::BI__sync_swap_2:
939 case Builtin::BI__sync_swap_4:
940 case Builtin::BI__sync_swap_8:
941 case Builtin::BI__sync_swap_16:
942 BuiltinIndex = 14;
943 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000944 }
Mike Stump1eb44332009-09-09 15:08:12 +0000945
Chris Lattner5caa3702009-05-08 06:58:22 +0000946 // Now that we know how many fixed arguments we expect, first check that we
947 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000948 if (TheCall->getNumArgs() < 1+NumFixed) {
949 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
950 << 0 << 1+NumFixed << TheCall->getNumArgs()
951 << TheCall->getCallee()->getSourceRange();
952 return ExprError();
953 }
Mike Stump1eb44332009-09-09 15:08:12 +0000954
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000955 // Get the decl for the concrete builtin from this, we can tell what the
956 // concrete integer type we should convert to is.
957 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
958 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
959 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000960 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000961 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
962 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000963
John McCallf871d0c2010-08-07 06:22:56 +0000964 // The first argument --- the pointer --- has a fixed type; we
965 // deduce the types of the rest of the arguments accordingly. Walk
966 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000967 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +0000968 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Chris Lattner5caa3702009-05-08 06:58:22 +0000970 // GCC does an implicit conversion to the pointer or integer ValType. This
971 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +0000972 // Initialize the argument.
973 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
974 ValType, /*consume*/ false);
975 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +0000976 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +0000977 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Chris Lattner5caa3702009-05-08 06:58:22 +0000979 // Okay, we have something that *can* be converted to the right type. Check
980 // to see if there is a potentially weird extension going on here. This can
981 // happen when you do an atomic operation on something like an char* and
982 // pass in 42. The 42 gets converted to char. This is even more strange
983 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000984 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +0000985 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +0000986 }
Mike Stump1eb44332009-09-09 15:08:12 +0000987
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000988 ASTContext& Context = this->getASTContext();
989
990 // Create a new DeclRefExpr to refer to the new decl.
991 DeclRefExpr* NewDRE = DeclRefExpr::Create(
992 Context,
993 DRE->getQualifierLoc(),
994 NewBuiltinDecl,
995 DRE->getLocation(),
996 NewBuiltinDecl->getType(),
997 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Chris Lattner5caa3702009-05-08 06:58:22 +0000999 // Set the callee in the CallExpr.
1000 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001001 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley429bb272011-04-08 18:41:53 +00001002 if (PromotedCall.isInvalid())
1003 return ExprError();
1004 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001005
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001006 // Change the result type of the call to match the original value type. This
1007 // is arbitrary, but the codegen for these builtins ins design to handle it
1008 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001009 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001010
1011 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +00001012}
1013
Chris Lattner69039812009-02-18 06:01:06 +00001014/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001015/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001016/// Note: It might also make sense to do the UTF-16 conversion here (would
1017/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001018bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001019 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001020 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1021
Douglas Gregor5cee1192011-07-27 05:40:30 +00001022 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001023 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1024 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001025 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001026 }
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001028 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001029 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001030 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001031 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001032 const UTF8 *FromPtr = (UTF8 *)String.data();
1033 UTF16 *ToPtr = &ToBuf[0];
1034
1035 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1036 &ToPtr, ToPtr + NumBytes,
1037 strictConversion);
1038 // Check for conversion failure.
1039 if (Result != conversionOK)
1040 Diag(Arg->getLocStart(),
1041 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1042 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001043 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001044}
1045
Chris Lattnerc27c6652007-12-20 00:05:45 +00001046/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1047/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001048bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1049 Expr *Fn = TheCall->getCallee();
1050 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001051 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001052 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001053 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1054 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001055 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001056 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001057 return true;
1058 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001059
1060 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001061 return Diag(TheCall->getLocEnd(),
1062 diag::err_typecheck_call_too_few_args_at_least)
1063 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001064 }
1065
John McCall5f8d6042011-08-27 01:09:30 +00001066 // Type-check the first argument normally.
1067 if (checkBuiltinArgument(*this, TheCall, 0))
1068 return true;
1069
Chris Lattnerc27c6652007-12-20 00:05:45 +00001070 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001071 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001072 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001073 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001074 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001075 else if (FunctionDecl *FD = getCurFunctionDecl())
1076 isVariadic = FD->isVariadic();
1077 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001078 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001079
Chris Lattnerc27c6652007-12-20 00:05:45 +00001080 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001081 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1082 return true;
1083 }
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Chris Lattner30ce3442007-12-19 23:59:04 +00001085 // Verify that the second argument to the builtin is the last argument of the
1086 // current function or method.
1087 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001088 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001089
Anders Carlsson88cf2262008-02-11 04:20:54 +00001090 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1091 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001092 // FIXME: This isn't correct for methods (results in bogus warning).
1093 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001094 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001095 if (CurBlock)
1096 LastArg = *(CurBlock->TheDecl->param_end()-1);
1097 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001098 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001099 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001100 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001101 SecondArgIsLastNamedArgument = PV == LastArg;
1102 }
1103 }
Mike Stump1eb44332009-09-09 15:08:12 +00001104
Chris Lattner30ce3442007-12-19 23:59:04 +00001105 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001106 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001107 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1108 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001109}
Chris Lattner30ce3442007-12-19 23:59:04 +00001110
Chris Lattner1b9a0792007-12-20 00:26:33 +00001111/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1112/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001113bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1114 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001115 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001116 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001117 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001118 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001119 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001120 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001121 << SourceRange(TheCall->getArg(2)->getLocStart(),
1122 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001123
John Wiegley429bb272011-04-08 18:41:53 +00001124 ExprResult OrigArg0 = TheCall->getArg(0);
1125 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001126
Chris Lattner1b9a0792007-12-20 00:26:33 +00001127 // Do standard promotions between the two arguments, returning their common
1128 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001129 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001130 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1131 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001132
1133 // Make sure any conversions are pushed back into the call; this is
1134 // type safe since unordered compare builtins are declared as "_Bool
1135 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001136 TheCall->setArg(0, OrigArg0.get());
1137 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001138
John Wiegley429bb272011-04-08 18:41:53 +00001139 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001140 return false;
1141
Chris Lattner1b9a0792007-12-20 00:26:33 +00001142 // If the common type isn't a real floating type, then the arguments were
1143 // invalid for this operation.
1144 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001145 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001146 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001147 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1148 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001149
Chris Lattner1b9a0792007-12-20 00:26:33 +00001150 return false;
1151}
1152
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001153/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1154/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001155/// to check everything. We expect the last argument to be a floating point
1156/// value.
1157bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1158 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001159 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001160 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001161 if (TheCall->getNumArgs() > NumArgs)
1162 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001163 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001164 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001165 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001166 (*(TheCall->arg_end()-1))->getLocEnd());
1167
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001168 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001169
Eli Friedman9ac6f622009-08-31 20:06:00 +00001170 if (OrigArg->isTypeDependent())
1171 return false;
1172
Chris Lattner81368fb2010-05-06 05:50:07 +00001173 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001174 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001175 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001176 diag::err_typecheck_call_invalid_unary_fp)
1177 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001178
Chris Lattner81368fb2010-05-06 05:50:07 +00001179 // If this is an implicit conversion from float -> double, remove it.
1180 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1181 Expr *CastArg = Cast->getSubExpr();
1182 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1183 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1184 "promotion from float to double is the only expected cast here");
1185 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001186 TheCall->setArg(NumArgs-1, CastArg);
1187 OrigArg = CastArg;
1188 }
1189 }
1190
Eli Friedman9ac6f622009-08-31 20:06:00 +00001191 return false;
1192}
1193
Eli Friedmand38617c2008-05-14 19:38:39 +00001194/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1195// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001196ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001197 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001198 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001199 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001200 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001201 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001202
Nate Begeman37b6a572010-06-08 00:16:34 +00001203 // Determine which of the following types of shufflevector we're checking:
1204 // 1) unary, vector mask: (lhs, mask)
1205 // 2) binary, vector mask: (lhs, rhs, mask)
1206 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1207 QualType resType = TheCall->getArg(0)->getType();
1208 unsigned numElements = 0;
1209
Douglas Gregorcde01732009-05-19 22:10:17 +00001210 if (!TheCall->getArg(0)->isTypeDependent() &&
1211 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001212 QualType LHSType = TheCall->getArg(0)->getType();
1213 QualType RHSType = TheCall->getArg(1)->getType();
1214
1215 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001216 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001217 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001218 TheCall->getArg(1)->getLocEnd());
1219 return ExprError();
1220 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001221
1222 numElements = LHSType->getAs<VectorType>()->getNumElements();
1223 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Nate Begeman37b6a572010-06-08 00:16:34 +00001225 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1226 // with mask. If so, verify that RHS is an integer vector type with the
1227 // same number of elts as lhs.
1228 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001229 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001230 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1231 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1232 << SourceRange(TheCall->getArg(1)->getLocStart(),
1233 TheCall->getArg(1)->getLocEnd());
1234 numResElements = numElements;
1235 }
1236 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001237 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001238 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001239 TheCall->getArg(1)->getLocEnd());
1240 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001241 } else if (numElements != numResElements) {
1242 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001243 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001244 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001245 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001246 }
1247
1248 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001249 if (TheCall->getArg(i)->isTypeDependent() ||
1250 TheCall->getArg(i)->isValueDependent())
1251 continue;
1252
Nate Begeman37b6a572010-06-08 00:16:34 +00001253 llvm::APSInt Result(32);
1254 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1255 return ExprError(Diag(TheCall->getLocStart(),
1256 diag::err_shufflevector_nonconstant_argument)
1257 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001258
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001259 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001260 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001261 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001262 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001263 }
1264
Chris Lattner5f9e2722011-07-23 10:55:15 +00001265 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001266
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001267 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001268 exprs.push_back(TheCall->getArg(i));
1269 TheCall->setArg(i, 0);
1270 }
1271
Nate Begemana88dc302009-08-12 02:10:25 +00001272 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +00001273 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001274 TheCall->getCallee()->getLocStart(),
1275 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001276}
Chris Lattner30ce3442007-12-19 23:59:04 +00001277
Daniel Dunbar4493f792008-07-21 22:59:13 +00001278/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1279// This is declared to take (const void*, ...) and can take two
1280// optional constant int args.
1281bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001282 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001283
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001284 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001285 return Diag(TheCall->getLocEnd(),
1286 diag::err_typecheck_call_too_many_args_at_most)
1287 << 0 /*function call*/ << 3 << NumArgs
1288 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001289
1290 // Argument 0 is checked for us and the remaining arguments must be
1291 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001292 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001293 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +00001294
Eli Friedman9aef7262009-12-04 00:30:06 +00001295 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001296 if (SemaBuiltinConstantArg(TheCall, i, Result))
1297 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001298
Daniel Dunbar4493f792008-07-21 22:59:13 +00001299 // FIXME: gcc issues a warning and rewrites these to 0. These
1300 // seems especially odd for the third argument since the default
1301 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001302 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001303 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001304 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001305 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001306 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001307 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001308 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001309 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001310 }
1311 }
1312
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001313 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001314}
1315
Eric Christopher691ebc32010-04-17 02:26:23 +00001316/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1317/// TheCall is a constant expression.
1318bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1319 llvm::APSInt &Result) {
1320 Expr *Arg = TheCall->getArg(ArgNum);
1321 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1322 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1323
1324 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1325
1326 if (!Arg->isIntegerConstantExpr(Result, Context))
1327 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001328 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001329
Chris Lattner21fb98e2009-09-23 06:06:36 +00001330 return false;
1331}
1332
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001333/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1334/// int type). This simply type checks that type is one of the defined
1335/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001336// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001337bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001338 llvm::APSInt Result;
1339
1340 // Check constant-ness first.
1341 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1342 return true;
1343
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001344 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001345 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001346 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1347 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001348 }
1349
1350 return false;
1351}
1352
Eli Friedman586d6a82009-05-03 06:04:26 +00001353/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001354/// This checks that val is a constant 1.
1355bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1356 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001357 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001358
Eric Christopher691ebc32010-04-17 02:26:23 +00001359 // TODO: This is less than ideal. Overload this to take a value.
1360 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1361 return true;
1362
1363 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001364 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1365 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1366
1367 return false;
1368}
1369
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001370// Handle i > 1 ? "x" : "y", recursively.
Ted Kremenek082d9362009-03-20 21:35:28 +00001371bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
1372 bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001373 unsigned format_idx, unsigned firstDataArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001374 bool isPrintf, bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001375 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001376 if (E->isTypeDependent() || E->isValueDependent())
1377 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001378
Peter Collingbournef111d932011-04-15 00:35:48 +00001379 E = E->IgnoreParens();
1380
Ted Kremenekd30ef872009-01-12 23:09:09 +00001381 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001382 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001383 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +00001384 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Ted Kremenek826a3452010-07-16 02:11:22 +00001385 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001386 format_idx, firstDataArg, isPrintf,
1387 inFunctionCall)
John McCall56ca35d2011-02-17 10:25:35 +00001388 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001389 format_idx, firstDataArg, isPrintf,
1390 inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001391 }
1392
Ted Kremenek95355bb2010-09-09 03:51:42 +00001393 case Stmt::IntegerLiteralClass:
1394 // Technically -Wformat-nonliteral does not warn about this case.
1395 // The behavior of printf and friends in this case is implementation
1396 // dependent. Ideally if the format string cannot be null then
1397 // it should have a 'nonnull' attribute in the function prototype.
1398 return true;
1399
Ted Kremenekd30ef872009-01-12 23:09:09 +00001400 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001401 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1402 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001403 }
1404
John McCall56ca35d2011-02-17 10:25:35 +00001405 case Stmt::OpaqueValueExprClass:
1406 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1407 E = src;
1408 goto tryAgain;
1409 }
1410 return false;
1411
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001412 case Stmt::PredefinedExprClass:
1413 // While __func__, etc., are technically not string literals, they
1414 // cannot contain format specifiers and thus are not a security
1415 // liability.
1416 return true;
1417
Ted Kremenek082d9362009-03-20 21:35:28 +00001418 case Stmt::DeclRefExprClass: {
1419 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001420
Ted Kremenek082d9362009-03-20 21:35:28 +00001421 // As an exception, do not flag errors for variables binding to
1422 // const string literals.
1423 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1424 bool isConstant = false;
1425 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001426
Ted Kremenek082d9362009-03-20 21:35:28 +00001427 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1428 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001429 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001430 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001431 PT->getPointeeType().isConstant(Context);
1432 }
Mike Stump1eb44332009-09-09 15:08:12 +00001433
Ted Kremenek082d9362009-03-20 21:35:28 +00001434 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001435 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +00001436 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek826a3452010-07-16 02:11:22 +00001437 HasVAListArg, format_idx, firstDataArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001438 isPrintf, /*inFunctionCall*/false);
Ted Kremenek082d9362009-03-20 21:35:28 +00001439 }
Mike Stump1eb44332009-09-09 15:08:12 +00001440
Anders Carlssond966a552009-06-28 19:55:58 +00001441 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1442 // special check to see if the format string is a function parameter
1443 // of the function calling the printf function. If the function
1444 // has an attribute indicating it is a printf-like function, then we
1445 // should suppress warnings concerning non-literals being used in a call
1446 // to a vprintf function. For example:
1447 //
1448 // void
1449 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1450 // va_list ap;
1451 // va_start(ap, fmt);
1452 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1453 // ...
1454 //
1455 //
1456 // FIXME: We don't have full attribute support yet, so just check to see
1457 // if the argument is a DeclRefExpr that references a parameter. We'll
1458 // add proper support for checking the attribute later.
1459 if (HasVAListArg)
1460 if (isa<ParmVarDecl>(VD))
1461 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +00001462 }
Mike Stump1eb44332009-09-09 15:08:12 +00001463
Ted Kremenek082d9362009-03-20 21:35:28 +00001464 return false;
1465 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001466
Anders Carlsson8f031b32009-06-27 04:05:33 +00001467 case Stmt::CallExprClass: {
1468 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001469 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +00001470 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1471 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1472 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001473 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001474 unsigned ArgIndex = FA->getFormatIdx();
1475 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001476
1477 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001478 format_idx, firstDataArg, isPrintf,
1479 inFunctionCall);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001480 }
1481 }
1482 }
1483 }
Mike Stump1eb44332009-09-09 15:08:12 +00001484
Anders Carlsson8f031b32009-06-27 04:05:33 +00001485 return false;
1486 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001487 case Stmt::ObjCStringLiteralClass:
1488 case Stmt::StringLiteralClass: {
1489 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001490
Ted Kremenek082d9362009-03-20 21:35:28 +00001491 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001492 StrE = ObjCFExpr->getString();
1493 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001494 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001495
Ted Kremenekd30ef872009-01-12 23:09:09 +00001496 if (StrE) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001497 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00001498 firstDataArg, isPrintf, inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001499 return true;
1500 }
Mike Stump1eb44332009-09-09 15:08:12 +00001501
Ted Kremenekd30ef872009-01-12 23:09:09 +00001502 return false;
1503 }
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Ted Kremenek082d9362009-03-20 21:35:28 +00001505 default:
1506 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001507 }
1508}
1509
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001510void
Mike Stump1eb44332009-09-09 15:08:12 +00001511Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001512 const Expr * const *ExprArgs,
1513 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001514 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1515 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001516 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001517 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001518 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001519 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001520 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001521 }
1522}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001523
Ted Kremenek826a3452010-07-16 02:11:22 +00001524/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1525/// functions) for correct use of format strings.
Chris Lattner59907c42007-08-10 20:18:51 +00001526void
Ted Kremenek826a3452010-07-16 02:11:22 +00001527Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1528 unsigned format_idx, unsigned firstDataArg,
1529 bool isPrintf) {
1530
Ted Kremenek082d9362009-03-20 21:35:28 +00001531 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001532
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001533 // The way the format attribute works in GCC, the implicit this argument
1534 // of member functions is counted. However, it doesn't appear in our own
1535 // lists, so decrement format_idx in that case.
1536 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth9263a302010-11-16 08:49:43 +00001537 const CXXMethodDecl *method_decl =
1538 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1539 if (method_decl && method_decl->isInstance()) {
1540 // Catch a format attribute mistakenly referring to the object argument.
1541 if (format_idx == 0)
1542 return;
1543 --format_idx;
1544 if(firstDataArg != 0)
1545 --firstDataArg;
1546 }
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001547 }
1548
Ted Kremenek826a3452010-07-16 02:11:22 +00001549 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001550 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001551 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001552 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001553 return;
1554 }
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Ted Kremenek082d9362009-03-20 21:35:28 +00001556 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001557
Chris Lattner59907c42007-08-10 20:18:51 +00001558 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001559 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001560 // Dynamically generated format strings are difficult to
1561 // automatically vet at compile time. Requiring that format strings
1562 // are string literals: (1) permits the checking of format strings by
1563 // the compiler and thereby (2) can practically remove the source of
1564 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001565
Mike Stump1eb44332009-09-09 15:08:12 +00001566 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001567 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001568 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001569 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001570 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek826a3452010-07-16 02:11:22 +00001571 firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001572 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001573
Chris Lattner655f1412009-04-29 04:59:47 +00001574 // If there are no arguments specified, warn with -Wformat-security, otherwise
1575 // warn only with -Wformat-nonliteral.
1576 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001577 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001578 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001579 << OrigFormatExpr->getSourceRange();
1580 else
Mike Stump1eb44332009-09-09 15:08:12 +00001581 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001582 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001583 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001584}
Ted Kremenek71895b92007-08-14 17:39:48 +00001585
Ted Kremeneke0e53132010-01-28 23:39:18 +00001586namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001587class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1588protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001589 Sema &S;
1590 const StringLiteral *FExpr;
1591 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001592 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001593 const unsigned NumDataArgs;
1594 const bool IsObjCLiteral;
1595 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001596 const bool HasVAListArg;
1597 const CallExpr *TheCall;
1598 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001599 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001600 bool usesPositionalArgs;
1601 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001602 bool inFunctionCall;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001603public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001604 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001605 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001606 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001607 const char *beg, bool hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001608 const CallExpr *theCall, unsigned formatIdx,
1609 bool inFunctionCall)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001610 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001611 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001612 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001613 IsObjCLiteral(isObjCLiteral), Beg(beg),
1614 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001615 TheCall(theCall), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001616 usesPositionalArgs(false), atFirstArg(true),
1617 inFunctionCall(inFunctionCall) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001618 CoveredArgs.resize(numDataArgs);
1619 CoveredArgs.reset();
1620 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001621
Ted Kremenek07d161f2010-01-29 01:50:07 +00001622 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001623
Ted Kremenek826a3452010-07-16 02:11:22 +00001624 void HandleIncompleteSpecifier(const char *startSpecifier,
1625 unsigned specifierLen);
1626
Ted Kremenekefaff192010-02-27 01:41:03 +00001627 virtual void HandleInvalidPosition(const char *startSpecifier,
1628 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001629 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001630
1631 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1632
Ted Kremeneke0e53132010-01-28 23:39:18 +00001633 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001634
Richard Trieu55733de2011-10-28 00:41:25 +00001635 template <typename Range>
1636 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1637 const Expr *ArgumentExpr,
1638 PartialDiagnostic PDiag,
1639 SourceLocation StringLoc,
1640 bool IsStringLocation, Range StringRange,
1641 FixItHint Fixit = FixItHint());
1642
Ted Kremenek826a3452010-07-16 02:11:22 +00001643protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001644 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1645 const char *startSpec,
1646 unsigned specifierLen,
1647 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00001648
1649 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1650 const char *startSpec,
1651 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001652
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001653 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001654 CharSourceRange getSpecifierRange(const char *startSpecifier,
1655 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001656 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001657
Ted Kremenek0d277352010-01-29 01:06:55 +00001658 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001659
1660 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1661 const analyze_format_string::ConversionSpecifier &CS,
1662 const char *startSpecifier, unsigned specifierLen,
1663 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00001664
1665 template <typename Range>
1666 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1667 bool IsStringLocation, Range StringRange,
1668 FixItHint Fixit = FixItHint());
1669
1670 void CheckPositionalAndNonpositionalArgs(
1671 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001672};
1673}
1674
Ted Kremenek826a3452010-07-16 02:11:22 +00001675SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001676 return OrigFormatExpr->getSourceRange();
1677}
1678
Ted Kremenek826a3452010-07-16 02:11:22 +00001679CharSourceRange CheckFormatHandler::
1680getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001681 SourceLocation Start = getLocationOfByte(startSpecifier);
1682 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1683
1684 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001685 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00001686
1687 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001688}
1689
Ted Kremenek826a3452010-07-16 02:11:22 +00001690SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001691 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001692}
1693
Ted Kremenek826a3452010-07-16 02:11:22 +00001694void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1695 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00001696 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
1697 getLocationOfByte(startSpecifier),
1698 /*IsStringLocation*/true,
1699 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00001700}
1701
Ted Kremenekefaff192010-02-27 01:41:03 +00001702void
Ted Kremenek826a3452010-07-16 02:11:22 +00001703CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1704 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00001705 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
1706 << (unsigned) p,
1707 getLocationOfByte(startPos), /*IsStringLocation*/true,
1708 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001709}
1710
Ted Kremenek826a3452010-07-16 02:11:22 +00001711void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001712 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00001713 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
1714 getLocationOfByte(startPos),
1715 /*IsStringLocation*/true,
1716 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001717}
1718
Ted Kremenek826a3452010-07-16 02:11:22 +00001719void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001720 if (!IsObjCLiteral) {
1721 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00001722 EmitFormatDiagnostic(
1723 S.PDiag(diag::warn_printf_format_string_contains_null_char),
1724 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
1725 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00001726 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001727}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001728
Ted Kremenek826a3452010-07-16 02:11:22 +00001729const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1730 return TheCall->getArg(FirstDataArg + i);
1731}
1732
1733void CheckFormatHandler::DoneProcessing() {
1734 // Does the number of data arguments exceed the number of
1735 // format conversions in the format string?
1736 if (!HasVAListArg) {
1737 // Find any arguments that weren't covered.
1738 CoveredArgs.flip();
1739 signed notCoveredArg = CoveredArgs.find_first();
1740 if (notCoveredArg >= 0) {
1741 assert((unsigned)notCoveredArg < NumDataArgs);
Richard Trieu55733de2011-10-28 00:41:25 +00001742 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
1743 getDataArg((unsigned) notCoveredArg)->getLocStart(),
1744 /*IsStringLocation*/false, getFormatStringRange());
Ted Kremenek826a3452010-07-16 02:11:22 +00001745 }
1746 }
1747}
1748
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001749bool
1750CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1751 SourceLocation Loc,
1752 const char *startSpec,
1753 unsigned specifierLen,
1754 const char *csStart,
1755 unsigned csLen) {
1756
1757 bool keepGoing = true;
1758 if (argIndex < NumDataArgs) {
1759 // Consider the argument coverered, even though the specifier doesn't
1760 // make sense.
1761 CoveredArgs.set(argIndex);
1762 }
1763 else {
1764 // If argIndex exceeds the number of data arguments we
1765 // don't issue a warning because that is just a cascade of warnings (and
1766 // they may have intended '%%' anyway). We don't want to continue processing
1767 // the format string after this point, however, as we will like just get
1768 // gibberish when trying to match arguments.
1769 keepGoing = false;
1770 }
1771
Richard Trieu55733de2011-10-28 00:41:25 +00001772 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
1773 << StringRef(csStart, csLen),
1774 Loc, /*IsStringLocation*/true,
1775 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001776
1777 return keepGoing;
1778}
1779
Richard Trieu55733de2011-10-28 00:41:25 +00001780void
1781CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
1782 const char *startSpec,
1783 unsigned specifierLen) {
1784 EmitFormatDiagnostic(
1785 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
1786 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
1787}
1788
Ted Kremenek666a1972010-07-26 19:45:42 +00001789bool
1790CheckFormatHandler::CheckNumArgs(
1791 const analyze_format_string::FormatSpecifier &FS,
1792 const analyze_format_string::ConversionSpecifier &CS,
1793 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1794
1795 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00001796 PartialDiagnostic PDiag = FS.usesPositionalArg()
1797 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
1798 << (argIndex+1) << NumDataArgs)
1799 : S.PDiag(diag::warn_printf_insufficient_data_args);
1800 EmitFormatDiagnostic(
1801 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
1802 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00001803 return false;
1804 }
1805 return true;
1806}
1807
Richard Trieu55733de2011-10-28 00:41:25 +00001808template<typename Range>
1809void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
1810 SourceLocation Loc,
1811 bool IsStringLocation,
1812 Range StringRange,
1813 FixItHint FixIt) {
1814 EmitFormatDiagnostic(S, inFunctionCall, TheCall->getArg(FormatIdx), PDiag,
1815 Loc, IsStringLocation, StringRange, FixIt);
1816}
1817
1818/// \brief If the format string is not within the funcion call, emit a note
1819/// so that the function call and string are in diagnostic messages.
1820///
1821/// \param inFunctionCall if true, the format string is within the function
1822/// call and only one diagnostic message will be produced. Otherwise, an
1823/// extra note will be emitted pointing to location of the format string.
1824///
1825/// \param ArgumentExpr the expression that is passed as the format string
1826/// argument in the function call. Used for getting locations when two
1827/// diagnostics are emitted.
1828///
1829/// \param PDiag the callee should already have provided any strings for the
1830/// diagnostic message. This function only adds locations and fixits
1831/// to diagnostics.
1832///
1833/// \param Loc primary location for diagnostic. If two diagnostics are
1834/// required, one will be at Loc and a new SourceLocation will be created for
1835/// the other one.
1836///
1837/// \param IsStringLocation if true, Loc points to the format string should be
1838/// used for the note. Otherwise, Loc points to the argument list and will
1839/// be used with PDiag.
1840///
1841/// \param StringRange some or all of the string to highlight. This is
1842/// templated so it can accept either a CharSourceRange or a SourceRange.
1843///
1844/// \param Fixit optional fix it hint for the format string.
1845template<typename Range>
1846void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
1847 const Expr *ArgumentExpr,
1848 PartialDiagnostic PDiag,
1849 SourceLocation Loc,
1850 bool IsStringLocation,
1851 Range StringRange,
1852 FixItHint FixIt) {
1853 if (InFunctionCall)
1854 S.Diag(Loc, PDiag) << StringRange << FixIt;
1855 else {
1856 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
1857 << ArgumentExpr->getSourceRange();
1858 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
1859 diag::note_format_string_defined)
1860 << StringRange << FixIt;
1861 }
1862}
1863
Ted Kremenek826a3452010-07-16 02:11:22 +00001864//===--- CHECK: Printf format string checking ------------------------------===//
1865
1866namespace {
1867class CheckPrintfHandler : public CheckFormatHandler {
1868public:
1869 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1870 const Expr *origFormatExpr, unsigned firstDataArg,
1871 unsigned numDataArgs, bool isObjCLiteral,
1872 const char *beg, bool hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001873 const CallExpr *theCall, unsigned formatIdx,
1874 bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00001875 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1876 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001877 theCall, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00001878
1879
1880 bool HandleInvalidPrintfConversionSpecifier(
1881 const analyze_printf::PrintfSpecifier &FS,
1882 const char *startSpecifier,
1883 unsigned specifierLen);
1884
1885 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1886 const char *startSpecifier,
1887 unsigned specifierLen);
1888
1889 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1890 const char *startSpecifier, unsigned specifierLen);
1891 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1892 const analyze_printf::OptionalAmount &Amt,
1893 unsigned type,
1894 const char *startSpecifier, unsigned specifierLen);
1895 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1896 const analyze_printf::OptionalFlag &flag,
1897 const char *startSpecifier, unsigned specifierLen);
1898 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1899 const analyze_printf::OptionalFlag &ignoredFlag,
1900 const analyze_printf::OptionalFlag &flag,
1901 const char *startSpecifier, unsigned specifierLen);
1902};
1903}
1904
1905bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1906 const analyze_printf::PrintfSpecifier &FS,
1907 const char *startSpecifier,
1908 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001909 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001910 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001911
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001912 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1913 getLocationOfByte(CS.getStart()),
1914 startSpecifier, specifierLen,
1915 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001916}
1917
Ted Kremenek826a3452010-07-16 02:11:22 +00001918bool CheckPrintfHandler::HandleAmount(
1919 const analyze_format_string::OptionalAmount &Amt,
1920 unsigned k, const char *startSpecifier,
1921 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001922
1923 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001924 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001925 unsigned argIndex = Amt.getArgIndex();
1926 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00001927 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
1928 << k,
1929 getLocationOfByte(Amt.getStart()),
1930 /*IsStringLocation*/true,
1931 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00001932 // Don't do any more checking. We will just emit
1933 // spurious errors.
1934 return false;
1935 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001936
Ted Kremenek0d277352010-01-29 01:06:55 +00001937 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001938 // Although not in conformance with C99, we also allow the argument to be
1939 // an 'unsigned int' as that is a reasonably safe case. GCC also
1940 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001941 CoveredArgs.set(argIndex);
1942 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001943 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001944
1945 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1946 assert(ATR.isValid());
1947
1948 if (!ATR.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00001949 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborga792aff2011-12-07 10:33:11 +00001950 << k << ATR.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00001951 << T << Arg->getSourceRange(),
1952 getLocationOfByte(Amt.getStart()),
1953 /*IsStringLocation*/true,
1954 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00001955 // Don't do any more checking. We will just emit
1956 // spurious errors.
1957 return false;
1958 }
1959 }
1960 }
1961 return true;
1962}
Ted Kremenek0d277352010-01-29 01:06:55 +00001963
Tom Caree4ee9662010-06-17 19:00:27 +00001964void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001965 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001966 const analyze_printf::OptionalAmount &Amt,
1967 unsigned type,
1968 const char *startSpecifier,
1969 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001970 const analyze_printf::PrintfConversionSpecifier &CS =
1971 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001972
Richard Trieu55733de2011-10-28 00:41:25 +00001973 FixItHint fixit =
1974 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
1975 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
1976 Amt.getConstantLength()))
1977 : FixItHint();
1978
1979 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
1980 << type << CS.toString(),
1981 getLocationOfByte(Amt.getStart()),
1982 /*IsStringLocation*/true,
1983 getSpecifierRange(startSpecifier, specifierLen),
1984 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00001985}
1986
Ted Kremenek826a3452010-07-16 02:11:22 +00001987void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001988 const analyze_printf::OptionalFlag &flag,
1989 const char *startSpecifier,
1990 unsigned specifierLen) {
1991 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001992 const analyze_printf::PrintfConversionSpecifier &CS =
1993 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00001994 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
1995 << flag.toString() << CS.toString(),
1996 getLocationOfByte(flag.getPosition()),
1997 /*IsStringLocation*/true,
1998 getSpecifierRange(startSpecifier, specifierLen),
1999 FixItHint::CreateRemoval(
2000 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002001}
2002
2003void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002004 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002005 const analyze_printf::OptionalFlag &ignoredFlag,
2006 const analyze_printf::OptionalFlag &flag,
2007 const char *startSpecifier,
2008 unsigned specifierLen) {
2009 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002010 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2011 << ignoredFlag.toString() << flag.toString(),
2012 getLocationOfByte(ignoredFlag.getPosition()),
2013 /*IsStringLocation*/true,
2014 getSpecifierRange(startSpecifier, specifierLen),
2015 FixItHint::CreateRemoval(
2016 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002017}
2018
Ted Kremeneke0e53132010-01-28 23:39:18 +00002019bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002020CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002021 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002022 const char *startSpecifier,
2023 unsigned specifierLen) {
2024
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002025 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002026 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002027 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002028
Ted Kremenekbaa40062010-07-19 22:01:06 +00002029 if (FS.consumesDataArgument()) {
2030 if (atFirstArg) {
2031 atFirstArg = false;
2032 usesPositionalArgs = FS.usesPositionalArg();
2033 }
2034 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002035 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2036 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002037 return false;
2038 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002039 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002040
Ted Kremenekefaff192010-02-27 01:41:03 +00002041 // First check if the field width, precision, and conversion specifier
2042 // have matching data arguments.
2043 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2044 startSpecifier, specifierLen)) {
2045 return false;
2046 }
2047
2048 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2049 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002050 return false;
2051 }
2052
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002053 if (!CS.consumesDataArgument()) {
2054 // FIXME: Technically specifying a precision or field width here
2055 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002056 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002057 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002058
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002059 // Consume the argument.
2060 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002061 if (argIndex < NumDataArgs) {
2062 // The check to see if the argIndex is valid will come later.
2063 // We set the bit here because we may exit early from this
2064 // function if we encounter some other error.
2065 CoveredArgs.set(argIndex);
2066 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002067
2068 // Check for using an Objective-C specific conversion specifier
2069 // in a non-ObjC literal.
2070 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002071 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2072 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002073 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002074
Tom Caree4ee9662010-06-17 19:00:27 +00002075 // Check for invalid use of field width
2076 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002077 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002078 startSpecifier, specifierLen);
2079 }
2080
2081 // Check for invalid use of precision
2082 if (!FS.hasValidPrecision()) {
2083 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2084 startSpecifier, specifierLen);
2085 }
2086
2087 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002088 if (!FS.hasValidThousandsGroupingPrefix())
2089 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002090 if (!FS.hasValidLeadingZeros())
2091 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2092 if (!FS.hasValidPlusPrefix())
2093 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002094 if (!FS.hasValidSpacePrefix())
2095 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002096 if (!FS.hasValidAlternativeForm())
2097 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2098 if (!FS.hasValidLeftJustified())
2099 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2100
2101 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002102 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2103 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2104 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002105 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2106 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2107 startSpecifier, specifierLen);
2108
2109 // Check the length modifier is valid with the given conversion specifier.
2110 const LengthModifier &LM = FS.getLengthModifier();
2111 if (!FS.hasValidLengthModifier())
Richard Trieu55733de2011-10-28 00:41:25 +00002112 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2113 << LM.toString() << CS.toString(),
2114 getLocationOfByte(LM.getStart()),
2115 /*IsStringLocation*/true,
2116 getSpecifierRange(startSpecifier, specifierLen),
2117 FixItHint::CreateRemoval(
2118 getSpecifierRange(LM.getStart(),
2119 LM.getLength())));
Tom Caree4ee9662010-06-17 19:00:27 +00002120
2121 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00002122 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00002123 // Issue a warning about this being a possible security issue.
Richard Trieu55733de2011-10-28 00:41:25 +00002124 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
2125 getLocationOfByte(CS.getStart()),
2126 /*IsStringLocation*/true,
2127 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremeneke82d8042010-01-29 01:35:25 +00002128 // Continue checking the other format specifiers.
2129 return true;
2130 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002131
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002132 // The remaining checks depend on the data arguments.
2133 if (HasVAListArg)
2134 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002135
Ted Kremenek666a1972010-07-26 19:45:42 +00002136 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002137 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002138
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002139 // Now type check the data expression that matches the
2140 // format specifier.
2141 const Expr *Ex = getDataArg(argIndex);
Nick Lewycky687b5df2011-12-02 23:21:43 +00002142 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002143 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2144 // Check if we didn't match because of an implicit cast from a 'char'
2145 // or 'short' to an 'int'. This is done because printf is a varargs
2146 // function.
2147 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002148 if (ICE->getType() == S.Context.IntTy) {
2149 // All further checking is done on the subexpression.
2150 Ex = ICE->getSubExpr();
2151 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002152 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002153 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002154
2155 // We may be able to offer a FixItHint if it is a supported type.
2156 PrintfSpecifier fixedFS = FS;
Hans Wennborga7da2152011-10-18 08:10:06 +00002157 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions());
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002158
2159 if (success) {
2160 // Get the fix string from the fixed format specifier
2161 llvm::SmallString<128> buf;
2162 llvm::raw_svector_ostream os(buf);
2163 fixedFS.toString(os);
2164
Richard Trieu55733de2011-10-28 00:41:25 +00002165 EmitFormatDiagnostic(
2166 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborga792aff2011-12-07 10:33:11 +00002167 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Richard Trieu55733de2011-10-28 00:41:25 +00002168 << Ex->getSourceRange(),
2169 getLocationOfByte(CS.getStart()),
2170 /*IsStringLocation*/true,
2171 getSpecifierRange(startSpecifier, specifierLen),
2172 FixItHint::CreateReplacement(
2173 getSpecifierRange(startSpecifier, specifierLen),
2174 os.str()));
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002175 }
2176 else {
2177 S.Diag(getLocationOfByte(CS.getStart()),
2178 diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborga792aff2011-12-07 10:33:11 +00002179 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002180 << getSpecifierRange(startSpecifier, specifierLen)
2181 << Ex->getSourceRange();
2182 }
2183 }
2184
Ted Kremeneke0e53132010-01-28 23:39:18 +00002185 return true;
2186}
2187
Ted Kremenek826a3452010-07-16 02:11:22 +00002188//===--- CHECK: Scanf format string checking ------------------------------===//
2189
2190namespace {
2191class CheckScanfHandler : public CheckFormatHandler {
2192public:
2193 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2194 const Expr *origFormatExpr, unsigned firstDataArg,
2195 unsigned numDataArgs, bool isObjCLiteral,
2196 const char *beg, bool hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00002197 const CallExpr *theCall, unsigned formatIdx,
2198 bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00002199 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2200 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00002201 theCall, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002202
2203 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2204 const char *startSpecifier,
2205 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002206
2207 bool HandleInvalidScanfConversionSpecifier(
2208 const analyze_scanf::ScanfSpecifier &FS,
2209 const char *startSpecifier,
2210 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002211
2212 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002213};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002214}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002215
Ted Kremenekb7c21012010-07-16 18:28:03 +00002216void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2217 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002218 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2219 getLocationOfByte(end), /*IsStringLocation*/true,
2220 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002221}
2222
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002223bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2224 const analyze_scanf::ScanfSpecifier &FS,
2225 const char *startSpecifier,
2226 unsigned specifierLen) {
2227
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002228 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002229 FS.getConversionSpecifier();
2230
2231 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2232 getLocationOfByte(CS.getStart()),
2233 startSpecifier, specifierLen,
2234 CS.getStart(), CS.getLength());
2235}
2236
Ted Kremenek826a3452010-07-16 02:11:22 +00002237bool CheckScanfHandler::HandleScanfSpecifier(
2238 const analyze_scanf::ScanfSpecifier &FS,
2239 const char *startSpecifier,
2240 unsigned specifierLen) {
2241
2242 using namespace analyze_scanf;
2243 using namespace analyze_format_string;
2244
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002245 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002246
Ted Kremenekbaa40062010-07-19 22:01:06 +00002247 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2248 // be used to decide if we are using positional arguments consistently.
2249 if (FS.consumesDataArgument()) {
2250 if (atFirstArg) {
2251 atFirstArg = false;
2252 usesPositionalArgs = FS.usesPositionalArg();
2253 }
2254 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002255 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2256 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002257 return false;
2258 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002259 }
2260
2261 // Check if the field with is non-zero.
2262 const OptionalAmount &Amt = FS.getFieldWidth();
2263 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2264 if (Amt.getConstantAmount() == 0) {
2265 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2266 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00002267 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2268 getLocationOfByte(Amt.getStart()),
2269 /*IsStringLocation*/true, R,
2270 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00002271 }
2272 }
2273
2274 if (!FS.consumesDataArgument()) {
2275 // FIXME: Technically specifying a precision or field width here
2276 // makes no sense. Worth issuing a warning at some point.
2277 return true;
2278 }
2279
2280 // Consume the argument.
2281 unsigned argIndex = FS.getArgIndex();
2282 if (argIndex < NumDataArgs) {
2283 // The check to see if the argIndex is valid will come later.
2284 // We set the bit here because we may exit early from this
2285 // function if we encounter some other error.
2286 CoveredArgs.set(argIndex);
2287 }
2288
Ted Kremenek1e51c202010-07-20 20:04:47 +00002289 // Check the length modifier is valid with the given conversion specifier.
2290 const LengthModifier &LM = FS.getLengthModifier();
2291 if (!FS.hasValidLengthModifier()) {
2292 S.Diag(getLocationOfByte(LM.getStart()),
2293 diag::warn_format_nonsensical_length)
2294 << LM.toString() << CS.toString()
2295 << getSpecifierRange(startSpecifier, specifierLen)
2296 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
2297 LM.getLength()));
2298 }
2299
Ted Kremenek826a3452010-07-16 02:11:22 +00002300 // The remaining checks depend on the data arguments.
2301 if (HasVAListArg)
2302 return true;
2303
Ted Kremenek666a1972010-07-26 19:45:42 +00002304 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002305 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002306
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002307 // Check that the argument type matches the format specifier.
2308 const Expr *Ex = getDataArg(argIndex);
2309 const analyze_scanf::ScanfArgTypeResult &ATR = FS.getArgType(S.Context);
2310 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2311 ScanfSpecifier fixedFS = FS;
2312 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions());
2313
2314 if (success) {
2315 // Get the fix string from the fixed format specifier.
2316 llvm::SmallString<128> buf;
2317 llvm::raw_svector_ostream os(buf);
2318 fixedFS.toString(os);
2319
2320 EmitFormatDiagnostic(
2321 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2322 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2323 << Ex->getSourceRange(),
2324 getLocationOfByte(CS.getStart()),
2325 /*IsStringLocation*/true,
2326 getSpecifierRange(startSpecifier, specifierLen),
2327 FixItHint::CreateReplacement(
2328 getSpecifierRange(startSpecifier, specifierLen),
2329 os.str()));
2330 } else {
2331 S.Diag(getLocationOfByte(CS.getStart()),
2332 diag::warn_printf_conversion_argument_type_mismatch)
2333 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2334 << getSpecifierRange(startSpecifier, specifierLen)
2335 << Ex->getSourceRange();
2336 }
2337 }
2338
Ted Kremenek826a3452010-07-16 02:11:22 +00002339 return true;
2340}
2341
2342void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002343 const Expr *OrigFormatExpr,
2344 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00002345 unsigned format_idx, unsigned firstDataArg,
Richard Trieu55733de2011-10-28 00:41:25 +00002346 bool isPrintf, bool inFunctionCall) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002347
Ted Kremeneke0e53132010-01-28 23:39:18 +00002348 // CHECK: is the format string a wide literal?
Douglas Gregor5cee1192011-07-27 05:40:30 +00002349 if (!FExpr->isAscii()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002350 CheckFormatHandler::EmitFormatDiagnostic(
2351 *this, inFunctionCall, TheCall->getArg(format_idx),
2352 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2353 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002354 return;
2355 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002356
Ted Kremeneke0e53132010-01-28 23:39:18 +00002357 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00002358 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002359 const char *Str = StrRef.data();
2360 unsigned StrLen = StrRef.size();
Ted Kremenek4cd57912011-09-29 05:52:16 +00002361 const unsigned numDataArgs = TheCall->getNumArgs() - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00002362
Ted Kremeneke0e53132010-01-28 23:39:18 +00002363 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00002364 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00002365 CheckFormatHandler::EmitFormatDiagnostic(
2366 *this, inFunctionCall, TheCall->getArg(format_idx),
2367 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2368 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002369 return;
2370 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002371
2372 if (isPrintf) {
2373 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002374 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Richard Trieu55733de2011-10-28 00:41:25 +00002375 Str, HasVAListArg, TheCall, format_idx,
2376 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002377
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002378 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
2379 getLangOptions()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002380 H.DoneProcessing();
2381 }
2382 else {
2383 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002384 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Richard Trieu55733de2011-10-28 00:41:25 +00002385 Str, HasVAListArg, TheCall, format_idx,
2386 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002387
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002388 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
2389 getLangOptions()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002390 H.DoneProcessing();
2391 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00002392}
2393
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002394//===--- CHECK: Standard memory functions ---------------------------------===//
2395
Douglas Gregor2a053a32011-05-03 20:05:22 +00002396/// \brief Determine whether the given type is a dynamic class type (e.g.,
2397/// whether it has a vtable).
2398static bool isDynamicClassType(QualType T) {
2399 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2400 if (CXXRecordDecl *Definition = Record->getDefinition())
2401 if (Definition->isDynamicClass())
2402 return true;
2403
2404 return false;
2405}
2406
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002407/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00002408/// otherwise returns NULL.
2409static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00002410 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00002411 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2412 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2413 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002414
Chandler Carruth000d4282011-06-16 09:09:40 +00002415 return 0;
2416}
2417
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002418/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00002419static QualType getSizeOfArgType(const Expr* E) {
2420 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2421 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2422 if (SizeOf->getKind() == clang::UETT_SizeOf)
2423 return SizeOf->getTypeOfArgument();
2424
2425 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00002426}
2427
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002428/// \brief Check for dangerous or invalid arguments to memset().
2429///
Chandler Carruth929f0132011-06-03 06:23:57 +00002430/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002431/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2432/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002433///
2434/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002435void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaksd9b859a2012-01-13 21:52:01 +00002436 FunctionDecl::MemoryFunctionKind CMF,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002437 IdentifierInfo *FnName) {
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002438 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00002439 // we have enough arguments, and if not, abort further checking.
Anna Zaksd9b859a2012-01-13 21:52:01 +00002440 unsigned ExpectedNumArgs = (CMF == FunctionDecl::MFK_Strndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00002441 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002442 return;
2443
Anna Zaksd9b859a2012-01-13 21:52:01 +00002444 unsigned LastArg = (CMF == FunctionDecl::MFK_Memset ||
2445 CMF == FunctionDecl::MFK_Strndup ? 1 : 2);
2446 unsigned LenArg = (CMF == FunctionDecl::MFK_Strndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00002447 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00002448
2449 // We have special checking when the length is a sizeof expression.
2450 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2451 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2452 llvm::FoldingSetNodeID SizeOfArgID;
2453
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002454 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2455 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002456 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002457
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002458 QualType DestTy = Dest->getType();
2459 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2460 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002461
Chandler Carruth000d4282011-06-16 09:09:40 +00002462 // Never warn about void type pointers. This can be used to suppress
2463 // false positives.
2464 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002465 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002466
Chandler Carruth000d4282011-06-16 09:09:40 +00002467 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2468 // actually comparing the expressions for equality. Because computing the
2469 // expression IDs can be expensive, we only do this if the diagnostic is
2470 // enabled.
2471 if (SizeOfArg &&
2472 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2473 SizeOfArg->getExprLoc())) {
2474 // We only compute IDs for expressions if the warning is enabled, and
2475 // cache the sizeof arg's ID.
2476 if (SizeOfArgID == llvm::FoldingSetNodeID())
2477 SizeOfArg->Profile(SizeOfArgID, Context, true);
2478 llvm::FoldingSetNodeID DestID;
2479 Dest->Profile(DestID, Context, true);
2480 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00002481 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2482 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00002483 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2484 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2485 if (UnaryOp->getOpcode() == UO_AddrOf)
2486 ActionIdx = 1; // If its an address-of operator, just remove it.
2487 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2488 ActionIdx = 2; // If the pointee's size is sizeof(char),
2489 // suggest an explicit length.
Anna Zaksd9b859a2012-01-13 21:52:01 +00002490 unsigned DestSrcSelect =
2491 (CMF == FunctionDecl::MFK_Strndup ? 1 : ArgIdx);
Chandler Carruth000d4282011-06-16 09:09:40 +00002492 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2493 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Nico Webercda57822011-10-13 22:30:23 +00002494 << FnName << DestSrcSelect << ActionIdx
Chandler Carruth000d4282011-06-16 09:09:40 +00002495 << Dest->getSourceRange()
2496 << SizeOfArg->getSourceRange());
2497 break;
2498 }
2499 }
2500
2501 // Also check for cases where the sizeof argument is the exact same
2502 // type as the memory argument, and where it points to a user-defined
2503 // record type.
2504 if (SizeOfArgTy != QualType()) {
2505 if (PointeeTy->isRecordType() &&
2506 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2507 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2508 PDiag(diag::warn_sizeof_pointer_type_memaccess)
2509 << FnName << SizeOfArgTy << ArgIdx
2510 << PointeeTy << Dest->getSourceRange()
2511 << LenExpr->getSourceRange());
2512 break;
2513 }
Nico Webere4a1c642011-06-14 16:14:58 +00002514 }
2515
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002516 // Always complain about dynamic classes.
John McCallf85e1932011-06-15 23:02:42 +00002517 if (isDynamicClassType(PointeeTy))
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002518 DiagRuntimeBehavior(
2519 Dest->getExprLoc(), Dest,
2520 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaksd9b859a2012-01-13 21:52:01 +00002521 << (CMF == FunctionDecl::MFK_Memcmp ? ArgIdx + 2 : ArgIdx)
2522 << FnName << PointeeTy
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002523 // "overwritten" if we're warning about the destination for any call
2524 // but memcmp; otherwise a verb appropriate to the call.
Anna Zaksd9b859a2012-01-13 21:52:01 +00002525 << (ArgIdx == 0 &&
2526 CMF != FunctionDecl::MFK_Memcmp ? 0 : (unsigned)CMF)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002527 << Call->getCallee()->getSourceRange());
Anna Zaksd9b859a2012-01-13 21:52:01 +00002528 else if (PointeeTy.hasNonTrivialObjCLifetime() &&
2529 CMF != FunctionDecl::MFK_Memset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002530 DiagRuntimeBehavior(
2531 Dest->getExprLoc(), Dest,
2532 PDiag(diag::warn_arc_object_memaccess)
2533 << ArgIdx << FnName << PointeeTy
2534 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00002535 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002536 continue;
John McCallf85e1932011-06-15 23:02:42 +00002537
2538 DiagRuntimeBehavior(
2539 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00002540 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002541 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2542 break;
2543 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002544 }
2545}
2546
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002547// A little helper routine: ignore addition and subtraction of integer literals.
2548// This intentionally does not ignore all integer constant expressions because
2549// we don't want to remove sizeof().
2550static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2551 Ex = Ex->IgnoreParenCasts();
2552
2553 for (;;) {
2554 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2555 if (!BO || !BO->isAdditiveOp())
2556 break;
2557
2558 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2559 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2560
2561 if (isa<IntegerLiteral>(RHS))
2562 Ex = LHS;
2563 else if (isa<IntegerLiteral>(LHS))
2564 Ex = RHS;
2565 else
2566 break;
2567 }
2568
2569 return Ex;
2570}
2571
2572// Warn if the user has made the 'size' argument to strlcpy or strlcat
2573// be the size of the source, instead of the destination.
2574void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2575 IdentifierInfo *FnName) {
2576
2577 // Don't crash if the user has the wrong number of arguments
2578 if (Call->getNumArgs() != 3)
2579 return;
2580
2581 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2582 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2583 const Expr *CompareWithSrc = NULL;
2584
2585 // Look for 'strlcpy(dst, x, sizeof(x))'
2586 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2587 CompareWithSrc = Ex;
2588 else {
2589 // Look for 'strlcpy(dst, x, strlen(x))'
2590 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00002591 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002592 && SizeCall->getNumArgs() == 1)
2593 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2594 }
2595 }
2596
2597 if (!CompareWithSrc)
2598 return;
2599
2600 // Determine if the argument to sizeof/strlen is equal to the source
2601 // argument. In principle there's all kinds of things you could do
2602 // here, for instance creating an == expression and evaluating it with
2603 // EvaluateAsBooleanCondition, but this uses a more direct technique:
2604 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2605 if (!SrcArgDRE)
2606 return;
2607
2608 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2609 if (!CompareWithSrcDRE ||
2610 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2611 return;
2612
2613 const Expr *OriginalSizeArg = Call->getArg(2);
2614 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2615 << OriginalSizeArg->getSourceRange() << FnName;
2616
2617 // Output a FIXIT hint if the destination is an array (rather than a
2618 // pointer to an array). This could be enhanced to handle some
2619 // pointers if we know the actual size, like if DstArg is 'array+2'
2620 // we could say 'sizeof(array)-2'.
2621 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek8f746222011-08-18 22:48:41 +00002622 QualType DstArgTy = DstArg->getType();
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002623
Ted Kremenek8f746222011-08-18 22:48:41 +00002624 // Only handle constant-sized or VLAs, but not flexible members.
2625 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2626 // Only issue the FIXIT for arrays of size > 1.
2627 if (CAT->getSize().getSExtValue() <= 1)
2628 return;
2629 } else if (!DstArgTy->isVariableArrayType()) {
2630 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002631 }
Ted Kremenek8f746222011-08-18 22:48:41 +00002632
2633 llvm::SmallString<128> sizeString;
2634 llvm::raw_svector_ostream OS(sizeString);
2635 OS << "sizeof(";
Douglas Gregor8987b232011-09-27 23:30:47 +00002636 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00002637 OS << ")";
2638
2639 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2640 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2641 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002642}
2643
Ted Kremenek06de2762007-08-17 16:46:58 +00002644//===--- CHECK: Return Address of Stack Variable --------------------------===//
2645
Chris Lattner5f9e2722011-07-23 10:55:15 +00002646static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2647static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002648
2649/// CheckReturnStackAddr - Check if a return statement returns the address
2650/// of a stack variable.
2651void
2652Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2653 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00002654
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002655 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002656 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002657
2658 // Perform checking for returned stack addresses, local blocks,
2659 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00002660 if (lhsType->isPointerType() ||
2661 (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002662 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002663 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002664 stackE = EvalVal(RetValExp, refVars);
2665 }
2666
2667 if (stackE == 0)
2668 return; // Nothing suspicious was found.
2669
2670 SourceLocation diagLoc;
2671 SourceRange diagRange;
2672 if (refVars.empty()) {
2673 diagLoc = stackE->getLocStart();
2674 diagRange = stackE->getSourceRange();
2675 } else {
2676 // We followed through a reference variable. 'stackE' contains the
2677 // problematic expression but we will warn at the return statement pointing
2678 // at the reference variable. We will later display the "trail" of
2679 // reference variables using notes.
2680 diagLoc = refVars[0]->getLocStart();
2681 diagRange = refVars[0]->getSourceRange();
2682 }
2683
2684 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2685 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2686 : diag::warn_ret_stack_addr)
2687 << DR->getDecl()->getDeclName() << diagRange;
2688 } else if (isa<BlockExpr>(stackE)) { // local block.
2689 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2690 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2691 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2692 } else { // local temporary.
2693 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2694 : diag::warn_ret_local_temp_addr)
2695 << diagRange;
2696 }
2697
2698 // Display the "trail" of reference variables that we followed until we
2699 // found the problematic expression using notes.
2700 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2701 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2702 // If this var binds to another reference var, show the range of the next
2703 // var, otherwise the var binds to the problematic expression, in which case
2704 // show the range of the expression.
2705 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2706 : stackE->getSourceRange();
2707 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2708 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00002709 }
2710}
2711
2712/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2713/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002714/// to a location on the stack, a local block, an address of a label, or a
2715/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00002716/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002717/// encounter a subexpression that (1) clearly does not lead to one of the
2718/// above problematic expressions (2) is something we cannot determine leads to
2719/// a problematic expression based on such local checking.
2720///
2721/// Both EvalAddr and EvalVal follow through reference variables to evaluate
2722/// the expression that they point to. Such variables are added to the
2723/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00002724///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002725/// EvalAddr processes expressions that are pointers that are used as
2726/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002727/// At the base case of the recursion is a check for the above problematic
2728/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00002729///
2730/// This implementation handles:
2731///
2732/// * pointer-to-pointer casts
2733/// * implicit conversions from array references to pointers
2734/// * taking the address of fields
2735/// * arbitrary interplay between "&" and "*" operators
2736/// * pointer arithmetic from an address of a stack variable
2737/// * taking the address of an array element where the array is on the stack
Chris Lattner5f9e2722011-07-23 10:55:15 +00002738static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002739 if (E->isTypeDependent())
2740 return NULL;
2741
Ted Kremenek06de2762007-08-17 16:46:58 +00002742 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00002743 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00002744 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002745 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002746 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00002747
Peter Collingbournef111d932011-04-15 00:35:48 +00002748 E = E->IgnoreParens();
2749
Ted Kremenek06de2762007-08-17 16:46:58 +00002750 // Our "symbolic interpreter" is just a dispatch off the currently
2751 // viewed AST node. We then recursively traverse the AST by calling
2752 // EvalAddr and EvalVal appropriately.
2753 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002754 case Stmt::DeclRefExprClass: {
2755 DeclRefExpr *DR = cast<DeclRefExpr>(E);
2756
2757 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2758 // If this is a reference variable, follow through to the expression that
2759 // it points to.
2760 if (V->hasLocalStorage() &&
2761 V->getType()->isReferenceType() && V->hasInit()) {
2762 // Add the reference variable to the "trail".
2763 refVars.push_back(DR);
2764 return EvalAddr(V->getInit(), refVars);
2765 }
2766
2767 return NULL;
2768 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002769
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002770 case Stmt::UnaryOperatorClass: {
2771 // The only unary operator that make sense to handle here
2772 // is AddrOf. All others don't make sense as pointers.
2773 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002774
John McCall2de56d12010-08-25 11:45:40 +00002775 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002776 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002777 else
Ted Kremenek06de2762007-08-17 16:46:58 +00002778 return NULL;
2779 }
Mike Stump1eb44332009-09-09 15:08:12 +00002780
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002781 case Stmt::BinaryOperatorClass: {
2782 // Handle pointer arithmetic. All other binary operators are not valid
2783 // in this context.
2784 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00002785 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00002786
John McCall2de56d12010-08-25 11:45:40 +00002787 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002788 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002789
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002790 Expr *Base = B->getLHS();
2791
2792 // Determine which argument is the real pointer base. It could be
2793 // the RHS argument instead of the LHS.
2794 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00002795
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002796 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002797 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002798 }
Steve Naroff61f40a22008-09-10 19:17:48 +00002799
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002800 // For conditional operators we need to see if either the LHS or RHS are
2801 // valid DeclRefExpr*s. If one of them is valid, we return it.
2802 case Stmt::ConditionalOperatorClass: {
2803 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002804
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002805 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002806 if (Expr *lhsExpr = C->getLHS()) {
2807 // In C++, we can have a throw-expression, which has 'void' type.
2808 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002809 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002810 return LHS;
2811 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002812
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002813 // In C++, we can have a throw-expression, which has 'void' type.
2814 if (C->getRHS()->getType()->isVoidType())
2815 return NULL;
2816
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002817 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002818 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002819
2820 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00002821 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002822 return E; // local block.
2823 return NULL;
2824
2825 case Stmt::AddrLabelExprClass:
2826 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00002827
John McCall80ee6e82011-11-10 05:35:25 +00002828 case Stmt::ExprWithCleanupsClass:
2829 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
2830
Ted Kremenek54b52742008-08-07 00:49:01 +00002831 // For casts, we need to handle conversions from arrays to
2832 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00002833 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002834 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002835 case Stmt::CXXFunctionalCastExprClass:
2836 case Stmt::ObjCBridgedCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002837 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00002838 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002839
Steve Naroffdd972f22008-09-05 22:11:13 +00002840 if (SubExpr->getType()->isPointerType() ||
2841 SubExpr->getType()->isBlockPointerType() ||
2842 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002843 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00002844 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002845 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002846 else
Ted Kremenek54b52742008-08-07 00:49:01 +00002847 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002848 }
Mike Stump1eb44332009-09-09 15:08:12 +00002849
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002850 // C++ casts. For dynamic casts, static casts, and const casts, we
2851 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00002852 // through the cast. In the case the dynamic cast doesn't fail (and
2853 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002854 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00002855 // FIXME: The comment about is wrong; we're not always converting
2856 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00002857 // handle references to objects.
2858 case Stmt::CXXStaticCastExprClass:
2859 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002860 case Stmt::CXXConstCastExprClass:
2861 case Stmt::CXXReinterpretCastExprClass: {
2862 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00002863 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002864 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002865 else
2866 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002867 }
Mike Stump1eb44332009-09-09 15:08:12 +00002868
Douglas Gregor03e80032011-06-21 17:03:29 +00002869 case Stmt::MaterializeTemporaryExprClass:
2870 if (Expr *Result = EvalAddr(
2871 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2872 refVars))
2873 return Result;
2874
2875 return E;
2876
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002877 // Everything else: we simply don't reason about them.
2878 default:
2879 return NULL;
2880 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002881}
Mike Stump1eb44332009-09-09 15:08:12 +00002882
Ted Kremenek06de2762007-08-17 16:46:58 +00002883
2884/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2885/// See the comments for EvalAddr for more details.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002886static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002887do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002888 // We should only be called for evaluating non-pointer expressions, or
2889 // expressions with a pointer type that are not used as references but instead
2890 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002891
Ted Kremenek06de2762007-08-17 16:46:58 +00002892 // Our "symbolic interpreter" is just a dispatch off the currently
2893 // viewed AST node. We then recursively traverse the AST by calling
2894 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00002895
2896 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00002897 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002898 case Stmt::ImplicitCastExprClass: {
2899 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002900 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002901 E = IE->getSubExpr();
2902 continue;
2903 }
2904 return NULL;
2905 }
2906
John McCall80ee6e82011-11-10 05:35:25 +00002907 case Stmt::ExprWithCleanupsClass:
2908 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
2909
Douglas Gregora2813ce2009-10-23 18:54:35 +00002910 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002911 // When we hit a DeclRefExpr we are looking at code that refers to a
2912 // variable's name. If it's not a reference variable we check if it has
2913 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00002914 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002915
Ted Kremenek06de2762007-08-17 16:46:58 +00002916 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002917 if (V->hasLocalStorage()) {
2918 if (!V->getType()->isReferenceType())
2919 return DR;
2920
2921 // Reference variable, follow through to the expression that
2922 // it points to.
2923 if (V->hasInit()) {
2924 // Add the reference variable to the "trail".
2925 refVars.push_back(DR);
2926 return EvalVal(V->getInit(), refVars);
2927 }
2928 }
Mike Stump1eb44332009-09-09 15:08:12 +00002929
Ted Kremenek06de2762007-08-17 16:46:58 +00002930 return NULL;
2931 }
Mike Stump1eb44332009-09-09 15:08:12 +00002932
Ted Kremenek06de2762007-08-17 16:46:58 +00002933 case Stmt::UnaryOperatorClass: {
2934 // The only unary operator that make sense to handle here
2935 // is Deref. All others don't resolve to a "name." This includes
2936 // handling all sorts of rvalues passed to a unary operator.
2937 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002938
John McCall2de56d12010-08-25 11:45:40 +00002939 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002940 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002941
2942 return NULL;
2943 }
Mike Stump1eb44332009-09-09 15:08:12 +00002944
Ted Kremenek06de2762007-08-17 16:46:58 +00002945 case Stmt::ArraySubscriptExprClass: {
2946 // Array subscripts are potential references to data on the stack. We
2947 // retrieve the DeclRefExpr* for the array variable if it indeed
2948 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002949 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002950 }
Mike Stump1eb44332009-09-09 15:08:12 +00002951
Ted Kremenek06de2762007-08-17 16:46:58 +00002952 case Stmt::ConditionalOperatorClass: {
2953 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002954 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00002955 ConditionalOperator *C = cast<ConditionalOperator>(E);
2956
Anders Carlsson39073232007-11-30 19:04:31 +00002957 // Handle the GNU extension for missing LHS.
2958 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002959 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00002960 return LHS;
2961
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002962 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002963 }
Mike Stump1eb44332009-09-09 15:08:12 +00002964
Ted Kremenek06de2762007-08-17 16:46:58 +00002965 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002966 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002967 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002968
Ted Kremenek06de2762007-08-17 16:46:58 +00002969 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00002970 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00002971 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00002972
2973 // Check whether the member type is itself a reference, in which case
2974 // we're not going to refer to the member, but to what the member refers to.
2975 if (M->getMemberDecl()->getType()->isReferenceType())
2976 return NULL;
2977
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002978 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002979 }
Mike Stump1eb44332009-09-09 15:08:12 +00002980
Douglas Gregor03e80032011-06-21 17:03:29 +00002981 case Stmt::MaterializeTemporaryExprClass:
2982 if (Expr *Result = EvalVal(
2983 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2984 refVars))
2985 return Result;
2986
2987 return E;
2988
Ted Kremenek06de2762007-08-17 16:46:58 +00002989 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002990 // Check that we don't return or take the address of a reference to a
2991 // temporary. This is only useful in C++.
2992 if (!E->isTypeDependent() && E->isRValue())
2993 return E;
2994
2995 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00002996 return NULL;
2997 }
Ted Kremenek68957a92010-08-04 20:01:07 +00002998} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00002999}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003000
3001//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3002
3003/// Check for comparisons of floating point operands using != and ==.
3004/// Issue a warning if these are no self-comparisons, as they are not likely
3005/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003006void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003007 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003008
Richard Trieudd225092011-09-15 21:56:47 +00003009 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3010 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003011
3012 // Special case: check for x == x (which is OK).
3013 // Do not emit warnings for such cases.
3014 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3015 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3016 if (DRL->getDecl() == DRR->getDecl())
3017 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003018
3019
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003020 // Special case: check for comparisons against literals that can be exactly
3021 // represented by APFloat. In such cases, do not emit a warning. This
3022 // is a heuristic: often comparison against such literals are used to
3023 // detect if a value in a variable has not changed. This clearly can
3024 // lead to false negatives.
3025 if (EmitWarning) {
3026 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3027 if (FLL->isExact())
3028 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003029 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003030 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
3031 if (FLR->isExact())
3032 EmitWarning = false;
3033 }
3034 }
Mike Stump1eb44332009-09-09 15:08:12 +00003035
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003036 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003037 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003038 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003039 if (CL->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003040 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003041
Sebastian Redl0eb23302009-01-19 00:08:26 +00003042 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003043 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003044 if (CR->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003045 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003046
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003047 // Emit the diagnostic.
3048 if (EmitWarning)
Richard Trieudd225092011-09-15 21:56:47 +00003049 Diag(Loc, diag::warn_floatingpoint_eq)
3050 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003051}
John McCallba26e582010-01-04 23:21:16 +00003052
John McCallf2370c92010-01-06 05:24:50 +00003053//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3054//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003055
John McCallf2370c92010-01-06 05:24:50 +00003056namespace {
John McCallba26e582010-01-04 23:21:16 +00003057
John McCallf2370c92010-01-06 05:24:50 +00003058/// Structure recording the 'active' range of an integer-valued
3059/// expression.
3060struct IntRange {
3061 /// The number of bits active in the int.
3062 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003063
John McCallf2370c92010-01-06 05:24:50 +00003064 /// True if the int is known not to have negative values.
3065 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003066
John McCallf2370c92010-01-06 05:24:50 +00003067 IntRange(unsigned Width, bool NonNegative)
3068 : Width(Width), NonNegative(NonNegative)
3069 {}
John McCallba26e582010-01-04 23:21:16 +00003070
John McCall1844a6e2010-11-10 23:38:19 +00003071 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00003072 static IntRange forBoolType() {
3073 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00003074 }
3075
John McCall1844a6e2010-11-10 23:38:19 +00003076 /// Returns the range of an opaque value of the given integral type.
3077 static IntRange forValueOfType(ASTContext &C, QualType T) {
3078 return forValueOfCanonicalType(C,
3079 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00003080 }
3081
John McCall1844a6e2010-11-10 23:38:19 +00003082 /// Returns the range of an opaque value of a canonical integral type.
3083 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00003084 assert(T->isCanonicalUnqualified());
3085
3086 if (const VectorType *VT = dyn_cast<VectorType>(T))
3087 T = VT->getElementType().getTypePtr();
3088 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3089 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00003090
John McCall091f23f2010-11-09 22:22:12 +00003091 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00003092 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3093 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00003094 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00003095 return IntRange(C.getIntWidth(QualType(T, 0)), false);
3096
John McCall323ed742010-05-06 08:58:33 +00003097 unsigned NumPositive = Enum->getNumPositiveBits();
3098 unsigned NumNegative = Enum->getNumNegativeBits();
3099
3100 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3101 }
John McCallf2370c92010-01-06 05:24:50 +00003102
3103 const BuiltinType *BT = cast<BuiltinType>(T);
3104 assert(BT->isInteger());
3105
3106 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3107 }
3108
John McCall1844a6e2010-11-10 23:38:19 +00003109 /// Returns the "target" range of a canonical integral type, i.e.
3110 /// the range of values expressible in the type.
3111 ///
3112 /// This matches forValueOfCanonicalType except that enums have the
3113 /// full range of their type, not the range of their enumerators.
3114 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3115 assert(T->isCanonicalUnqualified());
3116
3117 if (const VectorType *VT = dyn_cast<VectorType>(T))
3118 T = VT->getElementType().getTypePtr();
3119 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3120 T = CT->getElementType().getTypePtr();
3121 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00003122 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00003123
3124 const BuiltinType *BT = cast<BuiltinType>(T);
3125 assert(BT->isInteger());
3126
3127 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3128 }
3129
3130 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003131 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00003132 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00003133 L.NonNegative && R.NonNegative);
3134 }
3135
John McCall1844a6e2010-11-10 23:38:19 +00003136 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003137 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00003138 return IntRange(std::min(L.Width, R.Width),
3139 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00003140 }
3141};
3142
3143IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
3144 if (value.isSigned() && value.isNegative())
3145 return IntRange(value.getMinSignedBits(), false);
3146
3147 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003148 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003149
3150 // isNonNegative() just checks the sign bit without considering
3151 // signedness.
3152 return IntRange(value.getActiveBits(), true);
3153}
3154
John McCall0acc3112010-01-06 22:57:21 +00003155IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00003156 unsigned MaxWidth) {
3157 if (result.isInt())
3158 return GetValueRange(C, result.getInt(), MaxWidth);
3159
3160 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00003161 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3162 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3163 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3164 R = IntRange::join(R, El);
3165 }
John McCallf2370c92010-01-06 05:24:50 +00003166 return R;
3167 }
3168
3169 if (result.isComplexInt()) {
3170 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3171 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3172 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00003173 }
3174
3175 // This can happen with lossless casts to intptr_t of "based" lvalues.
3176 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00003177 // FIXME: The only reason we need to pass the type in here is to get
3178 // the sign right on this one case. It would be nice if APValue
3179 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00003180 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003181 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00003182}
John McCallf2370c92010-01-06 05:24:50 +00003183
3184/// Pseudo-evaluate the given integer expression, estimating the
3185/// range of values it might take.
3186///
3187/// \param MaxWidth - the width to which the value will be truncated
3188IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
3189 E = E->IgnoreParens();
3190
3191 // Try a full evaluation first.
3192 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003193 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00003194 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003195
3196 // I think we only want to look through implicit casts here; if the
3197 // user has an explicit widening cast, we should treat the value as
3198 // being of the new, wider type.
3199 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00003200 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00003201 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3202
John McCall1844a6e2010-11-10 23:38:19 +00003203 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00003204
John McCall2de56d12010-08-25 11:45:40 +00003205 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00003206
John McCallf2370c92010-01-06 05:24:50 +00003207 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00003208 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00003209 return OutputTypeRange;
3210
3211 IntRange SubRange
3212 = GetExprRange(C, CE->getSubExpr(),
3213 std::min(MaxWidth, OutputTypeRange.Width));
3214
3215 // Bail out if the subexpr's range is as wide as the cast type.
3216 if (SubRange.Width >= OutputTypeRange.Width)
3217 return OutputTypeRange;
3218
3219 // Otherwise, we take the smaller width, and we're non-negative if
3220 // either the output type or the subexpr is.
3221 return IntRange(SubRange.Width,
3222 SubRange.NonNegative || OutputTypeRange.NonNegative);
3223 }
3224
3225 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3226 // If we can fold the condition, just take that operand.
3227 bool CondResult;
3228 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3229 return GetExprRange(C, CondResult ? CO->getTrueExpr()
3230 : CO->getFalseExpr(),
3231 MaxWidth);
3232
3233 // Otherwise, conservatively merge.
3234 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3235 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3236 return IntRange::join(L, R);
3237 }
3238
3239 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3240 switch (BO->getOpcode()) {
3241
3242 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00003243 case BO_LAnd:
3244 case BO_LOr:
3245 case BO_LT:
3246 case BO_GT:
3247 case BO_LE:
3248 case BO_GE:
3249 case BO_EQ:
3250 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00003251 return IntRange::forBoolType();
3252
John McCall862ff872011-07-13 06:35:24 +00003253 // The type of the assignments is the type of the LHS, so the RHS
3254 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00003255 case BO_MulAssign:
3256 case BO_DivAssign:
3257 case BO_RemAssign:
3258 case BO_AddAssign:
3259 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00003260 case BO_XorAssign:
3261 case BO_OrAssign:
3262 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00003263 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00003264
John McCall862ff872011-07-13 06:35:24 +00003265 // Simple assignments just pass through the RHS, which will have
3266 // been coerced to the LHS type.
3267 case BO_Assign:
3268 // TODO: bitfields?
3269 return GetExprRange(C, BO->getRHS(), MaxWidth);
3270
John McCallf2370c92010-01-06 05:24:50 +00003271 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003272 case BO_PtrMemD:
3273 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00003274 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003275
John McCall60fad452010-01-06 22:07:33 +00003276 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00003277 case BO_And:
3278 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00003279 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3280 GetExprRange(C, BO->getRHS(), MaxWidth));
3281
John McCallf2370c92010-01-06 05:24:50 +00003282 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00003283 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00003284 // ...except that we want to treat '1 << (blah)' as logically
3285 // positive. It's an important idiom.
3286 if (IntegerLiteral *I
3287 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3288 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00003289 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00003290 return IntRange(R.Width, /*NonNegative*/ true);
3291 }
3292 }
3293 // fallthrough
3294
John McCall2de56d12010-08-25 11:45:40 +00003295 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00003296 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003297
John McCall60fad452010-01-06 22:07:33 +00003298 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00003299 case BO_Shr:
3300 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00003301 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3302
3303 // If the shift amount is a positive constant, drop the width by
3304 // that much.
3305 llvm::APSInt shift;
3306 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3307 shift.isNonNegative()) {
3308 unsigned zext = shift.getZExtValue();
3309 if (zext >= L.Width)
3310 L.Width = (L.NonNegative ? 0 : 1);
3311 else
3312 L.Width -= zext;
3313 }
3314
3315 return L;
3316 }
3317
3318 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00003319 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00003320 return GetExprRange(C, BO->getRHS(), MaxWidth);
3321
John McCall60fad452010-01-06 22:07:33 +00003322 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00003323 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00003324 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00003325 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00003326 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003327
John McCall00fe7612011-07-14 22:39:48 +00003328 // The width of a division result is mostly determined by the size
3329 // of the LHS.
3330 case BO_Div: {
3331 // Don't 'pre-truncate' the operands.
3332 unsigned opWidth = C.getIntWidth(E->getType());
3333 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3334
3335 // If the divisor is constant, use that.
3336 llvm::APSInt divisor;
3337 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3338 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3339 if (log2 >= L.Width)
3340 L.Width = (L.NonNegative ? 0 : 1);
3341 else
3342 L.Width = std::min(L.Width - log2, MaxWidth);
3343 return L;
3344 }
3345
3346 // Otherwise, just use the LHS's width.
3347 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3348 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3349 }
3350
3351 // The result of a remainder can't be larger than the result of
3352 // either side.
3353 case BO_Rem: {
3354 // Don't 'pre-truncate' the operands.
3355 unsigned opWidth = C.getIntWidth(E->getType());
3356 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3357 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3358
3359 IntRange meet = IntRange::meet(L, R);
3360 meet.Width = std::min(meet.Width, MaxWidth);
3361 return meet;
3362 }
3363
3364 // The default behavior is okay for these.
3365 case BO_Mul:
3366 case BO_Add:
3367 case BO_Xor:
3368 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00003369 break;
3370 }
3371
John McCall00fe7612011-07-14 22:39:48 +00003372 // The default case is to treat the operation as if it were closed
3373 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00003374 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3375 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3376 return IntRange::join(L, R);
3377 }
3378
3379 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3380 switch (UO->getOpcode()) {
3381 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00003382 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00003383 return IntRange::forBoolType();
3384
3385 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003386 case UO_Deref:
3387 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00003388 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003389
3390 default:
3391 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3392 }
3393 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003394
3395 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00003396 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003397 }
John McCallf2370c92010-01-06 05:24:50 +00003398
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003399 if (FieldDecl *BitField = E->getBitField())
3400 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003401 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00003402
John McCall1844a6e2010-11-10 23:38:19 +00003403 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003404}
John McCall51313c32010-01-04 23:31:57 +00003405
John McCall323ed742010-05-06 08:58:33 +00003406IntRange GetExprRange(ASTContext &C, Expr *E) {
3407 return GetExprRange(C, E, C.getIntWidth(E->getType()));
3408}
3409
John McCall51313c32010-01-04 23:31:57 +00003410/// Checks whether the given value, which currently has the given
3411/// source semantics, has the same value when coerced through the
3412/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00003413bool IsSameFloatAfterCast(const llvm::APFloat &value,
3414 const llvm::fltSemantics &Src,
3415 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003416 llvm::APFloat truncated = value;
3417
3418 bool ignored;
3419 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3420 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3421
3422 return truncated.bitwiseIsEqual(value);
3423}
3424
3425/// Checks whether the given value, which currently has the given
3426/// source semantics, has the same value when coerced through the
3427/// target semantics.
3428///
3429/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00003430bool IsSameFloatAfterCast(const APValue &value,
3431 const llvm::fltSemantics &Src,
3432 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003433 if (value.isFloat())
3434 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3435
3436 if (value.isVector()) {
3437 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3438 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3439 return false;
3440 return true;
3441 }
3442
3443 assert(value.isComplexFloat());
3444 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3445 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3446}
3447
John McCallb4eb64d2010-10-08 02:01:28 +00003448void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00003449
Ted Kremeneke3b159c2010-09-23 21:43:44 +00003450static bool IsZero(Sema &S, Expr *E) {
3451 // Suppress cases where we are comparing against an enum constant.
3452 if (const DeclRefExpr *DR =
3453 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3454 if (isa<EnumConstantDecl>(DR->getDecl()))
3455 return false;
3456
3457 // Suppress cases where the '0' value is expanded from a macro.
3458 if (E->getLocStart().isMacroID())
3459 return false;
3460
John McCall323ed742010-05-06 08:58:33 +00003461 llvm::APSInt Value;
3462 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3463}
3464
John McCall372e1032010-10-06 00:25:24 +00003465static bool HasEnumType(Expr *E) {
3466 // Strip off implicit integral promotions.
3467 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003468 if (ICE->getCastKind() != CK_IntegralCast &&
3469 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00003470 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003471 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00003472 }
3473
3474 return E->getType()->isEnumeralType();
3475}
3476
John McCall323ed742010-05-06 08:58:33 +00003477void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003478 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00003479 if (E->isValueDependent())
3480 return;
3481
John McCall2de56d12010-08-25 11:45:40 +00003482 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003483 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003484 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003485 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003486 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003487 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003488 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003489 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003490 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003491 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003492 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003493 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003494 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003495 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003496 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003497 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3498 }
3499}
3500
3501/// Analyze the operands of the given comparison. Implements the
3502/// fallback case from AnalyzeComparison.
3503void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00003504 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3505 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00003506}
John McCall51313c32010-01-04 23:31:57 +00003507
John McCallba26e582010-01-04 23:21:16 +00003508/// \brief Implements -Wsign-compare.
3509///
Richard Trieudd225092011-09-15 21:56:47 +00003510/// \param E the binary operator to check for warnings
John McCall323ed742010-05-06 08:58:33 +00003511void AnalyzeComparison(Sema &S, BinaryOperator *E) {
3512 // The type the comparison is being performed in.
3513 QualType T = E->getLHS()->getType();
3514 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3515 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00003516
John McCall323ed742010-05-06 08:58:33 +00003517 // We don't do anything special if this isn't an unsigned integral
3518 // comparison: we're only interested in integral comparisons, and
3519 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00003520 //
3521 // We also don't care about value-dependent expressions or expressions
3522 // whose result is a constant.
3523 if (!T->hasUnsignedIntegerRepresentation()
3524 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00003525 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00003526
Richard Trieudd225092011-09-15 21:56:47 +00003527 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3528 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00003529
John McCall323ed742010-05-06 08:58:33 +00003530 // Check to see if one of the (unmodified) operands is of different
3531 // signedness.
3532 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00003533 if (LHS->getType()->hasSignedIntegerRepresentation()) {
3534 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00003535 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00003536 signedOperand = LHS;
3537 unsignedOperand = RHS;
3538 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3539 signedOperand = RHS;
3540 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00003541 } else {
John McCall323ed742010-05-06 08:58:33 +00003542 CheckTrivialUnsignedComparison(S, E);
3543 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003544 }
3545
John McCall323ed742010-05-06 08:58:33 +00003546 // Otherwise, calculate the effective range of the signed operand.
3547 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00003548
John McCall323ed742010-05-06 08:58:33 +00003549 // Go ahead and analyze implicit conversions in the operands. Note
3550 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00003551 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3552 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00003553
John McCall323ed742010-05-06 08:58:33 +00003554 // If the signed range is non-negative, -Wsign-compare won't fire,
3555 // but we should still check for comparisons which are always true
3556 // or false.
3557 if (signedRange.NonNegative)
3558 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003559
3560 // For (in)equality comparisons, if the unsigned operand is a
3561 // constant which cannot collide with a overflowed signed operand,
3562 // then reinterpreting the signed operand as unsigned will not
3563 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00003564 if (E->isEqualityOp()) {
3565 unsigned comparisonWidth = S.Context.getIntWidth(T);
3566 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00003567
John McCall323ed742010-05-06 08:58:33 +00003568 // We should never be unable to prove that the unsigned operand is
3569 // non-negative.
3570 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3571
3572 if (unsignedRange.Width < comparisonWidth)
3573 return;
3574 }
3575
3576 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
Richard Trieudd225092011-09-15 21:56:47 +00003577 << LHS->getType() << RHS->getType()
3578 << LHS->getSourceRange() << RHS->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00003579}
3580
John McCall15d7d122010-11-11 03:21:53 +00003581/// Analyzes an attempt to assign the given value to a bitfield.
3582///
3583/// Returns true if there was something fishy about the attempt.
3584bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3585 SourceLocation InitLoc) {
3586 assert(Bitfield->isBitField());
3587 if (Bitfield->isInvalidDecl())
3588 return false;
3589
John McCall91b60142010-11-11 05:33:51 +00003590 // White-list bool bitfields.
3591 if (Bitfield->getType()->isBooleanType())
3592 return false;
3593
Douglas Gregor46ff3032011-02-04 13:09:01 +00003594 // Ignore value- or type-dependent expressions.
3595 if (Bitfield->getBitWidth()->isValueDependent() ||
3596 Bitfield->getBitWidth()->isTypeDependent() ||
3597 Init->isValueDependent() ||
3598 Init->isTypeDependent())
3599 return false;
3600
John McCall15d7d122010-11-11 03:21:53 +00003601 Expr *OriginalInit = Init->IgnoreParenImpCasts();
3602
Richard Smith80d4b552011-12-28 19:48:30 +00003603 llvm::APSInt Value;
3604 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00003605 return false;
3606
John McCall15d7d122010-11-11 03:21:53 +00003607 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003608 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00003609
3610 if (OriginalWidth <= FieldWidth)
3611 return false;
3612
Jay Foad9f71a8f2010-12-07 08:25:34 +00003613 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall15d7d122010-11-11 03:21:53 +00003614
3615 // It's fairly common to write values into signed bitfields
3616 // that, if sign-extended, would end up becoming a different
3617 // value. We don't want to warn about that.
3618 if (Value.isSigned() && Value.isNegative())
Jay Foad9f71a8f2010-12-07 08:25:34 +00003619 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003620 else
Jay Foad9f71a8f2010-12-07 08:25:34 +00003621 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003622
3623 if (Value == TruncatedValue)
3624 return false;
3625
3626 std::string PrettyValue = Value.toString(10);
3627 std::string PrettyTrunc = TruncatedValue.toString(10);
3628
3629 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3630 << PrettyValue << PrettyTrunc << OriginalInit->getType()
3631 << Init->getSourceRange();
3632
3633 return true;
3634}
3635
John McCallbeb22aa2010-11-09 23:24:47 +00003636/// Analyze the given simple or compound assignment for warning-worthy
3637/// operations.
3638void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
3639 // Just recurse on the LHS.
3640 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3641
3642 // We want to recurse on the RHS as normal unless we're assigning to
3643 // a bitfield.
3644 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00003645 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3646 E->getOperatorLoc())) {
3647 // Recurse, ignoring any implicit conversions on the RHS.
3648 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3649 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00003650 }
3651 }
3652
3653 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3654}
3655
John McCall51313c32010-01-04 23:31:57 +00003656/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003657void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
3658 SourceLocation CContext, unsigned diag) {
3659 S.Diag(E->getExprLoc(), diag)
3660 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3661}
3662
Chandler Carruthe1b02e02011-04-05 06:47:57 +00003663/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
3664void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
3665 unsigned diag) {
3666 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
3667}
3668
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003669/// Diagnose an implicit cast from a literal expression. Does not warn when the
3670/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003671void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3672 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003673 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003674 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003675 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003676 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3677 T->hasUnsignedIntegerRepresentation());
3678 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00003679 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003680 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00003681 return;
3682
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003683 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3684 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00003685}
3686
John McCall091f23f2010-11-09 22:22:12 +00003687std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3688 if (!Range.Width) return "0";
3689
3690 llvm::APSInt ValueInRange = Value;
3691 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00003692 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00003693 return ValueInRange.toString(10);
3694}
3695
John McCall323ed742010-05-06 08:58:33 +00003696void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003697 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00003698 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00003699
John McCall323ed742010-05-06 08:58:33 +00003700 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3701 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3702 if (Source == Target) return;
3703 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00003704
Chandler Carruth108f7562011-07-26 05:40:03 +00003705 // If the conversion context location is invalid don't complain. We also
3706 // don't want to emit a warning if the issue occurs from the expansion of
3707 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3708 // delay this check as long as possible. Once we detect we are in that
3709 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003710 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00003711 return;
3712
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003713 // Diagnose implicit casts to bool.
3714 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
3715 if (isa<StringLiteral>(E))
3716 // Warn on string literal to bool. Checks for string literals in logical
3717 // expressions, for instances, assert(0 && "error here"), is prevented
3718 // by a check in AnalyzeImplicitConversions().
3719 return DiagnoseImpCast(S, E, T, CC,
3720 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00003721 if (Source->isFunctionType()) {
3722 // Warn on function to bool. Checks free functions and static member
3723 // functions. Weakly imported functions are excluded from the check,
3724 // since it's common to test their value to check whether the linker
3725 // found a definition for them.
3726 ValueDecl *D = 0;
3727 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
3728 D = R->getDecl();
3729 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
3730 D = M->getMemberDecl();
3731 }
3732
3733 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00003734 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
3735 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
3736 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00003737 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
3738 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
3739 QualType ReturnType;
3740 UnresolvedSet<4> NonTemplateOverloads;
3741 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
3742 if (!ReturnType.isNull()
3743 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
3744 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
3745 << FixItHint::CreateInsertion(
3746 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00003747 return;
3748 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00003749 }
3750 }
David Blaikiee37cdc42011-09-29 04:06:47 +00003751 return; // Other casts to bool are not checked.
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003752 }
John McCall51313c32010-01-04 23:31:57 +00003753
3754 // Strip vector types.
3755 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003756 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003757 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003758 return;
John McCallb4eb64d2010-10-08 02:01:28 +00003759 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003760 }
Chris Lattnerb792b302011-06-14 04:51:15 +00003761
3762 // If the vector cast is cast between two vectors of the same size, it is
3763 // a bitcast, not a conversion.
3764 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3765 return;
John McCall51313c32010-01-04 23:31:57 +00003766
3767 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3768 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3769 }
3770
3771 // Strip complex types.
3772 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003773 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003774 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003775 return;
3776
John McCallb4eb64d2010-10-08 02:01:28 +00003777 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003778 }
John McCall51313c32010-01-04 23:31:57 +00003779
3780 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3781 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3782 }
3783
3784 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3785 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3786
3787 // If the source is floating point...
3788 if (SourceBT && SourceBT->isFloatingPoint()) {
3789 // ...and the target is floating point...
3790 if (TargetBT && TargetBT->isFloatingPoint()) {
3791 // ...then warn if we're dropping FP rank.
3792
3793 // Builtin FP kinds are ordered by increasing FP rank.
3794 if (SourceBT->getKind() > TargetBT->getKind()) {
3795 // Don't warn about float constants that are precisely
3796 // representable in the target type.
3797 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003798 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00003799 // Value might be a float, a float vector, or a float complex.
3800 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00003801 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3802 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00003803 return;
3804 }
3805
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003806 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003807 return;
3808
John McCallb4eb64d2010-10-08 02:01:28 +00003809 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00003810 }
3811 return;
3812 }
3813
Ted Kremenekef9ff882011-03-10 20:03:42 +00003814 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00003815 if ((TargetBT && TargetBT->isInteger())) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003816 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003817 return;
3818
Chandler Carrutha5b93322011-02-17 11:05:49 +00003819 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00003820 // We also want to warn on, e.g., "int i = -1.234"
3821 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
3822 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
3823 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
3824
Chandler Carruthf65076e2011-04-10 08:36:24 +00003825 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3826 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00003827 } else {
3828 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3829 }
3830 }
John McCall51313c32010-01-04 23:31:57 +00003831
3832 return;
3833 }
3834
John McCallf2370c92010-01-06 05:24:50 +00003835 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00003836 return;
3837
Richard Trieu1838ca52011-05-29 19:59:02 +00003838 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3839 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3840 S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
3841 << E->getSourceRange() << clang::SourceRange(CC);
3842 return;
3843 }
3844
John McCall323ed742010-05-06 08:58:33 +00003845 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00003846 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00003847
3848 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00003849 // If the source is a constant, use a default-on diagnostic.
3850 // TODO: this should happen for bitfield stores, too.
3851 llvm::APSInt Value(32);
3852 if (E->isIntegerConstantExpr(Value, S.Context)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003853 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003854 return;
3855
John McCall091f23f2010-11-09 22:22:12 +00003856 std::string PrettySourceValue = Value.toString(10);
3857 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
3858
Ted Kremenek5e745da2011-10-22 02:37:33 +00003859 S.DiagRuntimeBehavior(E->getExprLoc(), E,
3860 S.PDiag(diag::warn_impcast_integer_precision_constant)
3861 << PrettySourceValue << PrettyTargetValue
3862 << E->getType() << T << E->getSourceRange()
3863 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00003864 return;
3865 }
3866
Chris Lattnerb792b302011-06-14 04:51:15 +00003867 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003868 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003869 return;
3870
John McCallf2370c92010-01-06 05:24:50 +00003871 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00003872 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
3873 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00003874 }
3875
3876 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
3877 (!TargetRange.NonNegative && SourceRange.NonNegative &&
3878 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003879
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003880 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003881 return;
3882
John McCall323ed742010-05-06 08:58:33 +00003883 unsigned DiagID = diag::warn_impcast_integer_sign;
3884
3885 // Traditionally, gcc has warned about this under -Wsign-compare.
3886 // We also want to warn about it in -Wconversion.
3887 // So if -Wconversion is off, use a completely identical diagnostic
3888 // in the sign-compare group.
3889 // The conditional-checking code will
3890 if (ICContext) {
3891 DiagID = diag::warn_impcast_integer_sign_conditional;
3892 *ICContext = true;
3893 }
3894
John McCallb4eb64d2010-10-08 02:01:28 +00003895 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00003896 }
3897
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003898 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003899 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3900 // type, to give us better diagnostics.
3901 QualType SourceType = E->getType();
3902 if (!S.getLangOptions().CPlusPlus) {
3903 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3904 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3905 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
3906 SourceType = S.Context.getTypeDeclType(Enum);
3907 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3908 }
3909 }
3910
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003911 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3912 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3913 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003914 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003915 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003916 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00003917 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003918 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003919 return;
3920
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003921 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003922 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003923 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003924
John McCall51313c32010-01-04 23:31:57 +00003925 return;
3926}
3927
John McCall323ed742010-05-06 08:58:33 +00003928void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3929
3930void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003931 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00003932 E = E->IgnoreParenImpCasts();
3933
3934 if (isa<ConditionalOperator>(E))
3935 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
3936
John McCallb4eb64d2010-10-08 02:01:28 +00003937 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003938 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003939 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00003940 return;
3941}
3942
3943void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00003944 SourceLocation CC = E->getQuestionLoc();
3945
3946 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00003947
3948 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00003949 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3950 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003951
3952 // If -Wconversion would have warned about either of the candidates
3953 // for a signedness conversion to the context type...
3954 if (!Suspicious) return;
3955
3956 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003957 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
3958 CC))
John McCall323ed742010-05-06 08:58:33 +00003959 return;
3960
John McCall323ed742010-05-06 08:58:33 +00003961 // ...then check whether it would have warned about either of the
3962 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00003963 if (E->getType() == T) return;
3964
3965 Suspicious = false;
3966 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
3967 E->getType(), CC, &Suspicious);
3968 if (!Suspicious)
3969 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003970 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003971}
3972
3973/// AnalyzeImplicitConversions - Find and report any interesting
3974/// implicit conversions in the given expression. There are a couple
3975/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003976void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003977 QualType T = OrigE->getType();
3978 Expr *E = OrigE->IgnoreParenImpCasts();
3979
Douglas Gregorf8b6e152011-10-10 17:38:18 +00003980 if (E->isTypeDependent() || E->isValueDependent())
3981 return;
3982
John McCall323ed742010-05-06 08:58:33 +00003983 // For conditional operators, we analyze the arguments as if they
3984 // were being fed directly into the output.
3985 if (isa<ConditionalOperator>(E)) {
3986 ConditionalOperator *CO = cast<ConditionalOperator>(E);
3987 CheckConditionalOperator(S, CO, T);
3988 return;
3989 }
3990
3991 // Go ahead and check any implicit conversions we might have skipped.
3992 // The non-canonical typecheck is just an optimization;
3993 // CheckImplicitConversion will filter out dead implicit conversions.
3994 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003995 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00003996
3997 // Now continue drilling into this expression.
3998
3999 // Skip past explicit casts.
4000 if (isa<ExplicitCastExpr>(E)) {
4001 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00004002 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004003 }
4004
John McCallbeb22aa2010-11-09 23:24:47 +00004005 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4006 // Do a somewhat different check with comparison operators.
4007 if (BO->isComparisonOp())
4008 return AnalyzeComparison(S, BO);
4009
4010 // And with assignments and compound assignments.
4011 if (BO->isAssignmentOp())
4012 return AnalyzeAssignment(S, BO);
4013 }
John McCall323ed742010-05-06 08:58:33 +00004014
4015 // These break the otherwise-useful invariant below. Fortunately,
4016 // we don't really need to recurse into them, because any internal
4017 // expressions should have been analyzed already when they were
4018 // built into statements.
4019 if (isa<StmtExpr>(E)) return;
4020
4021 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004022 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00004023
4024 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00004025 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004026 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
4027 bool IsLogicalOperator = BO && BO->isLogicalOp();
4028 for (Stmt::child_range I = E->children(); I; ++I) {
4029 Expr *ChildExpr = cast<Expr>(*I);
4030 if (IsLogicalOperator &&
4031 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
4032 // Ignore checking string literals that are in logical operators.
4033 continue;
4034 AnalyzeImplicitConversions(S, ChildExpr, CC);
4035 }
John McCall323ed742010-05-06 08:58:33 +00004036}
4037
4038} // end anonymous namespace
4039
4040/// Diagnoses "dangerous" implicit conversions within the given
4041/// expression (which is a full expression). Implements -Wconversion
4042/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004043///
4044/// \param CC the "context" location of the implicit conversion, i.e.
4045/// the most location of the syntactic entity requiring the implicit
4046/// conversion
4047void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004048 // Don't diagnose in unevaluated contexts.
4049 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
4050 return;
4051
4052 // Don't diagnose for value- or type-dependent expressions.
4053 if (E->isTypeDependent() || E->isValueDependent())
4054 return;
4055
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004056 // Check for array bounds violations in cases where the check isn't triggered
4057 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
4058 // ArraySubscriptExpr is on the RHS of a variable initialization.
4059 CheckArrayAccess(E);
4060
John McCallb4eb64d2010-10-08 02:01:28 +00004061 // This is not the right CC for (e.g.) a variable initialization.
4062 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004063}
4064
John McCall15d7d122010-11-11 03:21:53 +00004065void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
4066 FieldDecl *BitField,
4067 Expr *Init) {
4068 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
4069}
4070
Mike Stumpf8c49212010-01-21 03:59:47 +00004071/// CheckParmsForFunctionDef - Check that the parameters of the given
4072/// function are appropriate for the definition of a function. This
4073/// takes care of any checks that cannot be performed on the
4074/// declaration itself, e.g., that the types of each of the function
4075/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004076bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
4077 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004078 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00004079 for (; P != PEnd; ++P) {
4080 ParmVarDecl *Param = *P;
4081
Mike Stumpf8c49212010-01-21 03:59:47 +00004082 // C99 6.7.5.3p4: the parameters in a parameter type list in a
4083 // function declarator that is part of a function definition of
4084 // that function shall not have incomplete type.
4085 //
4086 // This is also C++ [dcl.fct]p6.
4087 if (!Param->isInvalidDecl() &&
4088 RequireCompleteType(Param->getLocation(), Param->getType(),
4089 diag::err_typecheck_decl_incomplete_type)) {
4090 Param->setInvalidDecl();
4091 HasInvalidParm = true;
4092 }
4093
4094 // C99 6.9.1p5: If the declarator includes a parameter type list, the
4095 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004096 if (CheckParameterNames &&
4097 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00004098 !Param->isImplicit() &&
4099 !getLangOptions().CPlusPlus)
4100 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00004101
4102 // C99 6.7.5.3p12:
4103 // If the function declarator is not part of a definition of that
4104 // function, parameters may have incomplete type and may use the [*]
4105 // notation in their sequences of declarator specifiers to specify
4106 // variable length array types.
4107 QualType PType = Param->getOriginalType();
4108 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
4109 if (AT->getSizeModifier() == ArrayType::Star) {
4110 // FIXME: This diagnosic should point the the '[*]' if source-location
4111 // information is added for it.
4112 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
4113 }
4114 }
Mike Stumpf8c49212010-01-21 03:59:47 +00004115 }
4116
4117 return HasInvalidParm;
4118}
John McCallb7f4ffe2010-08-12 21:44:57 +00004119
4120/// CheckCastAlign - Implements -Wcast-align, which warns when a
4121/// pointer cast increases the alignment requirements.
4122void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
4123 // This is actually a lot of work to potentially be doing on every
4124 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004125 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
4126 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00004127 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00004128 return;
4129
4130 // Ignore dependent types.
4131 if (T->isDependentType() || Op->getType()->isDependentType())
4132 return;
4133
4134 // Require that the destination be a pointer type.
4135 const PointerType *DestPtr = T->getAs<PointerType>();
4136 if (!DestPtr) return;
4137
4138 // If the destination has alignment 1, we're done.
4139 QualType DestPointee = DestPtr->getPointeeType();
4140 if (DestPointee->isIncompleteType()) return;
4141 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
4142 if (DestAlign.isOne()) return;
4143
4144 // Require that the source be a pointer type.
4145 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
4146 if (!SrcPtr) return;
4147 QualType SrcPointee = SrcPtr->getPointeeType();
4148
4149 // Whitelist casts from cv void*. We already implicitly
4150 // whitelisted casts to cv void*, since they have alignment 1.
4151 // Also whitelist casts involving incomplete types, which implicitly
4152 // includes 'void'.
4153 if (SrcPointee->isIncompleteType()) return;
4154
4155 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
4156 if (SrcAlign >= DestAlign) return;
4157
4158 Diag(TRange.getBegin(), diag::warn_cast_align)
4159 << Op->getType() << T
4160 << static_cast<unsigned>(SrcAlign.getQuantity())
4161 << static_cast<unsigned>(DestAlign.getQuantity())
4162 << TRange << Op->getSourceRange();
4163}
4164
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004165static const Type* getElementType(const Expr *BaseExpr) {
4166 const Type* EltType = BaseExpr->getType().getTypePtr();
4167 if (EltType->isAnyPointerType())
4168 return EltType->getPointeeType().getTypePtr();
4169 else if (EltType->isArrayType())
4170 return EltType->getBaseElementTypeUnsafe();
4171 return EltType;
4172}
4173
Chandler Carruthc2684342011-08-05 09:10:50 +00004174/// \brief Check whether this array fits the idiom of a size-one tail padded
4175/// array member of a struct.
4176///
4177/// We avoid emitting out-of-bounds access warnings for such arrays as they are
4178/// commonly used to emulate flexible arrays in C89 code.
4179static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4180 const NamedDecl *ND) {
4181 if (Size != 1 || !ND) return false;
4182
4183 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4184 if (!FD) return false;
4185
4186 // Don't consider sizes resulting from macro expansions or template argument
4187 // substitution to form C89 tail-padded arrays.
4188 ConstantArrayTypeLoc TL =
4189 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
4190 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
4191 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4192 return false;
4193
4194 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00004195 if (!RD) return false;
4196 if (RD->isUnion()) return false;
4197 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
4198 if (!CRD->isStandardLayout()) return false;
4199 }
Chandler Carruthc2684342011-08-05 09:10:50 +00004200
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00004201 // See if this is the last field decl in the record.
4202 const Decl *D = FD;
4203 while ((D = D->getNextDeclInContext()))
4204 if (isa<FieldDecl>(D))
4205 return false;
4206 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00004207}
4208
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004209void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004210 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00004211 bool AllowOnePastEnd, bool IndexNegated) {
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004212 IndexExpr = IndexExpr->IgnoreParenCasts();
4213 if (IndexExpr->isValueDependent())
4214 return;
4215
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00004216 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004217 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00004218 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004219 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00004220 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00004221 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00004222
Chandler Carruth34064582011-02-17 20:55:08 +00004223 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004224 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00004225 return;
Richard Smith25b009a2011-12-16 19:31:14 +00004226 if (IndexNegated)
4227 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004228
Chandler Carruthba447122011-08-05 08:07:29 +00004229 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00004230 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4231 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00004232 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00004233 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00004234
Ted Kremenek9e060ca2011-02-23 23:06:04 +00004235 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00004236 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00004237 if (!size.isStrictlyPositive())
4238 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004239
4240 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00004241 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004242 // Make sure we're comparing apples to apples when comparing index to size
4243 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4244 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00004245 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00004246 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004247 if (ptrarith_typesize != array_typesize) {
4248 // There's a cast to a different size type involved
4249 uint64_t ratio = array_typesize / ptrarith_typesize;
4250 // TODO: Be smarter about handling cases where array_typesize is not a
4251 // multiple of ptrarith_typesize
4252 if (ptrarith_typesize * ratio == array_typesize)
4253 size *= llvm::APInt(size.getBitWidth(), ratio);
4254 }
4255 }
4256
Chandler Carruth34064582011-02-17 20:55:08 +00004257 if (size.getBitWidth() > index.getBitWidth())
4258 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004259 else if (size.getBitWidth() < index.getBitWidth())
4260 size = size.sext(index.getBitWidth());
4261
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004262 // For array subscripting the index must be less than size, but for pointer
4263 // arithmetic also allow the index (offset) to be equal to size since
4264 // computing the next address after the end of the array is legal and
4265 // commonly done e.g. in C++ iterators and range-based for loops.
4266 if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
Chandler Carruthba447122011-08-05 08:07:29 +00004267 return;
4268
4269 // Also don't warn for arrays of size 1 which are members of some
4270 // structure. These are often used to approximate flexible arrays in C89
4271 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004272 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004273 return;
Chandler Carruth34064582011-02-17 20:55:08 +00004274
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004275 // Suppress the warning if the subscript expression (as identified by the
4276 // ']' location) and the index expression are both from macro expansions
4277 // within a system header.
4278 if (ASE) {
4279 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
4280 ASE->getRBracketLoc());
4281 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
4282 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
4283 IndexExpr->getLocStart());
4284 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
4285 return;
4286 }
4287 }
4288
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004289 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004290 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004291 DiagID = diag::warn_array_index_exceeds_bounds;
4292
4293 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4294 PDiag(DiagID) << index.toString(10, true)
4295 << size.toString(10, true)
4296 << (unsigned)size.getLimitedValue(~0U)
4297 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00004298 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004299 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004300 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004301 DiagID = diag::warn_ptr_arith_precedes_bounds;
4302 if (index.isNegative()) index = -index;
4303 }
4304
4305 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4306 PDiag(DiagID) << index.toString(10, true)
4307 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004308 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00004309
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00004310 if (!ND) {
4311 // Try harder to find a NamedDecl to point at in the note.
4312 while (const ArraySubscriptExpr *ASE =
4313 dyn_cast<ArraySubscriptExpr>(BaseExpr))
4314 BaseExpr = ASE->getBase()->IgnoreParenCasts();
4315 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4316 ND = dyn_cast<NamedDecl>(DRE->getDecl());
4317 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
4318 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
4319 }
4320
Chandler Carruth35001ca2011-02-17 21:10:52 +00004321 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004322 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4323 PDiag(diag::note_array_index_out_of_bounds)
4324 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004325}
4326
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004327void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004328 int AllowOnePastEnd = 0;
4329 while (expr) {
4330 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004331 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004332 case Stmt::ArraySubscriptExprClass: {
4333 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004334 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004335 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004336 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004337 }
4338 case Stmt::UnaryOperatorClass: {
4339 // Only unwrap the * and & unary operators
4340 const UnaryOperator *UO = cast<UnaryOperator>(expr);
4341 expr = UO->getSubExpr();
4342 switch (UO->getOpcode()) {
4343 case UO_AddrOf:
4344 AllowOnePastEnd++;
4345 break;
4346 case UO_Deref:
4347 AllowOnePastEnd--;
4348 break;
4349 default:
4350 return;
4351 }
4352 break;
4353 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004354 case Stmt::ConditionalOperatorClass: {
4355 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4356 if (const Expr *lhs = cond->getLHS())
4357 CheckArrayAccess(lhs);
4358 if (const Expr *rhs = cond->getRHS())
4359 CheckArrayAccess(rhs);
4360 return;
4361 }
4362 default:
4363 return;
4364 }
Peter Collingbournef111d932011-04-15 00:35:48 +00004365 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004366}
John McCallf85e1932011-06-15 23:02:42 +00004367
4368//===--- CHECK: Objective-C retain cycles ----------------------------------//
4369
4370namespace {
4371 struct RetainCycleOwner {
4372 RetainCycleOwner() : Variable(0), Indirect(false) {}
4373 VarDecl *Variable;
4374 SourceRange Range;
4375 SourceLocation Loc;
4376 bool Indirect;
4377
4378 void setLocsFrom(Expr *e) {
4379 Loc = e->getExprLoc();
4380 Range = e->getSourceRange();
4381 }
4382 };
4383}
4384
4385/// Consider whether capturing the given variable can possibly lead to
4386/// a retain cycle.
4387static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4388 // In ARC, it's captured strongly iff the variable has __strong
4389 // lifetime. In MRR, it's captured strongly if the variable is
4390 // __block and has an appropriate type.
4391 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4392 return false;
4393
4394 owner.Variable = var;
4395 owner.setLocsFrom(ref);
4396 return true;
4397}
4398
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004399static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00004400 while (true) {
4401 e = e->IgnoreParens();
4402 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4403 switch (cast->getCastKind()) {
4404 case CK_BitCast:
4405 case CK_LValueBitCast:
4406 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00004407 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00004408 e = cast->getSubExpr();
4409 continue;
4410
John McCallf85e1932011-06-15 23:02:42 +00004411 default:
4412 return false;
4413 }
4414 }
4415
4416 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4417 ObjCIvarDecl *ivar = ref->getDecl();
4418 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4419 return false;
4420
4421 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004422 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00004423 return false;
4424
4425 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4426 owner.Indirect = true;
4427 return true;
4428 }
4429
4430 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4431 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4432 if (!var) return false;
4433 return considerVariable(var, ref, owner);
4434 }
4435
4436 if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
4437 owner.Variable = ref->getDecl();
4438 owner.setLocsFrom(ref);
4439 return true;
4440 }
4441
4442 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4443 if (member->isArrow()) return false;
4444
4445 // Don't count this as an indirect ownership.
4446 e = member->getBase();
4447 continue;
4448 }
4449
John McCall4b9c2d22011-11-06 09:01:30 +00004450 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
4451 // Only pay attention to pseudo-objects on property references.
4452 ObjCPropertyRefExpr *pre
4453 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
4454 ->IgnoreParens());
4455 if (!pre) return false;
4456 if (pre->isImplicitProperty()) return false;
4457 ObjCPropertyDecl *property = pre->getExplicitProperty();
4458 if (!property->isRetaining() &&
4459 !(property->getPropertyIvarDecl() &&
4460 property->getPropertyIvarDecl()->getType()
4461 .getObjCLifetime() == Qualifiers::OCL_Strong))
4462 return false;
4463
4464 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004465 if (pre->isSuperReceiver()) {
4466 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
4467 if (!owner.Variable)
4468 return false;
4469 owner.Loc = pre->getLocation();
4470 owner.Range = pre->getSourceRange();
4471 return true;
4472 }
John McCall4b9c2d22011-11-06 09:01:30 +00004473 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
4474 ->getSourceExpr());
4475 continue;
4476 }
4477
John McCallf85e1932011-06-15 23:02:42 +00004478 // Array ivars?
4479
4480 return false;
4481 }
4482}
4483
4484namespace {
4485 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4486 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4487 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4488 Variable(variable), Capturer(0) {}
4489
4490 VarDecl *Variable;
4491 Expr *Capturer;
4492
4493 void VisitDeclRefExpr(DeclRefExpr *ref) {
4494 if (ref->getDecl() == Variable && !Capturer)
4495 Capturer = ref;
4496 }
4497
4498 void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
4499 if (ref->getDecl() == Variable && !Capturer)
4500 Capturer = ref;
4501 }
4502
4503 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4504 if (Capturer) return;
4505 Visit(ref->getBase());
4506 if (Capturer && ref->isFreeIvar())
4507 Capturer = ref;
4508 }
4509
4510 void VisitBlockExpr(BlockExpr *block) {
4511 // Look inside nested blocks
4512 if (block->getBlockDecl()->capturesVariable(Variable))
4513 Visit(block->getBlockDecl()->getBody());
4514 }
4515 };
4516}
4517
4518/// Check whether the given argument is a block which captures a
4519/// variable.
4520static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4521 assert(owner.Variable && owner.Loc.isValid());
4522
4523 e = e->IgnoreParenCasts();
4524 BlockExpr *block = dyn_cast<BlockExpr>(e);
4525 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4526 return 0;
4527
4528 FindCaptureVisitor visitor(S.Context, owner.Variable);
4529 visitor.Visit(block->getBlockDecl()->getBody());
4530 return visitor.Capturer;
4531}
4532
4533static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4534 RetainCycleOwner &owner) {
4535 assert(capturer);
4536 assert(owner.Variable && owner.Loc.isValid());
4537
4538 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4539 << owner.Variable << capturer->getSourceRange();
4540 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4541 << owner.Indirect << owner.Range;
4542}
4543
4544/// Check for a keyword selector that starts with the word 'add' or
4545/// 'set'.
4546static bool isSetterLikeSelector(Selector sel) {
4547 if (sel.isUnarySelector()) return false;
4548
Chris Lattner5f9e2722011-07-23 10:55:15 +00004549 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00004550 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00004551 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00004552 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00004553 else if (str.startswith("add")) {
4554 // Specially whitelist 'addOperationWithBlock:'.
4555 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
4556 return false;
4557 str = str.substr(3);
4558 }
John McCallf85e1932011-06-15 23:02:42 +00004559 else
4560 return false;
4561
4562 if (str.empty()) return true;
4563 return !islower(str.front());
4564}
4565
4566/// Check a message send to see if it's likely to cause a retain cycle.
4567void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4568 // Only check instance methods whose selector looks like a setter.
4569 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4570 return;
4571
4572 // Try to find a variable that the receiver is strongly owned by.
4573 RetainCycleOwner owner;
4574 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004575 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00004576 return;
4577 } else {
4578 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4579 owner.Variable = getCurMethodDecl()->getSelfDecl();
4580 owner.Loc = msg->getSuperLoc();
4581 owner.Range = msg->getSuperLoc();
4582 }
4583
4584 // Check whether the receiver is captured by any of the arguments.
4585 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4586 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4587 return diagnoseRetainCycle(*this, capturer, owner);
4588}
4589
4590/// Check a property assign to see if it's likely to cause a retain cycle.
4591void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4592 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004593 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00004594 return;
4595
4596 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4597 diagnoseRetainCycle(*this, capturer, owner);
4598}
4599
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004600bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00004601 QualType LHS, Expr *RHS) {
4602 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4603 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004604 return false;
4605 // strip off any implicit cast added to get to the one arc-specific
4606 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004607 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00004608 Diag(Loc, diag::warn_arc_retained_assign)
4609 << (LT == Qualifiers::OCL_ExplicitNone)
4610 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004611 return true;
4612 }
4613 RHS = cast->getSubExpr();
4614 }
4615 return false;
John McCallf85e1932011-06-15 23:02:42 +00004616}
4617
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004618void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4619 Expr *LHS, Expr *RHS) {
4620 QualType LHSType = LHS->getType();
4621 if (checkUnsafeAssigns(Loc, LHSType, RHS))
4622 return;
4623 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4624 // FIXME. Check for other life times.
4625 if (LT != Qualifiers::OCL_None)
4626 return;
4627
John McCall3c3b7f92011-10-25 17:37:35 +00004628 if (ObjCPropertyRefExpr *PRE
4629 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens())) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004630 if (PRE->isImplicitProperty())
4631 return;
4632 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4633 if (!PD)
4634 return;
4635
4636 unsigned Attributes = PD->getPropertyAttributes();
4637 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign)
4638 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004639 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004640 Diag(Loc, diag::warn_arc_retained_property_assign)
4641 << RHS->getSourceRange();
4642 return;
4643 }
4644 RHS = cast->getSubExpr();
4645 }
4646 }
4647}