blob: cdc546c476197d32592c52bc65048e8782a5f421 [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner59907c42007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump1eb44332009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattner59907c42007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall2d887082010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattner59907c42007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikiebe0ee872012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenek23245122007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rose3f6f51e2013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000030#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/Initialization.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
35#include "llvm/ADT/BitVector.h"
36#include "llvm/ADT/STLExtras.h"
37#include "llvm/ADT/SmallString.h"
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +000038#include "llvm/Support/ConvertUTF.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/Support/raw_ostream.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000040#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000041using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000042using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000043
Chris Lattner60800082009-02-18 17:49:48 +000044SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000046 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +000047 PP.getLangOpts(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000048}
49
John McCall8e10f3b2011-02-26 05:39:39 +000050/// Checks that a call expression's argument count is the desired number.
51/// This is useful when doing custom type-checking. Returns true on error.
52static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53 unsigned argCount = call->getNumArgs();
54 if (argCount == desiredArgCount) return false;
55
56 if (argCount < desiredArgCount)
57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58 << 0 /*function call*/ << desiredArgCount << argCount
59 << call->getSourceRange();
60
61 // Highlight all the excess arguments.
62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63 call->getArg(argCount - 1)->getLocEnd());
64
65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66 << 0 /*function call*/ << desiredArgCount << argCount
67 << call->getArg(1)->getSourceRange();
68}
69
Julien Lerougee5939212012-04-28 17:39:16 +000070/// Check that the first argument to __builtin_annotation is an integer
71/// and the second argument is a non-wide string literal.
72static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73 if (checkArgCount(S, TheCall, 2))
74 return true;
75
76 // First argument should be an integer.
77 Expr *ValArg = TheCall->getArg(0);
78 QualType Ty = ValArg->getType();
79 if (!Ty->isIntegerType()) {
80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81 << ValArg->getSourceRange();
Julien Lerouge77f68bb2011-09-09 22:41:49 +000082 return true;
83 }
Julien Lerougee5939212012-04-28 17:39:16 +000084
85 // Second argument should be a constant string.
86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88 if (!Literal || !Literal->isAscii()) {
89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90 << StrArg->getSourceRange();
91 return true;
92 }
93
94 TheCall->setType(Ty);
Julien Lerouge77f68bb2011-09-09 22:41:49 +000095 return false;
96}
97
John McCall60d7b3a2010-08-24 06:29:42 +000098ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +000099Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +0000100 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000101
Chris Lattner946928f2010-10-01 23:23:24 +0000102 // Find out if any arguments are required to be integer constant expressions.
103 unsigned ICEArguments = 0;
104 ASTContext::GetBuiltinTypeError Error;
105 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
106 if (Error != ASTContext::GE_None)
107 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
108
109 // If any arguments are required to be ICE's, check and diagnose.
110 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
111 // Skip arguments not required to be ICE's.
112 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
113
114 llvm::APSInt Result;
115 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
116 return true;
117 ICEArguments &= ~(1 << ArgNo);
118 }
119
Anders Carlssond406bf02009-08-16 01:56:34 +0000120 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000121 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000122 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000123 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000124 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000125 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000126 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000127 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000128 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000129 if (SemaBuiltinVAStart(TheCall))
130 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000131 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000132 case Builtin::BI__builtin_isgreater:
133 case Builtin::BI__builtin_isgreaterequal:
134 case Builtin::BI__builtin_isless:
135 case Builtin::BI__builtin_islessequal:
136 case Builtin::BI__builtin_islessgreater:
137 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000138 if (SemaBuiltinUnorderedCompare(TheCall))
139 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000140 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000141 case Builtin::BI__builtin_fpclassify:
142 if (SemaBuiltinFPClassification(TheCall, 6))
143 return ExprError();
144 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000145 case Builtin::BI__builtin_isfinite:
146 case Builtin::BI__builtin_isinf:
147 case Builtin::BI__builtin_isinf_sign:
148 case Builtin::BI__builtin_isnan:
149 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000150 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000151 return ExprError();
152 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000153 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000154 return SemaBuiltinShuffleVector(TheCall);
155 // TheCall will be freed by the smart pointer here, but that's fine, since
156 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000157 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000158 if (SemaBuiltinPrefetch(TheCall))
159 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000160 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000161 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000162 if (SemaBuiltinObjectSize(TheCall))
163 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000164 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000165 case Builtin::BI__builtin_longjmp:
166 if (SemaBuiltinLongjmp(TheCall))
167 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000168 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000169
170 case Builtin::BI__builtin_classify_type:
171 if (checkArgCount(*this, TheCall, 1)) return true;
172 TheCall->setType(Context.IntTy);
173 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000174 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000175 if (checkArgCount(*this, TheCall, 1)) return true;
176 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000177 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000178 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000179 case Builtin::BI__sync_fetch_and_add_1:
180 case Builtin::BI__sync_fetch_and_add_2:
181 case Builtin::BI__sync_fetch_and_add_4:
182 case Builtin::BI__sync_fetch_and_add_8:
183 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000184 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000185 case Builtin::BI__sync_fetch_and_sub_1:
186 case Builtin::BI__sync_fetch_and_sub_2:
187 case Builtin::BI__sync_fetch_and_sub_4:
188 case Builtin::BI__sync_fetch_and_sub_8:
189 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000190 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000191 case Builtin::BI__sync_fetch_and_or_1:
192 case Builtin::BI__sync_fetch_and_or_2:
193 case Builtin::BI__sync_fetch_and_or_4:
194 case Builtin::BI__sync_fetch_and_or_8:
195 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000196 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000197 case Builtin::BI__sync_fetch_and_and_1:
198 case Builtin::BI__sync_fetch_and_and_2:
199 case Builtin::BI__sync_fetch_and_and_4:
200 case Builtin::BI__sync_fetch_and_and_8:
201 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000202 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000203 case Builtin::BI__sync_fetch_and_xor_1:
204 case Builtin::BI__sync_fetch_and_xor_2:
205 case Builtin::BI__sync_fetch_and_xor_4:
206 case Builtin::BI__sync_fetch_and_xor_8:
207 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000208 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000209 case Builtin::BI__sync_add_and_fetch_1:
210 case Builtin::BI__sync_add_and_fetch_2:
211 case Builtin::BI__sync_add_and_fetch_4:
212 case Builtin::BI__sync_add_and_fetch_8:
213 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000214 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000215 case Builtin::BI__sync_sub_and_fetch_1:
216 case Builtin::BI__sync_sub_and_fetch_2:
217 case Builtin::BI__sync_sub_and_fetch_4:
218 case Builtin::BI__sync_sub_and_fetch_8:
219 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000220 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000221 case Builtin::BI__sync_and_and_fetch_1:
222 case Builtin::BI__sync_and_and_fetch_2:
223 case Builtin::BI__sync_and_and_fetch_4:
224 case Builtin::BI__sync_and_and_fetch_8:
225 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000226 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000227 case Builtin::BI__sync_or_and_fetch_1:
228 case Builtin::BI__sync_or_and_fetch_2:
229 case Builtin::BI__sync_or_and_fetch_4:
230 case Builtin::BI__sync_or_and_fetch_8:
231 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000232 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000233 case Builtin::BI__sync_xor_and_fetch_1:
234 case Builtin::BI__sync_xor_and_fetch_2:
235 case Builtin::BI__sync_xor_and_fetch_4:
236 case Builtin::BI__sync_xor_and_fetch_8:
237 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000238 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000239 case Builtin::BI__sync_val_compare_and_swap_1:
240 case Builtin::BI__sync_val_compare_and_swap_2:
241 case Builtin::BI__sync_val_compare_and_swap_4:
242 case Builtin::BI__sync_val_compare_and_swap_8:
243 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000244 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000245 case Builtin::BI__sync_bool_compare_and_swap_1:
246 case Builtin::BI__sync_bool_compare_and_swap_2:
247 case Builtin::BI__sync_bool_compare_and_swap_4:
248 case Builtin::BI__sync_bool_compare_and_swap_8:
249 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000250 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000251 case Builtin::BI__sync_lock_test_and_set_1:
252 case Builtin::BI__sync_lock_test_and_set_2:
253 case Builtin::BI__sync_lock_test_and_set_4:
254 case Builtin::BI__sync_lock_test_and_set_8:
255 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000256 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000257 case Builtin::BI__sync_lock_release_1:
258 case Builtin::BI__sync_lock_release_2:
259 case Builtin::BI__sync_lock_release_4:
260 case Builtin::BI__sync_lock_release_8:
261 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000262 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000263 case Builtin::BI__sync_swap_1:
264 case Builtin::BI__sync_swap_2:
265 case Builtin::BI__sync_swap_4:
266 case Builtin::BI__sync_swap_8:
267 case Builtin::BI__sync_swap_16:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000268 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithff34d402012-04-12 05:08:17 +0000269#define BUILTIN(ID, TYPE, ATTRS)
270#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
271 case Builtin::BI##ID: \
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000272 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithff34d402012-04-12 05:08:17 +0000273#include "clang/Basic/Builtins.def"
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000274 case Builtin::BI__builtin_annotation:
Julien Lerougee5939212012-04-28 17:39:16 +0000275 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000276 return ExprError();
277 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000278 }
279
280 // Since the target specific builtins for each arch overlap, only check those
281 // of the arch we are compiling for.
282 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000283 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000284 case llvm::Triple::arm:
285 case llvm::Triple::thumb:
286 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
287 return ExprError();
288 break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000289 case llvm::Triple::mips:
290 case llvm::Triple::mipsel:
291 case llvm::Triple::mips64:
292 case llvm::Triple::mips64el:
293 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
294 return ExprError();
295 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000296 default:
297 break;
298 }
299 }
300
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000301 return TheCallResult;
Nate Begeman26a31422010-06-08 02:47:44 +0000302}
303
Nate Begeman61eecf52010-06-14 05:21:25 +0000304// Get the valid immediate range for the specified NEON type code.
305static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000306 NeonTypeFlags Type(t);
307 int IsQuad = Type.isQuad();
308 switch (Type.getEltType()) {
309 case NeonTypeFlags::Int8:
310 case NeonTypeFlags::Poly8:
311 return shift ? 7 : (8 << IsQuad) - 1;
312 case NeonTypeFlags::Int16:
313 case NeonTypeFlags::Poly16:
314 return shift ? 15 : (4 << IsQuad) - 1;
315 case NeonTypeFlags::Int32:
316 return shift ? 31 : (2 << IsQuad) - 1;
317 case NeonTypeFlags::Int64:
318 return shift ? 63 : (1 << IsQuad) - 1;
319 case NeonTypeFlags::Float16:
320 assert(!shift && "cannot shift float types!");
321 return (4 << IsQuad) - 1;
322 case NeonTypeFlags::Float32:
323 assert(!shift && "cannot shift float types!");
324 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000325 }
David Blaikie7530c032012-01-17 06:56:22 +0000326 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000327}
328
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000329/// getNeonEltType - Return the QualType corresponding to the elements of
330/// the vector type specified by the NeonTypeFlags. This is used to check
331/// the pointer arguments for Neon load/store intrinsics.
332static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
333 switch (Flags.getEltType()) {
334 case NeonTypeFlags::Int8:
335 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
336 case NeonTypeFlags::Int16:
337 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
338 case NeonTypeFlags::Int32:
339 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
340 case NeonTypeFlags::Int64:
341 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
342 case NeonTypeFlags::Poly8:
343 return Context.SignedCharTy;
344 case NeonTypeFlags::Poly16:
345 return Context.ShortTy;
346 case NeonTypeFlags::Float16:
347 return Context.UnsignedShortTy;
348 case NeonTypeFlags::Float32:
349 return Context.FloatTy;
350 }
David Blaikie7530c032012-01-17 06:56:22 +0000351 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000352}
353
Nate Begeman26a31422010-06-08 02:47:44 +0000354bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000355 llvm::APSInt Result;
356
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000357 uint64_t mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000358 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000359 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000360 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000361 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000362#define GET_NEON_OVERLOAD_CHECK
363#include "clang/Basic/arm_neon.inc"
364#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000365 }
366
Nate Begeman0d15c532010-06-13 04:47:52 +0000367 // For NEON intrinsics which are overloaded on vector element type, validate
368 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000369 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000370 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000371 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000372 return true;
373
Bob Wilsonda95f732011-11-08 01:16:11 +0000374 TV = Result.getLimitedValue(64);
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000375 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000376 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000377 << TheCall->getArg(ImmArg)->getSourceRange();
378 }
379
Bob Wilson46482552011-11-16 21:32:23 +0000380 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000381 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000382 Expr *Arg = TheCall->getArg(PtrArgNum);
383 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
384 Arg = ICE->getSubExpr();
385 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
386 QualType RHSTy = RHS.get()->getType();
387 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
388 if (HasConstPtr)
389 EltTy = EltTy.withConst();
390 QualType LHSTy = Context.getPointerType(EltTy);
391 AssignConvertType ConvTy;
392 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
393 if (RHS.isInvalid())
394 return true;
395 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
396 RHS.get(), AA_Assigning))
397 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000398 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000399
Nate Begeman0d15c532010-06-13 04:47:52 +0000400 // For NEON intrinsics which take an immediate value as part of the
401 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000402 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000403 switch (BuiltinID) {
404 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000405 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
406 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000407 case ARM::BI__builtin_arm_vcvtr_f:
408 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000409#define GET_NEON_IMMEDIATE_CHECK
410#include "clang/Basic/arm_neon.inc"
411#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000412 };
413
Douglas Gregor592a4232012-06-29 01:05:22 +0000414 // We can't check the value of a dependent argument.
415 if (TheCall->getArg(i)->isTypeDependent() ||
416 TheCall->getArg(i)->isValueDependent())
417 return false;
418
Nate Begeman61eecf52010-06-14 05:21:25 +0000419 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000420 if (SemaBuiltinConstantArg(TheCall, i, Result))
421 return true;
422
Nate Begeman61eecf52010-06-14 05:21:25 +0000423 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000424 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000425 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000426 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000427 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000428
Nate Begeman99c40bb2010-08-03 21:32:34 +0000429 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000430 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000431}
Daniel Dunbarde454282008-10-02 18:44:07 +0000432
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000433bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
434 unsigned i = 0, l = 0, u = 0;
435 switch (BuiltinID) {
436 default: return false;
437 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
438 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyanbe22cb82012-08-27 12:29:20 +0000439 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
440 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
441 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
442 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
443 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000444 };
445
446 // We can't check the value of a dependent argument.
447 if (TheCall->getArg(i)->isTypeDependent() ||
448 TheCall->getArg(i)->isValueDependent())
449 return false;
450
451 // Check that the immediate argument is actually a constant.
452 llvm::APSInt Result;
453 if (SemaBuiltinConstantArg(TheCall, i, Result))
454 return true;
455
456 // Range check against the upper/lower values for this instruction.
457 unsigned Val = Result.getZExtValue();
458 if (Val < l || Val > u)
459 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
460 << l << u << TheCall->getArg(i)->getSourceRange();
461
462 return false;
463}
464
Richard Smith831421f2012-06-25 20:30:08 +0000465/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
466/// parameter with the FormatAttr's correct format_idx and firstDataArg.
467/// Returns true when the format fits the function and the FormatStringInfo has
468/// been populated.
469bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
470 FormatStringInfo *FSI) {
471 FSI->HasVAListArg = Format->getFirstArg() == 0;
472 FSI->FormatIdx = Format->getFormatIdx() - 1;
473 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssond406bf02009-08-16 01:56:34 +0000474
Richard Smith831421f2012-06-25 20:30:08 +0000475 // The way the format attribute works in GCC, the implicit this argument
476 // of member functions is counted. However, it doesn't appear in our own
477 // lists, so decrement format_idx in that case.
478 if (IsCXXMember) {
479 if(FSI->FormatIdx == 0)
480 return false;
481 --FSI->FormatIdx;
482 if (FSI->FirstDataArg != 0)
483 --FSI->FirstDataArg;
484 }
485 return true;
486}
Mike Stump1eb44332009-09-09 15:08:12 +0000487
Richard Smith831421f2012-06-25 20:30:08 +0000488/// Handles the checks for format strings, non-POD arguments to vararg
489/// functions, and NULL arguments passed to non-NULL parameters.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000490void Sema::checkCall(NamedDecl *FDecl,
491 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000492 unsigned NumProtoArgs,
493 bool IsMemberFunction,
494 SourceLocation Loc,
495 SourceRange Range,
496 VariadicCallType CallType) {
Jordan Rose66360e22012-10-02 01:49:54 +0000497 if (CurContext->isDependentContext())
498 return;
Daniel Dunbarde454282008-10-02 18:44:07 +0000499
Ted Kremenekc82faca2010-09-09 04:33:05 +0000500 // Printf and scanf checking.
Richard Smith831421f2012-06-25 20:30:08 +0000501 bool HandledFormatString = false;
Ted Kremenekc82faca2010-09-09 04:33:05 +0000502 for (specific_attr_iterator<FormatAttr>
Richard Smith831421f2012-06-25 20:30:08 +0000503 I = FDecl->specific_attr_begin<FormatAttr>(),
504 E = FDecl->specific_attr_end<FormatAttr>(); I != E ; ++I)
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000505 if (CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc, Range))
Richard Smith831421f2012-06-25 20:30:08 +0000506 HandledFormatString = true;
507
508 // Refuse POD arguments that weren't caught by the format string
509 // checks above.
510 if (!HandledFormatString && CallType != VariadicDoesNotApply)
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000511 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000512 // Args[ArgIdx] can be null in malformed code.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000513 if (const Expr *Arg = Args[ArgIdx])
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000514 variadicArgumentPODCheck(Arg, CallType);
515 }
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Ted Kremenekc82faca2010-09-09 04:33:05 +0000517 for (specific_attr_iterator<NonNullAttr>
Richard Smith831421f2012-06-25 20:30:08 +0000518 I = FDecl->specific_attr_begin<NonNullAttr>(),
519 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000520 CheckNonNullArguments(*I, Args.data(), Loc);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000521
522 // Type safety checking.
523 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
524 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
525 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>(); i != e; ++i) {
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000526 CheckArgumentWithTypeTag(*i, Args.data());
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000527 }
Richard Smith831421f2012-06-25 20:30:08 +0000528}
529
530/// CheckConstructorCall - Check a constructor call for correctness and safety
531/// properties not enforced by the C type system.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000532void Sema::CheckConstructorCall(FunctionDecl *FDecl,
533 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000534 const FunctionProtoType *Proto,
535 SourceLocation Loc) {
536 VariadicCallType CallType =
537 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000538 checkCall(FDecl, Args, Proto->getNumArgs(),
Richard Smith831421f2012-06-25 20:30:08 +0000539 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
540}
541
542/// CheckFunctionCall - Check a direct function call for various correctness
543/// and safety properties not strictly enforced by the C type system.
544bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
545 const FunctionProtoType *Proto) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000546 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
547 isa<CXXMethodDecl>(FDecl);
548 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
549 IsMemberOperatorCall;
Richard Smith831421f2012-06-25 20:30:08 +0000550 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
551 TheCall->getCallee());
552 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Eli Friedman2edcde82012-10-11 00:30:58 +0000553 Expr** Args = TheCall->getArgs();
554 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmandf75b0c2012-10-11 00:34:15 +0000555 if (IsMemberOperatorCall) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000556 // If this is a call to a member operator, hide the first argument
557 // from checkCall.
558 // FIXME: Our choice of AST representation here is less than ideal.
559 ++Args;
560 --NumArgs;
561 }
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000562 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs),
563 NumProtoArgs,
Richard Smith831421f2012-06-25 20:30:08 +0000564 IsMemberFunction, TheCall->getRParenLoc(),
565 TheCall->getCallee()->getSourceRange(), CallType);
566
567 IdentifierInfo *FnInfo = FDecl->getIdentifier();
568 // None of the checks below are needed for functions that don't have
569 // simple names (e.g., C++ conversion functions).
570 if (!FnInfo)
571 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +0000572
Anna Zaks0a151a12012-01-17 00:37:07 +0000573 unsigned CMId = FDecl->getMemoryFunctionKind();
574 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000575 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000576
Anna Zaksd9b859a2012-01-13 21:52:01 +0000577 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000578 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000579 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000580 else if (CMId == Builtin::BIstrncat)
581 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000582 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000583 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000584
Anders Carlssond406bf02009-08-16 01:56:34 +0000585 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000586}
587
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000588bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000589 ArrayRef<const Expr *> Args) {
Richard Smith831421f2012-06-25 20:30:08 +0000590 VariadicCallType CallType =
591 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000592
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000593 checkCall(Method, Args, Method->param_size(),
Richard Smith831421f2012-06-25 20:30:08 +0000594 /*IsMemberFunction=*/false,
595 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000596
597 return false;
598}
599
Richard Smith831421f2012-06-25 20:30:08 +0000600bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall,
601 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000602 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
603 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000604 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000605
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000606 QualType Ty = V->getType();
607 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000608 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000609
Richard Smith831421f2012-06-25 20:30:08 +0000610 VariadicCallType CallType =
611 Proto && Proto->isVariadic() ? VariadicBlock : VariadicDoesNotApply ;
612 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000613
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000614 checkCall(NDecl,
615 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
616 TheCall->getNumArgs()),
Richard Smith831421f2012-06-25 20:30:08 +0000617 NumProtoArgs, /*IsMemberFunction=*/false,
618 TheCall->getRParenLoc(),
619 TheCall->getCallee()->getSourceRange(), CallType);
620
Anders Carlssond406bf02009-08-16 01:56:34 +0000621 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000622}
623
Richard Smithff34d402012-04-12 05:08:17 +0000624ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
625 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000626 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
627 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000628
Richard Smithff34d402012-04-12 05:08:17 +0000629 // All these operations take one of the following forms:
630 enum {
631 // C __c11_atomic_init(A *, C)
632 Init,
633 // C __c11_atomic_load(A *, int)
634 Load,
635 // void __atomic_load(A *, CP, int)
636 Copy,
637 // C __c11_atomic_add(A *, M, int)
638 Arithmetic,
639 // C __atomic_exchange_n(A *, CP, int)
640 Xchg,
641 // void __atomic_exchange(A *, C *, CP, int)
642 GNUXchg,
643 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
644 C11CmpXchg,
645 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
646 GNUCmpXchg
647 } Form = Init;
648 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
649 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
650 // where:
651 // C is an appropriate type,
652 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
653 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
654 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
655 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000656
Richard Smithff34d402012-04-12 05:08:17 +0000657 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
658 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
659 && "need to update code for modified C11 atomics");
660 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
661 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
662 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
663 Op == AtomicExpr::AO__atomic_store_n ||
664 Op == AtomicExpr::AO__atomic_exchange_n ||
665 Op == AtomicExpr::AO__atomic_compare_exchange_n;
666 bool IsAddSub = false;
667
668 switch (Op) {
669 case AtomicExpr::AO__c11_atomic_init:
670 Form = Init;
671 break;
672
673 case AtomicExpr::AO__c11_atomic_load:
674 case AtomicExpr::AO__atomic_load_n:
675 Form = Load;
676 break;
677
678 case AtomicExpr::AO__c11_atomic_store:
679 case AtomicExpr::AO__atomic_load:
680 case AtomicExpr::AO__atomic_store:
681 case AtomicExpr::AO__atomic_store_n:
682 Form = Copy;
683 break;
684
685 case AtomicExpr::AO__c11_atomic_fetch_add:
686 case AtomicExpr::AO__c11_atomic_fetch_sub:
687 case AtomicExpr::AO__atomic_fetch_add:
688 case AtomicExpr::AO__atomic_fetch_sub:
689 case AtomicExpr::AO__atomic_add_fetch:
690 case AtomicExpr::AO__atomic_sub_fetch:
691 IsAddSub = true;
692 // Fall through.
693 case AtomicExpr::AO__c11_atomic_fetch_and:
694 case AtomicExpr::AO__c11_atomic_fetch_or:
695 case AtomicExpr::AO__c11_atomic_fetch_xor:
696 case AtomicExpr::AO__atomic_fetch_and:
697 case AtomicExpr::AO__atomic_fetch_or:
698 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000699 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000700 case AtomicExpr::AO__atomic_and_fetch:
701 case AtomicExpr::AO__atomic_or_fetch:
702 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000703 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000704 Form = Arithmetic;
705 break;
706
707 case AtomicExpr::AO__c11_atomic_exchange:
708 case AtomicExpr::AO__atomic_exchange_n:
709 Form = Xchg;
710 break;
711
712 case AtomicExpr::AO__atomic_exchange:
713 Form = GNUXchg;
714 break;
715
716 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
717 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
718 Form = C11CmpXchg;
719 break;
720
721 case AtomicExpr::AO__atomic_compare_exchange:
722 case AtomicExpr::AO__atomic_compare_exchange_n:
723 Form = GNUCmpXchg;
724 break;
725 }
726
727 // Check we have the right number of arguments.
728 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000729 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000730 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000731 << TheCall->getCallee()->getSourceRange();
732 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000733 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
734 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000735 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000736 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000737 << TheCall->getCallee()->getSourceRange();
738 return ExprError();
739 }
740
Richard Smithff34d402012-04-12 05:08:17 +0000741 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000742 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000743 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
744 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
745 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +0000746 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +0000747 << Ptr->getType() << Ptr->getSourceRange();
748 return ExprError();
749 }
750
Richard Smithff34d402012-04-12 05:08:17 +0000751 // For a __c11 builtin, this should be a pointer to an _Atomic type.
752 QualType AtomTy = pointerType->getPointeeType(); // 'A'
753 QualType ValType = AtomTy; // 'C'
754 if (IsC11) {
755 if (!AtomTy->isAtomicType()) {
756 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
757 << Ptr->getType() << Ptr->getSourceRange();
758 return ExprError();
759 }
Richard Smithbc57b102012-09-15 06:09:58 +0000760 if (AtomTy.isConstQualified()) {
761 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
762 << Ptr->getType() << Ptr->getSourceRange();
763 return ExprError();
764 }
Richard Smithff34d402012-04-12 05:08:17 +0000765 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +0000766 }
Eli Friedman276b0612011-10-11 02:20:01 +0000767
Richard Smithff34d402012-04-12 05:08:17 +0000768 // For an arithmetic operation, the implied arithmetic must be well-formed.
769 if (Form == Arithmetic) {
770 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
771 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
772 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
773 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
774 return ExprError();
775 }
776 if (!IsAddSub && !ValType->isIntegerType()) {
777 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
778 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
779 return ExprError();
780 }
781 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
782 // For __atomic_*_n operations, the value type must be a scalar integral or
783 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +0000784 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +0000785 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
786 return ExprError();
787 }
788
789 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
790 // For GNU atomics, require a trivially-copyable type. This is not part of
791 // the GNU atomics specification, but we enforce it for sanity.
792 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +0000793 << Ptr->getType() << Ptr->getSourceRange();
794 return ExprError();
795 }
796
Richard Smithff34d402012-04-12 05:08:17 +0000797 // FIXME: For any builtin other than a load, the ValType must not be
798 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +0000799
800 switch (ValType.getObjCLifetime()) {
801 case Qualifiers::OCL_None:
802 case Qualifiers::OCL_ExplicitNone:
803 // okay
804 break;
805
806 case Qualifiers::OCL_Weak:
807 case Qualifiers::OCL_Strong:
808 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +0000809 // FIXME: Can this happen? By this point, ValType should be known
810 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +0000811 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
812 << ValType << Ptr->getSourceRange();
813 return ExprError();
814 }
815
816 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +0000817 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000818 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +0000819 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +0000820 ResultType = Context.BoolTy;
821
Richard Smithff34d402012-04-12 05:08:17 +0000822 // The type of a parameter passed 'by value'. In the GNU atomics, such
823 // arguments are actually passed as pointers.
824 QualType ByValType = ValType; // 'CP'
825 if (!IsC11 && !IsN)
826 ByValType = Ptr->getType();
827
Eli Friedman276b0612011-10-11 02:20:01 +0000828 // The first argument --- the pointer --- has a fixed type; we
829 // deduce the types of the rest of the arguments accordingly. Walk
830 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +0000831 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +0000832 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +0000833 if (i < NumVals[Form] + 1) {
834 switch (i) {
835 case 1:
836 // The second argument is the non-atomic operand. For arithmetic, this
837 // is always passed by value, and for a compare_exchange it is always
838 // passed by address. For the rest, GNU uses by-address and C11 uses
839 // by-value.
840 assert(Form != Load);
841 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
842 Ty = ValType;
843 else if (Form == Copy || Form == Xchg)
844 Ty = ByValType;
845 else if (Form == Arithmetic)
846 Ty = Context.getPointerDiffType();
847 else
848 Ty = Context.getPointerType(ValType.getUnqualifiedType());
849 break;
850 case 2:
851 // The third argument to compare_exchange / GNU exchange is a
852 // (pointer to a) desired value.
853 Ty = ByValType;
854 break;
855 case 3:
856 // The fourth argument to GNU compare_exchange is a 'weak' flag.
857 Ty = Context.BoolTy;
858 break;
859 }
Eli Friedman276b0612011-10-11 02:20:01 +0000860 } else {
861 // The order(s) are always converted to int.
862 Ty = Context.IntTy;
863 }
Richard Smithff34d402012-04-12 05:08:17 +0000864
Eli Friedman276b0612011-10-11 02:20:01 +0000865 InitializedEntity Entity =
866 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +0000867 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +0000868 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
869 if (Arg.isInvalid())
870 return true;
871 TheCall->setArg(i, Arg.get());
872 }
873
Richard Smithff34d402012-04-12 05:08:17 +0000874 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000875 SmallVector<Expr*, 5> SubExprs;
876 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +0000877 switch (Form) {
878 case Init:
879 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +0000880 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000881 break;
882 case Load:
883 SubExprs.push_back(TheCall->getArg(1)); // Order
884 break;
885 case Copy:
886 case Arithmetic:
887 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000888 SubExprs.push_back(TheCall->getArg(2)); // Order
889 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000890 break;
891 case GNUXchg:
892 // Note, AtomicExpr::getVal2() has a special case for this atomic.
893 SubExprs.push_back(TheCall->getArg(3)); // Order
894 SubExprs.push_back(TheCall->getArg(1)); // Val1
895 SubExprs.push_back(TheCall->getArg(2)); // Val2
896 break;
897 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000898 SubExprs.push_back(TheCall->getArg(3)); // Order
899 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000900 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +0000901 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +0000902 break;
903 case GNUCmpXchg:
904 SubExprs.push_back(TheCall->getArg(4)); // Order
905 SubExprs.push_back(TheCall->getArg(1)); // Val1
906 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
907 SubExprs.push_back(TheCall->getArg(2)); // Val2
908 SubExprs.push_back(TheCall->getArg(3)); // Weak
909 break;
Eli Friedman276b0612011-10-11 02:20:01 +0000910 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000911
912 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +0000913 SubExprs, ResultType, Op,
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000914 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000915}
916
917
John McCall5f8d6042011-08-27 01:09:30 +0000918/// checkBuiltinArgument - Given a call to a builtin function, perform
919/// normal type-checking on the given argument, updating the call in
920/// place. This is useful when a builtin function requires custom
921/// type-checking for some of its arguments but not necessarily all of
922/// them.
923///
924/// Returns true on error.
925static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
926 FunctionDecl *Fn = E->getDirectCallee();
927 assert(Fn && "builtin call without direct callee!");
928
929 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
930 InitializedEntity Entity =
931 InitializedEntity::InitializeParameter(S.Context, Param);
932
933 ExprResult Arg = E->getArg(0);
934 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
935 if (Arg.isInvalid())
936 return true;
937
938 E->setArg(ArgIndex, Arg.take());
939 return false;
940}
941
Chris Lattner5caa3702009-05-08 06:58:22 +0000942/// SemaBuiltinAtomicOverloaded - We have a call to a function like
943/// __sync_fetch_and_add, which is an overloaded function based on the pointer
944/// type of its first argument. The main ActOnCallExpr routines have already
945/// promoted the types of arguments because all of these calls are prototyped as
946/// void(...).
947///
948/// This function goes through and does final semantic checking for these
949/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000950ExprResult
951Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000952 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000953 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
954 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
955
956 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000957 if (TheCall->getNumArgs() < 1) {
958 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
959 << 0 << 1 << TheCall->getNumArgs()
960 << TheCall->getCallee()->getSourceRange();
961 return ExprError();
962 }
Mike Stump1eb44332009-09-09 15:08:12 +0000963
Chris Lattner5caa3702009-05-08 06:58:22 +0000964 // Inspect the first argument of the atomic builtin. This should always be
965 // a pointer type, whose element is an integral scalar or pointer type.
966 // Because it is a pointer type, we don't have to worry about any implicit
967 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000968 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000969 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +0000970 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
971 if (FirstArgResult.isInvalid())
972 return ExprError();
973 FirstArg = FirstArgResult.take();
974 TheCall->setArg(0, FirstArg);
975
John McCallf85e1932011-06-15 23:02:42 +0000976 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
977 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000978 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
979 << FirstArg->getType() << FirstArg->getSourceRange();
980 return ExprError();
981 }
Mike Stump1eb44332009-09-09 15:08:12 +0000982
John McCallf85e1932011-06-15 23:02:42 +0000983 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000984 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000985 !ValType->isBlockPointerType()) {
986 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
987 << FirstArg->getType() << FirstArg->getSourceRange();
988 return ExprError();
989 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000990
John McCallf85e1932011-06-15 23:02:42 +0000991 switch (ValType.getObjCLifetime()) {
992 case Qualifiers::OCL_None:
993 case Qualifiers::OCL_ExplicitNone:
994 // okay
995 break;
996
997 case Qualifiers::OCL_Weak:
998 case Qualifiers::OCL_Strong:
999 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001000 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001001 << ValType << FirstArg->getSourceRange();
1002 return ExprError();
1003 }
1004
John McCallb45ae252011-10-05 07:41:44 +00001005 // Strip any qualifiers off ValType.
1006 ValType = ValType.getUnqualifiedType();
1007
Chandler Carruth8d13d222010-07-18 20:54:12 +00001008 // The majority of builtins return a value, but a few have special return
1009 // types, so allow them to override appropriately below.
1010 QualType ResultType = ValType;
1011
Chris Lattner5caa3702009-05-08 06:58:22 +00001012 // We need to figure out which concrete builtin this maps onto. For example,
1013 // __sync_fetch_and_add with a 2 byte object turns into
1014 // __sync_fetch_and_add_2.
1015#define BUILTIN_ROW(x) \
1016 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1017 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +00001018
Chris Lattner5caa3702009-05-08 06:58:22 +00001019 static const unsigned BuiltinIndices[][5] = {
1020 BUILTIN_ROW(__sync_fetch_and_add),
1021 BUILTIN_ROW(__sync_fetch_and_sub),
1022 BUILTIN_ROW(__sync_fetch_and_or),
1023 BUILTIN_ROW(__sync_fetch_and_and),
1024 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +00001025
Chris Lattner5caa3702009-05-08 06:58:22 +00001026 BUILTIN_ROW(__sync_add_and_fetch),
1027 BUILTIN_ROW(__sync_sub_and_fetch),
1028 BUILTIN_ROW(__sync_and_and_fetch),
1029 BUILTIN_ROW(__sync_or_and_fetch),
1030 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001031
Chris Lattner5caa3702009-05-08 06:58:22 +00001032 BUILTIN_ROW(__sync_val_compare_and_swap),
1033 BUILTIN_ROW(__sync_bool_compare_and_swap),
1034 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001035 BUILTIN_ROW(__sync_lock_release),
1036 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001037 };
Mike Stump1eb44332009-09-09 15:08:12 +00001038#undef BUILTIN_ROW
1039
Chris Lattner5caa3702009-05-08 06:58:22 +00001040 // Determine the index of the size.
1041 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001042 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001043 case 1: SizeIndex = 0; break;
1044 case 2: SizeIndex = 1; break;
1045 case 4: SizeIndex = 2; break;
1046 case 8: SizeIndex = 3; break;
1047 case 16: SizeIndex = 4; break;
1048 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001049 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1050 << FirstArg->getType() << FirstArg->getSourceRange();
1051 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001052 }
Mike Stump1eb44332009-09-09 15:08:12 +00001053
Chris Lattner5caa3702009-05-08 06:58:22 +00001054 // Each of these builtins has one pointer argument, followed by some number of
1055 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1056 // that we ignore. Find out which row of BuiltinIndices to read from as well
1057 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001058 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001059 unsigned BuiltinIndex, NumFixed = 1;
1060 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001061 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001062 case Builtin::BI__sync_fetch_and_add:
1063 case Builtin::BI__sync_fetch_and_add_1:
1064 case Builtin::BI__sync_fetch_and_add_2:
1065 case Builtin::BI__sync_fetch_and_add_4:
1066 case Builtin::BI__sync_fetch_and_add_8:
1067 case Builtin::BI__sync_fetch_and_add_16:
1068 BuiltinIndex = 0;
1069 break;
1070
1071 case Builtin::BI__sync_fetch_and_sub:
1072 case Builtin::BI__sync_fetch_and_sub_1:
1073 case Builtin::BI__sync_fetch_and_sub_2:
1074 case Builtin::BI__sync_fetch_and_sub_4:
1075 case Builtin::BI__sync_fetch_and_sub_8:
1076 case Builtin::BI__sync_fetch_and_sub_16:
1077 BuiltinIndex = 1;
1078 break;
1079
1080 case Builtin::BI__sync_fetch_and_or:
1081 case Builtin::BI__sync_fetch_and_or_1:
1082 case Builtin::BI__sync_fetch_and_or_2:
1083 case Builtin::BI__sync_fetch_and_or_4:
1084 case Builtin::BI__sync_fetch_and_or_8:
1085 case Builtin::BI__sync_fetch_and_or_16:
1086 BuiltinIndex = 2;
1087 break;
1088
1089 case Builtin::BI__sync_fetch_and_and:
1090 case Builtin::BI__sync_fetch_and_and_1:
1091 case Builtin::BI__sync_fetch_and_and_2:
1092 case Builtin::BI__sync_fetch_and_and_4:
1093 case Builtin::BI__sync_fetch_and_and_8:
1094 case Builtin::BI__sync_fetch_and_and_16:
1095 BuiltinIndex = 3;
1096 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Douglas Gregora9766412011-11-28 16:30:08 +00001098 case Builtin::BI__sync_fetch_and_xor:
1099 case Builtin::BI__sync_fetch_and_xor_1:
1100 case Builtin::BI__sync_fetch_and_xor_2:
1101 case Builtin::BI__sync_fetch_and_xor_4:
1102 case Builtin::BI__sync_fetch_and_xor_8:
1103 case Builtin::BI__sync_fetch_and_xor_16:
1104 BuiltinIndex = 4;
1105 break;
1106
1107 case Builtin::BI__sync_add_and_fetch:
1108 case Builtin::BI__sync_add_and_fetch_1:
1109 case Builtin::BI__sync_add_and_fetch_2:
1110 case Builtin::BI__sync_add_and_fetch_4:
1111 case Builtin::BI__sync_add_and_fetch_8:
1112 case Builtin::BI__sync_add_and_fetch_16:
1113 BuiltinIndex = 5;
1114 break;
1115
1116 case Builtin::BI__sync_sub_and_fetch:
1117 case Builtin::BI__sync_sub_and_fetch_1:
1118 case Builtin::BI__sync_sub_and_fetch_2:
1119 case Builtin::BI__sync_sub_and_fetch_4:
1120 case Builtin::BI__sync_sub_and_fetch_8:
1121 case Builtin::BI__sync_sub_and_fetch_16:
1122 BuiltinIndex = 6;
1123 break;
1124
1125 case Builtin::BI__sync_and_and_fetch:
1126 case Builtin::BI__sync_and_and_fetch_1:
1127 case Builtin::BI__sync_and_and_fetch_2:
1128 case Builtin::BI__sync_and_and_fetch_4:
1129 case Builtin::BI__sync_and_and_fetch_8:
1130 case Builtin::BI__sync_and_and_fetch_16:
1131 BuiltinIndex = 7;
1132 break;
1133
1134 case Builtin::BI__sync_or_and_fetch:
1135 case Builtin::BI__sync_or_and_fetch_1:
1136 case Builtin::BI__sync_or_and_fetch_2:
1137 case Builtin::BI__sync_or_and_fetch_4:
1138 case Builtin::BI__sync_or_and_fetch_8:
1139 case Builtin::BI__sync_or_and_fetch_16:
1140 BuiltinIndex = 8;
1141 break;
1142
1143 case Builtin::BI__sync_xor_and_fetch:
1144 case Builtin::BI__sync_xor_and_fetch_1:
1145 case Builtin::BI__sync_xor_and_fetch_2:
1146 case Builtin::BI__sync_xor_and_fetch_4:
1147 case Builtin::BI__sync_xor_and_fetch_8:
1148 case Builtin::BI__sync_xor_and_fetch_16:
1149 BuiltinIndex = 9;
1150 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001151
Chris Lattner5caa3702009-05-08 06:58:22 +00001152 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001153 case Builtin::BI__sync_val_compare_and_swap_1:
1154 case Builtin::BI__sync_val_compare_and_swap_2:
1155 case Builtin::BI__sync_val_compare_and_swap_4:
1156 case Builtin::BI__sync_val_compare_and_swap_8:
1157 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001158 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001159 NumFixed = 2;
1160 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001161
Chris Lattner5caa3702009-05-08 06:58:22 +00001162 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001163 case Builtin::BI__sync_bool_compare_and_swap_1:
1164 case Builtin::BI__sync_bool_compare_and_swap_2:
1165 case Builtin::BI__sync_bool_compare_and_swap_4:
1166 case Builtin::BI__sync_bool_compare_and_swap_8:
1167 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001168 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001169 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001170 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001171 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001172
1173 case Builtin::BI__sync_lock_test_and_set:
1174 case Builtin::BI__sync_lock_test_and_set_1:
1175 case Builtin::BI__sync_lock_test_and_set_2:
1176 case Builtin::BI__sync_lock_test_and_set_4:
1177 case Builtin::BI__sync_lock_test_and_set_8:
1178 case Builtin::BI__sync_lock_test_and_set_16:
1179 BuiltinIndex = 12;
1180 break;
1181
Chris Lattner5caa3702009-05-08 06:58:22 +00001182 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001183 case Builtin::BI__sync_lock_release_1:
1184 case Builtin::BI__sync_lock_release_2:
1185 case Builtin::BI__sync_lock_release_4:
1186 case Builtin::BI__sync_lock_release_8:
1187 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001188 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001189 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001190 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001191 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001192
1193 case Builtin::BI__sync_swap:
1194 case Builtin::BI__sync_swap_1:
1195 case Builtin::BI__sync_swap_2:
1196 case Builtin::BI__sync_swap_4:
1197 case Builtin::BI__sync_swap_8:
1198 case Builtin::BI__sync_swap_16:
1199 BuiltinIndex = 14;
1200 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001201 }
Mike Stump1eb44332009-09-09 15:08:12 +00001202
Chris Lattner5caa3702009-05-08 06:58:22 +00001203 // Now that we know how many fixed arguments we expect, first check that we
1204 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001205 if (TheCall->getNumArgs() < 1+NumFixed) {
1206 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1207 << 0 << 1+NumFixed << TheCall->getNumArgs()
1208 << TheCall->getCallee()->getSourceRange();
1209 return ExprError();
1210 }
Mike Stump1eb44332009-09-09 15:08:12 +00001211
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001212 // Get the decl for the concrete builtin from this, we can tell what the
1213 // concrete integer type we should convert to is.
1214 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1215 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001216 FunctionDecl *NewBuiltinDecl;
1217 if (NewBuiltinID == BuiltinID)
1218 NewBuiltinDecl = FDecl;
1219 else {
1220 // Perform builtin lookup to avoid redeclaring it.
1221 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1222 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1223 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1224 assert(Res.getFoundDecl());
1225 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1226 if (NewBuiltinDecl == 0)
1227 return ExprError();
1228 }
Chandler Carruthd2014572010-07-09 18:59:35 +00001229
John McCallf871d0c2010-08-07 06:22:56 +00001230 // The first argument --- the pointer --- has a fixed type; we
1231 // deduce the types of the rest of the arguments accordingly. Walk
1232 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001233 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001234 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Chris Lattner5caa3702009-05-08 06:58:22 +00001236 // GCC does an implicit conversion to the pointer or integer ValType. This
1237 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001238 // Initialize the argument.
1239 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1240 ValType, /*consume*/ false);
1241 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001242 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001243 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Chris Lattner5caa3702009-05-08 06:58:22 +00001245 // Okay, we have something that *can* be converted to the right type. Check
1246 // to see if there is a potentially weird extension going on here. This can
1247 // happen when you do an atomic operation on something like an char* and
1248 // pass in 42. The 42 gets converted to char. This is even more strange
1249 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001250 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001251 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001252 }
Mike Stump1eb44332009-09-09 15:08:12 +00001253
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001254 ASTContext& Context = this->getASTContext();
1255
1256 // Create a new DeclRefExpr to refer to the new decl.
1257 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1258 Context,
1259 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001260 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001261 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001262 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001263 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001264 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001265 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001266
Chris Lattner5caa3702009-05-08 06:58:22 +00001267 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001268 // FIXME: This loses syntactic information.
1269 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1270 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1271 CK_BuiltinFnToFnPtr);
John Wiegley429bb272011-04-08 18:41:53 +00001272 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001273
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001274 // Change the result type of the call to match the original value type. This
1275 // is arbitrary, but the codegen for these builtins ins design to handle it
1276 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001277 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001278
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001279 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001280}
1281
Chris Lattner69039812009-02-18 06:01:06 +00001282/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001283/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001284/// Note: It might also make sense to do the UTF-16 conversion here (would
1285/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001286bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001287 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001288 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1289
Douglas Gregor5cee1192011-07-27 05:40:30 +00001290 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001291 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1292 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001293 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001294 }
Mike Stump1eb44332009-09-09 15:08:12 +00001295
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001296 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001297 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001298 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001299 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00001300 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001301 UTF16 *ToPtr = &ToBuf[0];
1302
1303 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1304 &ToPtr, ToPtr + NumBytes,
1305 strictConversion);
1306 // Check for conversion failure.
1307 if (Result != conversionOK)
1308 Diag(Arg->getLocStart(),
1309 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1310 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001311 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001312}
1313
Chris Lattnerc27c6652007-12-20 00:05:45 +00001314/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1315/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001316bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1317 Expr *Fn = TheCall->getCallee();
1318 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001319 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001320 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001321 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1322 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001323 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001324 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001325 return true;
1326 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001327
1328 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001329 return Diag(TheCall->getLocEnd(),
1330 diag::err_typecheck_call_too_few_args_at_least)
1331 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001332 }
1333
John McCall5f8d6042011-08-27 01:09:30 +00001334 // Type-check the first argument normally.
1335 if (checkBuiltinArgument(*this, TheCall, 0))
1336 return true;
1337
Chris Lattnerc27c6652007-12-20 00:05:45 +00001338 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001339 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001340 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001341 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001342 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001343 else if (FunctionDecl *FD = getCurFunctionDecl())
1344 isVariadic = FD->isVariadic();
1345 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001346 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001347
Chris Lattnerc27c6652007-12-20 00:05:45 +00001348 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001349 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1350 return true;
1351 }
Mike Stump1eb44332009-09-09 15:08:12 +00001352
Chris Lattner30ce3442007-12-19 23:59:04 +00001353 // Verify that the second argument to the builtin is the last argument of the
1354 // current function or method.
1355 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001356 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001357
Nico Weberb07d4482013-05-24 23:31:57 +00001358 // These are valid if SecondArgIsLastNamedArgument is false after the next
1359 // block.
1360 QualType Type;
1361 SourceLocation ParamLoc;
1362
Anders Carlsson88cf2262008-02-11 04:20:54 +00001363 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1364 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001365 // FIXME: This isn't correct for methods (results in bogus warning).
1366 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001367 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001368 if (CurBlock)
1369 LastArg = *(CurBlock->TheDecl->param_end()-1);
1370 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001371 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001372 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001373 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001374 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weberb07d4482013-05-24 23:31:57 +00001375
1376 Type = PV->getType();
1377 ParamLoc = PV->getLocation();
Chris Lattner30ce3442007-12-19 23:59:04 +00001378 }
1379 }
Mike Stump1eb44332009-09-09 15:08:12 +00001380
Chris Lattner30ce3442007-12-19 23:59:04 +00001381 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001382 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001383 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weberb07d4482013-05-24 23:31:57 +00001384 else if (Type->isReferenceType()) {
1385 Diag(Arg->getLocStart(),
1386 diag::warn_va_start_of_reference_type_is_undefined);
1387 Diag(ParamLoc, diag::note_parameter_type) << Type;
1388 }
1389
Chris Lattner30ce3442007-12-19 23:59:04 +00001390 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001391}
Chris Lattner30ce3442007-12-19 23:59:04 +00001392
Chris Lattner1b9a0792007-12-20 00:26:33 +00001393/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1394/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001395bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1396 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001397 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001398 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001399 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001400 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001401 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001402 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001403 << SourceRange(TheCall->getArg(2)->getLocStart(),
1404 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001405
John Wiegley429bb272011-04-08 18:41:53 +00001406 ExprResult OrigArg0 = TheCall->getArg(0);
1407 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001408
Chris Lattner1b9a0792007-12-20 00:26:33 +00001409 // Do standard promotions between the two arguments, returning their common
1410 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001411 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001412 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1413 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001414
1415 // Make sure any conversions are pushed back into the call; this is
1416 // type safe since unordered compare builtins are declared as "_Bool
1417 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001418 TheCall->setArg(0, OrigArg0.get());
1419 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001420
John Wiegley429bb272011-04-08 18:41:53 +00001421 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001422 return false;
1423
Chris Lattner1b9a0792007-12-20 00:26:33 +00001424 // If the common type isn't a real floating type, then the arguments were
1425 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001426 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001427 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001428 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001429 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1430 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001431
Chris Lattner1b9a0792007-12-20 00:26:33 +00001432 return false;
1433}
1434
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001435/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1436/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001437/// to check everything. We expect the last argument to be a floating point
1438/// value.
1439bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1440 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001441 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001442 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001443 if (TheCall->getNumArgs() > NumArgs)
1444 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001445 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001446 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001447 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001448 (*(TheCall->arg_end()-1))->getLocEnd());
1449
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001450 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001451
Eli Friedman9ac6f622009-08-31 20:06:00 +00001452 if (OrigArg->isTypeDependent())
1453 return false;
1454
Chris Lattner81368fb2010-05-06 05:50:07 +00001455 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001456 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001457 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001458 diag::err_typecheck_call_invalid_unary_fp)
1459 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001460
Chris Lattner81368fb2010-05-06 05:50:07 +00001461 // If this is an implicit conversion from float -> double, remove it.
1462 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1463 Expr *CastArg = Cast->getSubExpr();
1464 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1465 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1466 "promotion from float to double is the only expected cast here");
1467 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001468 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001469 }
1470 }
1471
Eli Friedman9ac6f622009-08-31 20:06:00 +00001472 return false;
1473}
1474
Eli Friedmand38617c2008-05-14 19:38:39 +00001475/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1476// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001477ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001478 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001479 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001480 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001481 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001482 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001483
Nate Begeman37b6a572010-06-08 00:16:34 +00001484 // Determine which of the following types of shufflevector we're checking:
1485 // 1) unary, vector mask: (lhs, mask)
1486 // 2) binary, vector mask: (lhs, rhs, mask)
1487 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1488 QualType resType = TheCall->getArg(0)->getType();
1489 unsigned numElements = 0;
1490
Douglas Gregorcde01732009-05-19 22:10:17 +00001491 if (!TheCall->getArg(0)->isTypeDependent() &&
1492 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001493 QualType LHSType = TheCall->getArg(0)->getType();
1494 QualType RHSType = TheCall->getArg(1)->getType();
1495
1496 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001497 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001498 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001499 TheCall->getArg(1)->getLocEnd());
1500 return ExprError();
1501 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001502
1503 numElements = LHSType->getAs<VectorType>()->getNumElements();
1504 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001505
Nate Begeman37b6a572010-06-08 00:16:34 +00001506 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1507 // with mask. If so, verify that RHS is an integer vector type with the
1508 // same number of elts as lhs.
1509 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001510 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001511 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1512 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1513 << SourceRange(TheCall->getArg(1)->getLocStart(),
1514 TheCall->getArg(1)->getLocEnd());
1515 numResElements = numElements;
1516 }
1517 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001518 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001519 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001520 TheCall->getArg(1)->getLocEnd());
1521 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001522 } else if (numElements != numResElements) {
1523 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001524 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001525 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001526 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001527 }
1528
1529 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001530 if (TheCall->getArg(i)->isTypeDependent() ||
1531 TheCall->getArg(i)->isValueDependent())
1532 continue;
1533
Nate Begeman37b6a572010-06-08 00:16:34 +00001534 llvm::APSInt Result(32);
1535 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1536 return ExprError(Diag(TheCall->getLocStart(),
1537 diag::err_shufflevector_nonconstant_argument)
1538 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001539
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001540 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001541 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001542 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001543 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001544 }
1545
Chris Lattner5f9e2722011-07-23 10:55:15 +00001546 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001547
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001548 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001549 exprs.push_back(TheCall->getArg(i));
1550 TheCall->setArg(i, 0);
1551 }
1552
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001553 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001554 TheCall->getCallee()->getLocStart(),
1555 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001556}
Chris Lattner30ce3442007-12-19 23:59:04 +00001557
Daniel Dunbar4493f792008-07-21 22:59:13 +00001558/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1559// This is declared to take (const void*, ...) and can take two
1560// optional constant int args.
1561bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001562 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001563
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001564 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001565 return Diag(TheCall->getLocEnd(),
1566 diag::err_typecheck_call_too_many_args_at_most)
1567 << 0 /*function call*/ << 3 << NumArgs
1568 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001569
1570 // Argument 0 is checked for us and the remaining arguments must be
1571 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001572 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001573 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001574
1575 // We can't check the value of a dependent argument.
1576 if (Arg->isTypeDependent() || Arg->isValueDependent())
1577 continue;
1578
Eli Friedman9aef7262009-12-04 00:30:06 +00001579 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001580 if (SemaBuiltinConstantArg(TheCall, i, Result))
1581 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001582
Daniel Dunbar4493f792008-07-21 22:59:13 +00001583 // FIXME: gcc issues a warning and rewrites these to 0. These
1584 // seems especially odd for the third argument since the default
1585 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001586 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001587 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001588 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001589 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001590 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001591 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001592 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001593 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001594 }
1595 }
1596
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001597 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001598}
1599
Eric Christopher691ebc32010-04-17 02:26:23 +00001600/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1601/// TheCall is a constant expression.
1602bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1603 llvm::APSInt &Result) {
1604 Expr *Arg = TheCall->getArg(ArgNum);
1605 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1606 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1607
1608 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1609
1610 if (!Arg->isIntegerConstantExpr(Result, Context))
1611 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001612 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001613
Chris Lattner21fb98e2009-09-23 06:06:36 +00001614 return false;
1615}
1616
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001617/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1618/// int type). This simply type checks that type is one of the defined
1619/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001620// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001621bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001622 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001623
1624 // We can't check the value of a dependent argument.
1625 if (TheCall->getArg(1)->isTypeDependent() ||
1626 TheCall->getArg(1)->isValueDependent())
1627 return false;
1628
Eric Christopher691ebc32010-04-17 02:26:23 +00001629 // Check constant-ness first.
1630 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1631 return true;
1632
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001633 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001634 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001635 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1636 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001637 }
1638
1639 return false;
1640}
1641
Eli Friedman586d6a82009-05-03 06:04:26 +00001642/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001643/// This checks that val is a constant 1.
1644bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1645 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001646 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001647
Eric Christopher691ebc32010-04-17 02:26:23 +00001648 // TODO: This is less than ideal. Overload this to take a value.
1649 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1650 return true;
1651
1652 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001653 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1654 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1655
1656 return false;
1657}
1658
Richard Smith831421f2012-06-25 20:30:08 +00001659// Determine if an expression is a string literal or constant string.
1660// If this function returns false on the arguments to a function expecting a
1661// format string, we will usually need to emit a warning.
1662// True string literals are then checked by CheckFormatString.
1663Sema::StringLiteralCheckType
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001664Sema::checkFormatStringExpr(const Expr *E, ArrayRef<const Expr *> Args,
1665 bool HasVAListArg,
Richard Smith831421f2012-06-25 20:30:08 +00001666 unsigned format_idx, unsigned firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001667 FormatStringType Type, VariadicCallType CallType,
1668 bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001669 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001670 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001671 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001672
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001673 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001674
David Blaikiea73cdcb2012-02-10 21:07:25 +00001675 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1676 // Technically -Wformat-nonliteral does not warn about this case.
1677 // The behavior of printf and friends in this case is implementation
1678 // dependent. Ideally if the format string cannot be null then
1679 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith831421f2012-06-25 20:30:08 +00001680 return SLCT_CheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001681
Ted Kremenekd30ef872009-01-12 23:09:09 +00001682 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001683 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001684 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001685 // The expression is a literal if both sub-expressions were, and it was
1686 // completely checked only if both sub-expressions were checked.
1687 const AbstractConditionalOperator *C =
1688 cast<AbstractConditionalOperator>(E);
1689 StringLiteralCheckType Left =
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001690 checkFormatStringExpr(C->getTrueExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001691 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001692 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001693 if (Left == SLCT_NotALiteral)
1694 return SLCT_NotALiteral;
1695 StringLiteralCheckType Right =
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001696 checkFormatStringExpr(C->getFalseExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001697 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001698 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001699 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001700 }
1701
1702 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001703 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1704 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001705 }
1706
John McCall56ca35d2011-02-17 10:25:35 +00001707 case Stmt::OpaqueValueExprClass:
1708 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1709 E = src;
1710 goto tryAgain;
1711 }
Richard Smith831421f2012-06-25 20:30:08 +00001712 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00001713
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001714 case Stmt::PredefinedExprClass:
1715 // While __func__, etc., are technically not string literals, they
1716 // cannot contain format specifiers and thus are not a security
1717 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00001718 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001719
Ted Kremenek082d9362009-03-20 21:35:28 +00001720 case Stmt::DeclRefExprClass: {
1721 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001722
Ted Kremenek082d9362009-03-20 21:35:28 +00001723 // As an exception, do not flag errors for variables binding to
1724 // const string literals.
1725 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1726 bool isConstant = false;
1727 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001728
Ted Kremenek082d9362009-03-20 21:35:28 +00001729 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1730 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001731 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001732 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001733 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001734 } else if (T->isObjCObjectPointerType()) {
1735 // In ObjC, there is usually no "const ObjectPointer" type,
1736 // so don't check if the pointee type is constant.
1737 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001738 }
Mike Stump1eb44332009-09-09 15:08:12 +00001739
Ted Kremenek082d9362009-03-20 21:35:28 +00001740 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001741 if (const Expr *Init = VD->getAnyInitializer()) {
1742 // Look through initializers like const char c[] = { "foo" }
1743 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
1744 if (InitList->isStringLiteralInit())
1745 Init = InitList->getInit(0)->IgnoreParenImpCasts();
1746 }
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001747 return checkFormatStringExpr(Init, Args,
Richard Smith831421f2012-06-25 20:30:08 +00001748 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001749 firstDataArg, Type, CallType,
Richard Smith831421f2012-06-25 20:30:08 +00001750 /*inFunctionCall*/false);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001751 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001752 }
Mike Stump1eb44332009-09-09 15:08:12 +00001753
Anders Carlssond966a552009-06-28 19:55:58 +00001754 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1755 // special check to see if the format string is a function parameter
1756 // of the function calling the printf function. If the function
1757 // has an attribute indicating it is a printf-like function, then we
1758 // should suppress warnings concerning non-literals being used in a call
1759 // to a vprintf function. For example:
1760 //
1761 // void
1762 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1763 // va_list ap;
1764 // va_start(ap, fmt);
1765 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1766 // ...
1767 //
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001768 if (HasVAListArg) {
1769 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1770 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1771 int PVIndex = PV->getFunctionScopeIndex() + 1;
1772 for (specific_attr_iterator<FormatAttr>
1773 i = ND->specific_attr_begin<FormatAttr>(),
1774 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1775 FormatAttr *PVFormat = *i;
1776 // adjust for implicit parameter
1777 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1778 if (MD->isInstance())
1779 ++PVIndex;
1780 // We also check if the formats are compatible.
1781 // We can't pass a 'scanf' string to a 'printf' function.
1782 if (PVIndex == PVFormat->getFormatIdx() &&
1783 Type == GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00001784 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001785 }
1786 }
1787 }
1788 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001789 }
Mike Stump1eb44332009-09-09 15:08:12 +00001790
Richard Smith831421f2012-06-25 20:30:08 +00001791 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00001792 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001793
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001794 case Stmt::CallExprClass:
1795 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001796 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001797 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1798 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1799 unsigned ArgIndex = FA->getFormatIdx();
1800 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1801 if (MD->isInstance())
1802 --ArgIndex;
1803 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001804
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001805 return checkFormatStringExpr(Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00001806 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001807 Type, CallType, inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001808 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1809 unsigned BuiltinID = FD->getBuiltinID();
1810 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
1811 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
1812 const Expr *Arg = CE->getArg(0);
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001813 return checkFormatStringExpr(Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00001814 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001815 firstDataArg, Type, CallType,
1816 inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001817 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00001818 }
1819 }
Mike Stump1eb44332009-09-09 15:08:12 +00001820
Richard Smith831421f2012-06-25 20:30:08 +00001821 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00001822 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001823 case Stmt::ObjCStringLiteralClass:
1824 case Stmt::StringLiteralClass: {
1825 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001826
Ted Kremenek082d9362009-03-20 21:35:28 +00001827 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001828 StrE = ObjCFExpr->getString();
1829 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001830 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Ted Kremenekd30ef872009-01-12 23:09:09 +00001832 if (StrE) {
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001833 CheckFormatString(StrE, E, Args, HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001834 firstDataArg, Type, inFunctionCall, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001835 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001836 }
Mike Stump1eb44332009-09-09 15:08:12 +00001837
Richard Smith831421f2012-06-25 20:30:08 +00001838 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001839 }
Mike Stump1eb44332009-09-09 15:08:12 +00001840
Ted Kremenek082d9362009-03-20 21:35:28 +00001841 default:
Richard Smith831421f2012-06-25 20:30:08 +00001842 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001843 }
1844}
1845
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001846void
Mike Stump1eb44332009-09-09 15:08:12 +00001847Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001848 const Expr * const *ExprArgs,
1849 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001850 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1851 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001852 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001853 const Expr *ArgExpr = ExprArgs[*i];
Nick Lewycky3edf3872013-01-23 05:08:29 +00001854
1855 // As a special case, transparent unions initialized with zero are
1856 // considered null for the purposes of the nonnull attribute.
1857 if (const RecordType *UT = ArgExpr->getType()->getAsUnionType()) {
1858 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1859 if (const CompoundLiteralExpr *CLE =
1860 dyn_cast<CompoundLiteralExpr>(ArgExpr))
1861 if (const InitListExpr *ILE =
1862 dyn_cast<InitListExpr>(CLE->getInitializer()))
1863 ArgExpr = ILE->getInit(0);
1864 }
1865
1866 bool Result;
1867 if (ArgExpr->EvaluateAsBooleanCondition(Result, Context) && !Result)
Nick Lewycky909a70d2011-03-25 01:44:32 +00001868 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001869 }
1870}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001871
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001872Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1873 return llvm::StringSwitch<FormatStringType>(Format->getType())
1874 .Case("scanf", FST_Scanf)
1875 .Cases("printf", "printf0", FST_Printf)
1876 .Cases("NSString", "CFString", FST_NSString)
1877 .Case("strftime", FST_Strftime)
1878 .Case("strfmon", FST_Strfmon)
1879 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1880 .Default(FST_Unknown);
1881}
1882
Jordan Roseddcfbc92012-07-19 18:10:23 +00001883/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00001884/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00001885/// Returns true if a format string has been fully checked.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001886bool Sema::CheckFormatArguments(const FormatAttr *Format,
1887 ArrayRef<const Expr *> Args,
1888 bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001889 VariadicCallType CallType,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001890 SourceLocation Loc, SourceRange Range) {
Richard Smith831421f2012-06-25 20:30:08 +00001891 FormatStringInfo FSI;
1892 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001893 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith831421f2012-06-25 20:30:08 +00001894 FSI.FirstDataArg, GetFormatStringType(Format),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001895 CallType, Loc, Range);
Richard Smith831421f2012-06-25 20:30:08 +00001896 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001897}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001898
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001899bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001900 bool HasVAListArg, unsigned format_idx,
1901 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001902 VariadicCallType CallType,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001903 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001904 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001905 if (format_idx >= Args.size()) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001906 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00001907 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00001908 }
Mike Stump1eb44332009-09-09 15:08:12 +00001909
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001910 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001911
Chris Lattner59907c42007-08-10 20:18:51 +00001912 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001913 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001914 // Dynamically generated format strings are difficult to
1915 // automatically vet at compile time. Requiring that format strings
1916 // are string literals: (1) permits the checking of format strings by
1917 // the compiler and thereby (2) can practically remove the source of
1918 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001919
Mike Stump1eb44332009-09-09 15:08:12 +00001920 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001921 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001922 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001923 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00001924 StringLiteralCheckType CT =
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001925 checkFormatStringExpr(OrigFormatExpr, Args, HasVAListArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001926 format_idx, firstDataArg, Type, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001927 if (CT != SLCT_NotALiteral)
1928 // Literal format string found, check done!
1929 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001930
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001931 // Strftime is particular as it always uses a single 'time' argument,
1932 // so it is safe to pass a non-literal string.
1933 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00001934 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001935
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001936 // Do not emit diag when the string param is a macro expansion and the
1937 // format is either NSString or CFString. This is a hack to prevent
1938 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1939 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00001940 if (Type == FST_NSString &&
1941 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00001942 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001943
Chris Lattner655f1412009-04-29 04:59:47 +00001944 // If there are no arguments specified, warn with -Wformat-security, otherwise
1945 // warn only with -Wformat-nonliteral.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001946 if (Args.size() == format_idx+1)
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001947 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001948 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001949 << OrigFormatExpr->getSourceRange();
1950 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001951 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001952 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001953 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00001954 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001955}
Ted Kremenek71895b92007-08-14 17:39:48 +00001956
Ted Kremeneke0e53132010-01-28 23:39:18 +00001957namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001958class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1959protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001960 Sema &S;
1961 const StringLiteral *FExpr;
1962 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001963 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001964 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001965 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001966 const bool HasVAListArg;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001967 ArrayRef<const Expr *> Args;
Ted Kremenek0d277352010-01-29 01:06:55 +00001968 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001969 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001970 bool usesPositionalArgs;
1971 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001972 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00001973 Sema::VariadicCallType CallType;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001974public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001975 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001976 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00001977 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001978 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001979 unsigned formatIdx, bool inFunctionCall,
1980 Sema::VariadicCallType callType)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001981 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00001982 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
1983 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001984 Args(Args), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001985 usesPositionalArgs(false), atFirstArg(true),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001986 inFunctionCall(inFunctionCall), CallType(callType) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001987 CoveredArgs.resize(numDataArgs);
1988 CoveredArgs.reset();
1989 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001990
Ted Kremenek07d161f2010-01-29 01:50:07 +00001991 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001992
Ted Kremenek826a3452010-07-16 02:11:22 +00001993 void HandleIncompleteSpecifier(const char *startSpecifier,
1994 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00001995
Jordan Rosebbb6bb42012-09-08 04:00:03 +00001996 void HandleInvalidLengthModifier(
1997 const analyze_format_string::FormatSpecifier &FS,
1998 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00001999 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002000
Hans Wennborg76517422012-02-22 10:17:01 +00002001 void HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002002 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002003 const char *startSpecifier, unsigned specifierLen);
2004
2005 void HandleNonStandardConversionSpecifier(
2006 const analyze_format_string::ConversionSpecifier &CS,
2007 const char *startSpecifier, unsigned specifierLen);
2008
Hans Wennborgf8562642012-03-09 10:10:54 +00002009 virtual void HandlePosition(const char *startPos, unsigned posLen);
2010
Ted Kremenekefaff192010-02-27 01:41:03 +00002011 virtual void HandleInvalidPosition(const char *startSpecifier,
2012 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00002013 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00002014
2015 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2016
Ted Kremeneke0e53132010-01-28 23:39:18 +00002017 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002018
Richard Trieu55733de2011-10-28 00:41:25 +00002019 template <typename Range>
2020 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2021 const Expr *ArgumentExpr,
2022 PartialDiagnostic PDiag,
2023 SourceLocation StringLoc,
2024 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002025 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002026
Ted Kremenek826a3452010-07-16 02:11:22 +00002027protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002028 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2029 const char *startSpec,
2030 unsigned specifierLen,
2031 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00002032
2033 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2034 const char *startSpec,
2035 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002036
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002037 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00002038 CharSourceRange getSpecifierRange(const char *startSpecifier,
2039 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002040 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002041
Ted Kremenek0d277352010-01-29 01:06:55 +00002042 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00002043
2044 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2045 const analyze_format_string::ConversionSpecifier &CS,
2046 const char *startSpecifier, unsigned specifierLen,
2047 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00002048
2049 template <typename Range>
2050 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2051 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002052 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002053
2054 void CheckPositionalAndNonpositionalArgs(
2055 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002056};
2057}
2058
Ted Kremenek826a3452010-07-16 02:11:22 +00002059SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002060 return OrigFormatExpr->getSourceRange();
2061}
2062
Ted Kremenek826a3452010-07-16 02:11:22 +00002063CharSourceRange CheckFormatHandler::
2064getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002065 SourceLocation Start = getLocationOfByte(startSpecifier);
2066 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2067
2068 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002069 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002070
2071 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002072}
2073
Ted Kremenek826a3452010-07-16 02:11:22 +00002074SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002075 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002076}
2077
Ted Kremenek826a3452010-07-16 02:11:22 +00002078void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2079 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002080 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2081 getLocationOfByte(startSpecifier),
2082 /*IsStringLocation*/true,
2083 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002084}
2085
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002086void CheckFormatHandler::HandleInvalidLengthModifier(
2087 const analyze_format_string::FormatSpecifier &FS,
2088 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002089 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002090 using namespace analyze_format_string;
2091
2092 const LengthModifier &LM = FS.getLengthModifier();
2093 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2094
2095 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002096 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002097 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002098 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002099 getLocationOfByte(LM.getStart()),
2100 /*IsStringLocation*/true,
2101 getSpecifierRange(startSpecifier, specifierLen));
2102
2103 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2104 << FixedLM->toString()
2105 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2106
2107 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00002108 FixItHint Hint;
2109 if (DiagID == diag::warn_format_nonsensical_length)
2110 Hint = FixItHint::CreateRemoval(LMRange);
2111
2112 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002113 getLocationOfByte(LM.getStart()),
2114 /*IsStringLocation*/true,
2115 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002116 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002117 }
2118}
2119
Hans Wennborg76517422012-02-22 10:17:01 +00002120void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002121 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002122 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002123 using namespace analyze_format_string;
2124
2125 const LengthModifier &LM = FS.getLengthModifier();
2126 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2127
2128 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002129 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose8be066e2012-09-08 04:00:12 +00002130 if (FixedLM) {
2131 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2132 << LM.toString() << 0,
2133 getLocationOfByte(LM.getStart()),
2134 /*IsStringLocation*/true,
2135 getSpecifierRange(startSpecifier, specifierLen));
2136
2137 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2138 << FixedLM->toString()
2139 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2140
2141 } else {
2142 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2143 << LM.toString() << 0,
2144 getLocationOfByte(LM.getStart()),
2145 /*IsStringLocation*/true,
2146 getSpecifierRange(startSpecifier, specifierLen));
2147 }
Hans Wennborg76517422012-02-22 10:17:01 +00002148}
2149
2150void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2151 const analyze_format_string::ConversionSpecifier &CS,
2152 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002153 using namespace analyze_format_string;
2154
2155 // See if we know how to fix this conversion specifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002156 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose670941c2012-09-13 02:11:15 +00002157 if (FixedCS) {
2158 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2159 << CS.toString() << /*conversion specifier*/1,
2160 getLocationOfByte(CS.getStart()),
2161 /*IsStringLocation*/true,
2162 getSpecifierRange(startSpecifier, specifierLen));
2163
2164 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2165 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2166 << FixedCS->toString()
2167 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2168 } else {
2169 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2170 << CS.toString() << /*conversion specifier*/1,
2171 getLocationOfByte(CS.getStart()),
2172 /*IsStringLocation*/true,
2173 getSpecifierRange(startSpecifier, specifierLen));
2174 }
Hans Wennborg76517422012-02-22 10:17:01 +00002175}
2176
Hans Wennborgf8562642012-03-09 10:10:54 +00002177void CheckFormatHandler::HandlePosition(const char *startPos,
2178 unsigned posLen) {
2179 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2180 getLocationOfByte(startPos),
2181 /*IsStringLocation*/true,
2182 getSpecifierRange(startPos, posLen));
2183}
2184
Ted Kremenekefaff192010-02-27 01:41:03 +00002185void
Ted Kremenek826a3452010-07-16 02:11:22 +00002186CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2187 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002188 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2189 << (unsigned) p,
2190 getLocationOfByte(startPos), /*IsStringLocation*/true,
2191 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002192}
2193
Ted Kremenek826a3452010-07-16 02:11:22 +00002194void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002195 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002196 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2197 getLocationOfByte(startPos),
2198 /*IsStringLocation*/true,
2199 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002200}
2201
Ted Kremenek826a3452010-07-16 02:11:22 +00002202void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002203 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002204 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002205 EmitFormatDiagnostic(
2206 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2207 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2208 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002209 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002210}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002211
Jordan Rose48716662012-07-19 18:10:08 +00002212// Note that this may return NULL if there was an error parsing or building
2213// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002214const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002215 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002216}
2217
2218void CheckFormatHandler::DoneProcessing() {
2219 // Does the number of data arguments exceed the number of
2220 // format conversions in the format string?
2221 if (!HasVAListArg) {
2222 // Find any arguments that weren't covered.
2223 CoveredArgs.flip();
2224 signed notCoveredArg = CoveredArgs.find_first();
2225 if (notCoveredArg >= 0) {
2226 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002227 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2228 SourceLocation Loc = E->getLocStart();
2229 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2230 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2231 Loc, /*IsStringLocation*/false,
2232 getFormatStringRange());
2233 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002234 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002235 }
2236 }
2237}
2238
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002239bool
2240CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2241 SourceLocation Loc,
2242 const char *startSpec,
2243 unsigned specifierLen,
2244 const char *csStart,
2245 unsigned csLen) {
2246
2247 bool keepGoing = true;
2248 if (argIndex < NumDataArgs) {
2249 // Consider the argument coverered, even though the specifier doesn't
2250 // make sense.
2251 CoveredArgs.set(argIndex);
2252 }
2253 else {
2254 // If argIndex exceeds the number of data arguments we
2255 // don't issue a warning because that is just a cascade of warnings (and
2256 // they may have intended '%%' anyway). We don't want to continue processing
2257 // the format string after this point, however, as we will like just get
2258 // gibberish when trying to match arguments.
2259 keepGoing = false;
2260 }
2261
Richard Trieu55733de2011-10-28 00:41:25 +00002262 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2263 << StringRef(csStart, csLen),
2264 Loc, /*IsStringLocation*/true,
2265 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002266
2267 return keepGoing;
2268}
2269
Richard Trieu55733de2011-10-28 00:41:25 +00002270void
2271CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2272 const char *startSpec,
2273 unsigned specifierLen) {
2274 EmitFormatDiagnostic(
2275 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2276 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2277}
2278
Ted Kremenek666a1972010-07-26 19:45:42 +00002279bool
2280CheckFormatHandler::CheckNumArgs(
2281 const analyze_format_string::FormatSpecifier &FS,
2282 const analyze_format_string::ConversionSpecifier &CS,
2283 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2284
2285 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002286 PartialDiagnostic PDiag = FS.usesPositionalArg()
2287 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2288 << (argIndex+1) << NumDataArgs)
2289 : S.PDiag(diag::warn_printf_insufficient_data_args);
2290 EmitFormatDiagnostic(
2291 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2292 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002293 return false;
2294 }
2295 return true;
2296}
2297
Richard Trieu55733de2011-10-28 00:41:25 +00002298template<typename Range>
2299void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2300 SourceLocation Loc,
2301 bool IsStringLocation,
2302 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002303 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002304 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002305 Loc, IsStringLocation, StringRange, FixIt);
2306}
2307
2308/// \brief If the format string is not within the funcion call, emit a note
2309/// so that the function call and string are in diagnostic messages.
2310///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002311/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002312/// call and only one diagnostic message will be produced. Otherwise, an
2313/// extra note will be emitted pointing to location of the format string.
2314///
2315/// \param ArgumentExpr the expression that is passed as the format string
2316/// argument in the function call. Used for getting locations when two
2317/// diagnostics are emitted.
2318///
2319/// \param PDiag the callee should already have provided any strings for the
2320/// diagnostic message. This function only adds locations and fixits
2321/// to diagnostics.
2322///
2323/// \param Loc primary location for diagnostic. If two diagnostics are
2324/// required, one will be at Loc and a new SourceLocation will be created for
2325/// the other one.
2326///
2327/// \param IsStringLocation if true, Loc points to the format string should be
2328/// used for the note. Otherwise, Loc points to the argument list and will
2329/// be used with PDiag.
2330///
2331/// \param StringRange some or all of the string to highlight. This is
2332/// templated so it can accept either a CharSourceRange or a SourceRange.
2333///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002334/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002335template<typename Range>
2336void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2337 const Expr *ArgumentExpr,
2338 PartialDiagnostic PDiag,
2339 SourceLocation Loc,
2340 bool IsStringLocation,
2341 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002342 ArrayRef<FixItHint> FixIt) {
2343 if (InFunctionCall) {
2344 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2345 D << StringRange;
2346 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2347 I != E; ++I) {
2348 D << *I;
2349 }
2350 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00002351 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2352 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00002353
2354 const Sema::SemaDiagnosticBuilder &Note =
2355 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2356 diag::note_format_string_defined);
2357
2358 Note << StringRange;
2359 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2360 I != E; ++I) {
2361 Note << *I;
2362 }
Richard Trieu55733de2011-10-28 00:41:25 +00002363 }
2364}
2365
Ted Kremenek826a3452010-07-16 02:11:22 +00002366//===--- CHECK: Printf format string checking ------------------------------===//
2367
2368namespace {
2369class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002370 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002371public:
2372 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2373 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002374 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002375 const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002376 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002377 unsigned formatIdx, bool inFunctionCall,
2378 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002379 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002380 numDataArgs, beg, hasVAListArg, Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002381 formatIdx, inFunctionCall, CallType), ObjCContext(isObjC)
2382 {}
2383
Ted Kremenek826a3452010-07-16 02:11:22 +00002384
2385 bool HandleInvalidPrintfConversionSpecifier(
2386 const analyze_printf::PrintfSpecifier &FS,
2387 const char *startSpecifier,
2388 unsigned specifierLen);
2389
2390 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2391 const char *startSpecifier,
2392 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002393 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2394 const char *StartSpecifier,
2395 unsigned SpecifierLen,
2396 const Expr *E);
2397
Ted Kremenek826a3452010-07-16 02:11:22 +00002398 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2399 const char *startSpecifier, unsigned specifierLen);
2400 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2401 const analyze_printf::OptionalAmount &Amt,
2402 unsigned type,
2403 const char *startSpecifier, unsigned specifierLen);
2404 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2405 const analyze_printf::OptionalFlag &flag,
2406 const char *startSpecifier, unsigned specifierLen);
2407 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2408 const analyze_printf::OptionalFlag &ignoredFlag,
2409 const analyze_printf::OptionalFlag &flag,
2410 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002411 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith831421f2012-06-25 20:30:08 +00002412 const Expr *E, const CharSourceRange &CSR);
2413
Ted Kremenek826a3452010-07-16 02:11:22 +00002414};
2415}
2416
2417bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2418 const analyze_printf::PrintfSpecifier &FS,
2419 const char *startSpecifier,
2420 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002421 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002422 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002423
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002424 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2425 getLocationOfByte(CS.getStart()),
2426 startSpecifier, specifierLen,
2427 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002428}
2429
Ted Kremenek826a3452010-07-16 02:11:22 +00002430bool CheckPrintfHandler::HandleAmount(
2431 const analyze_format_string::OptionalAmount &Amt,
2432 unsigned k, const char *startSpecifier,
2433 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002434
2435 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002436 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002437 unsigned argIndex = Amt.getArgIndex();
2438 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002439 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2440 << k,
2441 getLocationOfByte(Amt.getStart()),
2442 /*IsStringLocation*/true,
2443 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002444 // Don't do any more checking. We will just emit
2445 // spurious errors.
2446 return false;
2447 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002448
Ted Kremenek0d277352010-01-29 01:06:55 +00002449 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002450 // Although not in conformance with C99, we also allow the argument to be
2451 // an 'unsigned int' as that is a reasonably safe case. GCC also
2452 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002453 CoveredArgs.set(argIndex);
2454 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002455 if (!Arg)
2456 return false;
2457
Ted Kremenek0d277352010-01-29 01:06:55 +00002458 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002459
Hans Wennborgf3749f42012-08-07 08:11:26 +00002460 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2461 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002462
Hans Wennborgf3749f42012-08-07 08:11:26 +00002463 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002464 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002465 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002466 << T << Arg->getSourceRange(),
2467 getLocationOfByte(Amt.getStart()),
2468 /*IsStringLocation*/true,
2469 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002470 // Don't do any more checking. We will just emit
2471 // spurious errors.
2472 return false;
2473 }
2474 }
2475 }
2476 return true;
2477}
Ted Kremenek0d277352010-01-29 01:06:55 +00002478
Tom Caree4ee9662010-06-17 19:00:27 +00002479void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002480 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002481 const analyze_printf::OptionalAmount &Amt,
2482 unsigned type,
2483 const char *startSpecifier,
2484 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002485 const analyze_printf::PrintfConversionSpecifier &CS =
2486 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002487
Richard Trieu55733de2011-10-28 00:41:25 +00002488 FixItHint fixit =
2489 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2490 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2491 Amt.getConstantLength()))
2492 : FixItHint();
2493
2494 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2495 << type << CS.toString(),
2496 getLocationOfByte(Amt.getStart()),
2497 /*IsStringLocation*/true,
2498 getSpecifierRange(startSpecifier, specifierLen),
2499 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002500}
2501
Ted Kremenek826a3452010-07-16 02:11:22 +00002502void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002503 const analyze_printf::OptionalFlag &flag,
2504 const char *startSpecifier,
2505 unsigned specifierLen) {
2506 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002507 const analyze_printf::PrintfConversionSpecifier &CS =
2508 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002509 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2510 << flag.toString() << CS.toString(),
2511 getLocationOfByte(flag.getPosition()),
2512 /*IsStringLocation*/true,
2513 getSpecifierRange(startSpecifier, specifierLen),
2514 FixItHint::CreateRemoval(
2515 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002516}
2517
2518void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002519 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002520 const analyze_printf::OptionalFlag &ignoredFlag,
2521 const analyze_printf::OptionalFlag &flag,
2522 const char *startSpecifier,
2523 unsigned specifierLen) {
2524 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002525 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2526 << ignoredFlag.toString() << flag.toString(),
2527 getLocationOfByte(ignoredFlag.getPosition()),
2528 /*IsStringLocation*/true,
2529 getSpecifierRange(startSpecifier, specifierLen),
2530 FixItHint::CreateRemoval(
2531 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002532}
2533
Richard Smith831421f2012-06-25 20:30:08 +00002534// Determines if the specified is a C++ class or struct containing
2535// a member with the specified name and kind (e.g. a CXXMethodDecl named
2536// "c_str()").
2537template<typename MemberKind>
2538static llvm::SmallPtrSet<MemberKind*, 1>
2539CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2540 const RecordType *RT = Ty->getAs<RecordType>();
2541 llvm::SmallPtrSet<MemberKind*, 1> Results;
2542
2543 if (!RT)
2544 return Results;
2545 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2546 if (!RD)
2547 return Results;
2548
2549 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2550 Sema::LookupMemberName);
2551
2552 // We just need to include all members of the right kind turned up by the
2553 // filter, at this point.
2554 if (S.LookupQualifiedName(R, RT->getDecl()))
2555 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2556 NamedDecl *decl = (*I)->getUnderlyingDecl();
2557 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2558 Results.insert(FK);
2559 }
2560 return Results;
2561}
2562
2563// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002564// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002565// Returns true when a c_str() conversion method is found.
2566bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgf3749f42012-08-07 08:11:26 +00002567 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith831421f2012-06-25 20:30:08 +00002568 const CharSourceRange &CSR) {
2569 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2570
2571 MethodSet Results =
2572 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2573
2574 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2575 MI != ME; ++MI) {
2576 const CXXMethodDecl *Method = *MI;
2577 if (Method->getNumParams() == 0 &&
Hans Wennborgf3749f42012-08-07 08:11:26 +00002578 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith831421f2012-06-25 20:30:08 +00002579 // FIXME: Suggest parens if the expression needs them.
2580 SourceLocation EndLoc =
2581 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2582 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2583 << "c_str()"
2584 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2585 return true;
2586 }
2587 }
2588
2589 return false;
2590}
2591
Ted Kremeneke0e53132010-01-28 23:39:18 +00002592bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002593CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002594 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002595 const char *startSpecifier,
2596 unsigned specifierLen) {
2597
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002598 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002599 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002600 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002601
Ted Kremenekbaa40062010-07-19 22:01:06 +00002602 if (FS.consumesDataArgument()) {
2603 if (atFirstArg) {
2604 atFirstArg = false;
2605 usesPositionalArgs = FS.usesPositionalArg();
2606 }
2607 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002608 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2609 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002610 return false;
2611 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002612 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002613
Ted Kremenekefaff192010-02-27 01:41:03 +00002614 // First check if the field width, precision, and conversion specifier
2615 // have matching data arguments.
2616 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2617 startSpecifier, specifierLen)) {
2618 return false;
2619 }
2620
2621 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2622 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002623 return false;
2624 }
2625
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002626 if (!CS.consumesDataArgument()) {
2627 // FIXME: Technically specifying a precision or field width here
2628 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002629 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002630 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002631
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002632 // Consume the argument.
2633 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002634 if (argIndex < NumDataArgs) {
2635 // The check to see if the argIndex is valid will come later.
2636 // We set the bit here because we may exit early from this
2637 // function if we encounter some other error.
2638 CoveredArgs.set(argIndex);
2639 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002640
2641 // Check for using an Objective-C specific conversion specifier
2642 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002643 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002644 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2645 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002646 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002647
Tom Caree4ee9662010-06-17 19:00:27 +00002648 // Check for invalid use of field width
2649 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002650 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002651 startSpecifier, specifierLen);
2652 }
2653
2654 // Check for invalid use of precision
2655 if (!FS.hasValidPrecision()) {
2656 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2657 startSpecifier, specifierLen);
2658 }
2659
2660 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002661 if (!FS.hasValidThousandsGroupingPrefix())
2662 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002663 if (!FS.hasValidLeadingZeros())
2664 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2665 if (!FS.hasValidPlusPrefix())
2666 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002667 if (!FS.hasValidSpacePrefix())
2668 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002669 if (!FS.hasValidAlternativeForm())
2670 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2671 if (!FS.hasValidLeftJustified())
2672 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2673
2674 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002675 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2676 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2677 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002678 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2679 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2680 startSpecifier, specifierLen);
2681
2682 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002683 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00002684 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2685 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002686 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00002687 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002688 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00002689 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2690 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00002691
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002692 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
2693 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2694
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002695 // The remaining checks depend on the data arguments.
2696 if (HasVAListArg)
2697 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002698
Ted Kremenek666a1972010-07-26 19:45:42 +00002699 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002700 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002701
Jordan Rose48716662012-07-19 18:10:08 +00002702 const Expr *Arg = getDataArg(argIndex);
2703 if (!Arg)
2704 return true;
2705
2706 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00002707}
2708
Jordan Roseec087352012-09-05 22:56:26 +00002709static bool requiresParensToAddCast(const Expr *E) {
2710 // FIXME: We should have a general way to reason about operator
2711 // precedence and whether parens are actually needed here.
2712 // Take care of a few common cases where they aren't.
2713 const Expr *Inside = E->IgnoreImpCasts();
2714 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
2715 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
2716
2717 switch (Inside->getStmtClass()) {
2718 case Stmt::ArraySubscriptExprClass:
2719 case Stmt::CallExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002720 case Stmt::CharacterLiteralClass:
2721 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002722 case Stmt::DeclRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002723 case Stmt::FloatingLiteralClass:
2724 case Stmt::IntegerLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00002725 case Stmt::MemberExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002726 case Stmt::ObjCArrayLiteralClass:
2727 case Stmt::ObjCBoolLiteralExprClass:
2728 case Stmt::ObjCBoxedExprClass:
2729 case Stmt::ObjCDictionaryLiteralClass:
2730 case Stmt::ObjCEncodeExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002731 case Stmt::ObjCIvarRefExprClass:
2732 case Stmt::ObjCMessageExprClass:
2733 case Stmt::ObjCPropertyRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002734 case Stmt::ObjCStringLiteralClass:
2735 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002736 case Stmt::ParenExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002737 case Stmt::StringLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00002738 case Stmt::UnaryOperatorClass:
2739 return false;
2740 default:
2741 return true;
2742 }
2743}
2744
Richard Smith831421f2012-06-25 20:30:08 +00002745bool
2746CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2747 const char *StartSpecifier,
2748 unsigned SpecifierLen,
2749 const Expr *E) {
2750 using namespace analyze_format_string;
2751 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002752 // Now type check the data expression that matches the
2753 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00002754 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
2755 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00002756 if (!AT.isValid())
2757 return true;
Jordan Roseec087352012-09-05 22:56:26 +00002758
Jordan Rose448ac3e2012-12-05 18:44:40 +00002759 QualType ExprTy = E->getType();
Ted Kremenek02be9682013-04-10 06:26:26 +00002760 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
2761 ExprTy = TET->getUnderlyingExpr()->getType();
2762 }
2763
Jordan Rose448ac3e2012-12-05 18:44:40 +00002764 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002765 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00002766
Jordan Rose614a8652012-09-05 22:56:19 +00002767 // Look through argument promotions for our error message's reported type.
2768 // This includes the integral and floating promotions, but excludes array
2769 // and function pointer decay; seeing that an argument intended to be a
2770 // string has type 'char [6]' is probably more confusing than 'char *'.
2771 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2772 if (ICE->getCastKind() == CK_IntegralCast ||
2773 ICE->getCastKind() == CK_FloatingCast) {
2774 E = ICE->getSubExpr();
Jordan Rose448ac3e2012-12-05 18:44:40 +00002775 ExprTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00002776
2777 // Check if we didn't match because of an implicit cast from a 'char'
2778 // or 'short' to an 'int'. This is done because printf is a varargs
2779 // function.
2780 if (ICE->getType() == S.Context.IntTy ||
2781 ICE->getType() == S.Context.UnsignedIntTy) {
2782 // All further checking is done on the subexpression.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002783 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002784 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002785 }
Jordan Roseee0259d2012-06-04 22:48:57 +00002786 }
Jordan Rose448ac3e2012-12-05 18:44:40 +00002787 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
2788 // Special case for 'a', which has type 'int' in C.
2789 // Note, however, that we do /not/ want to treat multibyte constants like
2790 // 'MooV' as characters! This form is deprecated but still exists.
2791 if (ExprTy == S.Context.IntTy)
2792 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
2793 ExprTy = S.Context.CharTy;
Jordan Rose614a8652012-09-05 22:56:19 +00002794 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002795
Jordan Rose2cd34402012-12-05 18:44:49 +00002796 // %C in an Objective-C context prints a unichar, not a wchar_t.
2797 // If the argument is an integer of some kind, believe the %C and suggest
2798 // a cast instead of changing the conversion specifier.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002799 QualType IntendedTy = ExprTy;
Jordan Rose2cd34402012-12-05 18:44:49 +00002800 if (ObjCContext &&
2801 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
2802 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
2803 !ExprTy->isCharType()) {
2804 // 'unichar' is defined as a typedef of unsigned short, but we should
2805 // prefer using the typedef if it is visible.
2806 IntendedTy = S.Context.UnsignedShortTy;
2807
2808 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
2809 Sema::LookupOrdinaryName);
2810 if (S.LookupName(Result, S.getCurScope())) {
2811 NamedDecl *ND = Result.getFoundDecl();
2812 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
2813 if (TD->getUnderlyingType() == IntendedTy)
2814 IntendedTy = S.Context.getTypedefType(TD);
2815 }
2816 }
2817 }
2818
2819 // Special-case some of Darwin's platform-independence types by suggesting
2820 // casts to primitive types that are known to be large enough.
2821 bool ShouldNotPrintDirectly = false;
Jordan Roseec087352012-09-05 22:56:26 +00002822 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenek6edb0292013-03-25 22:28:37 +00002823 // Use a 'while' to peel off layers of typedefs.
2824 QualType TyTy = IntendedTy;
2825 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseec087352012-09-05 22:56:26 +00002826 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose2cd34402012-12-05 18:44:49 +00002827 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseec087352012-09-05 22:56:26 +00002828 .Case("NSInteger", S.Context.LongTy)
2829 .Case("NSUInteger", S.Context.UnsignedLongTy)
2830 .Case("SInt32", S.Context.IntTy)
2831 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose2cd34402012-12-05 18:44:49 +00002832 .Default(QualType());
2833
2834 if (!CastTy.isNull()) {
2835 ShouldNotPrintDirectly = true;
2836 IntendedTy = CastTy;
Ted Kremenek6edb0292013-03-25 22:28:37 +00002837 break;
Jordan Rose2cd34402012-12-05 18:44:49 +00002838 }
Ted Kremenek6edb0292013-03-25 22:28:37 +00002839 TyTy = UserTy->desugar();
Jordan Roseec087352012-09-05 22:56:26 +00002840 }
2841 }
2842
Jordan Rose614a8652012-09-05 22:56:19 +00002843 // We may be able to offer a FixItHint if it is a supported type.
2844 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00002845 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00002846 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002847
Jordan Rose614a8652012-09-05 22:56:19 +00002848 if (success) {
2849 // Get the fix string from the fixed format specifier
2850 SmallString<16> buf;
2851 llvm::raw_svector_ostream os(buf);
2852 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002853
Jordan Roseec087352012-09-05 22:56:26 +00002854 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
2855
Jordan Rose2cd34402012-12-05 18:44:49 +00002856 if (IntendedTy == ExprTy) {
2857 // In this case, the specifier is wrong and should be changed to match
2858 // the argument.
2859 EmitFormatDiagnostic(
2860 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2861 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
2862 << E->getSourceRange(),
2863 E->getLocStart(),
2864 /*IsStringLocation*/false,
2865 SpecRange,
2866 FixItHint::CreateReplacement(SpecRange, os.str()));
2867
2868 } else {
Jordan Roseec087352012-09-05 22:56:26 +00002869 // The canonical type for formatting this value is different from the
2870 // actual type of the expression. (This occurs, for example, with Darwin's
2871 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
2872 // should be printed as 'long' for 64-bit compatibility.)
2873 // Rather than emitting a normal format/argument mismatch, we want to
2874 // add a cast to the recommended type (and correct the format string
2875 // if necessary).
2876 SmallString<16> CastBuf;
2877 llvm::raw_svector_ostream CastFix(CastBuf);
2878 CastFix << "(";
2879 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
2880 CastFix << ")";
2881
2882 SmallVector<FixItHint,4> Hints;
2883 if (!AT.matchesType(S.Context, IntendedTy))
2884 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
2885
2886 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
2887 // If there's already a cast present, just replace it.
2888 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
2889 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
2890
2891 } else if (!requiresParensToAddCast(E)) {
2892 // If the expression has high enough precedence,
2893 // just write the C-style cast.
2894 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2895 CastFix.str()));
2896 } else {
2897 // Otherwise, add parens around the expression as well as the cast.
2898 CastFix << "(";
2899 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2900 CastFix.str()));
2901
2902 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
2903 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
2904 }
2905
Jordan Rose2cd34402012-12-05 18:44:49 +00002906 if (ShouldNotPrintDirectly) {
2907 // The expression has a type that should not be printed directly.
2908 // We extract the name from the typedef because we don't want to show
2909 // the underlying type in the diagnostic.
2910 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseec087352012-09-05 22:56:26 +00002911
Jordan Rose2cd34402012-12-05 18:44:49 +00002912 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
2913 << Name << IntendedTy
2914 << E->getSourceRange(),
2915 E->getLocStart(), /*IsStringLocation=*/false,
2916 SpecRange, Hints);
2917 } else {
2918 // In this case, the expression could be printed using a different
2919 // specifier, but we've decided that the specifier is probably correct
2920 // and we should cast instead. Just use the normal warning message.
2921 EmitFormatDiagnostic(
2922 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2923 << AT.getRepresentativeTypeName(S.Context) << ExprTy
2924 << E->getSourceRange(),
2925 E->getLocStart(), /*IsStringLocation*/false,
2926 SpecRange, Hints);
2927 }
Jordan Roseec087352012-09-05 22:56:26 +00002928 }
Jordan Rose614a8652012-09-05 22:56:19 +00002929 } else {
2930 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
2931 SpecifierLen);
2932 // Since the warning for passing non-POD types to variadic functions
2933 // was deferred until now, we emit a warning for non-POD
2934 // arguments here.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002935 if (S.isValidVarArgType(ExprTy) == Sema::VAK_Invalid) {
Jordan Rose614a8652012-09-05 22:56:19 +00002936 unsigned DiagKind;
Jordan Rose448ac3e2012-12-05 18:44:40 +00002937 if (ExprTy->isObjCObjectType())
Jordan Rose614a8652012-09-05 22:56:19 +00002938 DiagKind = diag::err_cannot_pass_objc_interface_to_vararg_format;
2939 else
2940 DiagKind = diag::warn_non_pod_vararg_with_format_string;
2941
2942 EmitFormatDiagnostic(
2943 S.PDiag(DiagKind)
Richard Smith80ad52f2013-01-02 11:42:31 +00002944 << S.getLangOpts().CPlusPlus11
Jordan Rose448ac3e2012-12-05 18:44:40 +00002945 << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00002946 << CallType
2947 << AT.getRepresentativeTypeName(S.Context)
2948 << CSR
2949 << E->getSourceRange(),
2950 E->getLocStart(), /*IsStringLocation*/false, CSR);
2951
2952 checkForCStrMembers(AT, E, CSR);
2953 } else
Richard Trieu55733de2011-10-28 00:41:25 +00002954 EmitFormatDiagnostic(
2955 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Jordan Rose448ac3e2012-12-05 18:44:40 +00002956 << AT.getRepresentativeTypeName(S.Context) << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00002957 << CSR
Richard Smith831421f2012-06-25 20:30:08 +00002958 << E->getSourceRange(),
Jordan Rose614a8652012-09-05 22:56:19 +00002959 E->getLocStart(), /*IsStringLocation*/false, CSR);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002960 }
2961
Ted Kremeneke0e53132010-01-28 23:39:18 +00002962 return true;
2963}
2964
Ted Kremenek826a3452010-07-16 02:11:22 +00002965//===--- CHECK: Scanf format string checking ------------------------------===//
2966
2967namespace {
2968class CheckScanfHandler : public CheckFormatHandler {
2969public:
2970 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2971 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002972 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002973 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002974 unsigned formatIdx, bool inFunctionCall,
2975 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002976 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002977 numDataArgs, beg, hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002978 Args, formatIdx, inFunctionCall, CallType)
Jordan Roseddcfbc92012-07-19 18:10:23 +00002979 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002980
2981 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2982 const char *startSpecifier,
2983 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002984
2985 bool HandleInvalidScanfConversionSpecifier(
2986 const analyze_scanf::ScanfSpecifier &FS,
2987 const char *startSpecifier,
2988 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002989
2990 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002991};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002992}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002993
Ted Kremenekb7c21012010-07-16 18:28:03 +00002994void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2995 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002996 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2997 getLocationOfByte(end), /*IsStringLocation*/true,
2998 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002999}
3000
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003001bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3002 const analyze_scanf::ScanfSpecifier &FS,
3003 const char *startSpecifier,
3004 unsigned specifierLen) {
3005
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003006 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003007 FS.getConversionSpecifier();
3008
3009 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3010 getLocationOfByte(CS.getStart()),
3011 startSpecifier, specifierLen,
3012 CS.getStart(), CS.getLength());
3013}
3014
Ted Kremenek826a3452010-07-16 02:11:22 +00003015bool CheckScanfHandler::HandleScanfSpecifier(
3016 const analyze_scanf::ScanfSpecifier &FS,
3017 const char *startSpecifier,
3018 unsigned specifierLen) {
3019
3020 using namespace analyze_scanf;
3021 using namespace analyze_format_string;
3022
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003023 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00003024
Ted Kremenekbaa40062010-07-19 22:01:06 +00003025 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3026 // be used to decide if we are using positional arguments consistently.
3027 if (FS.consumesDataArgument()) {
3028 if (atFirstArg) {
3029 atFirstArg = false;
3030 usesPositionalArgs = FS.usesPositionalArg();
3031 }
3032 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003033 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3034 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003035 return false;
3036 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003037 }
3038
3039 // Check if the field with is non-zero.
3040 const OptionalAmount &Amt = FS.getFieldWidth();
3041 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3042 if (Amt.getConstantAmount() == 0) {
3043 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3044 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00003045 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3046 getLocationOfByte(Amt.getStart()),
3047 /*IsStringLocation*/true, R,
3048 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00003049 }
3050 }
3051
3052 if (!FS.consumesDataArgument()) {
3053 // FIXME: Technically specifying a precision or field width here
3054 // makes no sense. Worth issuing a warning at some point.
3055 return true;
3056 }
3057
3058 // Consume the argument.
3059 unsigned argIndex = FS.getArgIndex();
3060 if (argIndex < NumDataArgs) {
3061 // The check to see if the argIndex is valid will come later.
3062 // We set the bit here because we may exit early from this
3063 // function if we encounter some other error.
3064 CoveredArgs.set(argIndex);
3065 }
3066
Ted Kremenek1e51c202010-07-20 20:04:47 +00003067 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003068 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003069 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3070 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003071 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003072 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003073 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003074 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3075 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00003076
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003077 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3078 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3079
Ted Kremenek826a3452010-07-16 02:11:22 +00003080 // The remaining checks depend on the data arguments.
3081 if (HasVAListArg)
3082 return true;
3083
Ted Kremenek666a1972010-07-26 19:45:42 +00003084 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00003085 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00003086
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003087 // Check that the argument type matches the format specifier.
3088 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00003089 if (!Ex)
3090 return true;
3091
Hans Wennborg58e1e542012-08-07 08:59:46 +00003092 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3093 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003094 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00003095 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00003096 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003097
3098 if (success) {
3099 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003100 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003101 llvm::raw_svector_ostream os(buf);
3102 fixedFS.toString(os);
3103
3104 EmitFormatDiagnostic(
3105 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003106 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003107 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003108 Ex->getLocStart(),
3109 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003110 getSpecifierRange(startSpecifier, specifierLen),
3111 FixItHint::CreateReplacement(
3112 getSpecifierRange(startSpecifier, specifierLen),
3113 os.str()));
3114 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003115 EmitFormatDiagnostic(
3116 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003117 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003118 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003119 Ex->getLocStart(),
3120 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003121 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003122 }
3123 }
3124
Ted Kremenek826a3452010-07-16 02:11:22 +00003125 return true;
3126}
3127
3128void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003129 const Expr *OrigFormatExpr,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003130 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003131 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003132 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003133 bool inFunctionCall, VariadicCallType CallType) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003134
Ted Kremeneke0e53132010-01-28 23:39:18 +00003135 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00003136 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003137 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003138 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003139 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3140 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003141 return;
3142 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003143
Ted Kremeneke0e53132010-01-28 23:39:18 +00003144 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00003145 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003146 const char *Str = StrRef.data();
3147 unsigned StrLen = StrRef.size();
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003148 const unsigned numDataArgs = Args.size() - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00003149
Ted Kremeneke0e53132010-01-28 23:39:18 +00003150 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00003151 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00003152 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003153 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003154 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3155 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003156 return;
3157 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003158
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003159 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003160 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003161 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003162 Str, HasVAListArg, Args, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003163 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003164
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003165 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003166 getLangOpts(),
3167 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003168 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003169 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00003170 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003171 Str, HasVAListArg, Args, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003172 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003173
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003174 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003175 getLangOpts(),
3176 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003177 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003178 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00003179}
3180
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003181//===--- CHECK: Standard memory functions ---------------------------------===//
3182
Douglas Gregor2a053a32011-05-03 20:05:22 +00003183/// \brief Determine whether the given type is a dynamic class type (e.g.,
3184/// whether it has a vtable).
3185static bool isDynamicClassType(QualType T) {
3186 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3187 if (CXXRecordDecl *Definition = Record->getDefinition())
3188 if (Definition->isDynamicClass())
3189 return true;
3190
3191 return false;
3192}
3193
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003194/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00003195/// otherwise returns NULL.
3196static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00003197 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00003198 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3199 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3200 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003201
Chandler Carruth000d4282011-06-16 09:09:40 +00003202 return 0;
3203}
3204
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003205/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00003206static QualType getSizeOfArgType(const Expr* E) {
3207 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3208 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3209 if (SizeOf->getKind() == clang::UETT_SizeOf)
3210 return SizeOf->getTypeOfArgument();
3211
3212 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00003213}
3214
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003215/// \brief Check for dangerous or invalid arguments to memset().
3216///
Chandler Carruth929f0132011-06-03 06:23:57 +00003217/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003218/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3219/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003220///
3221/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003222void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00003223 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003224 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00003225 assert(BId != 0);
3226
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003227 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00003228 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00003229 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00003230 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003231 return;
3232
Anna Zaks0a151a12012-01-17 00:37:07 +00003233 unsigned LastArg = (BId == Builtin::BImemset ||
3234 BId == Builtin::BIstrndup ? 1 : 2);
3235 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00003236 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00003237
3238 // We have special checking when the length is a sizeof expression.
3239 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3240 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3241 llvm::FoldingSetNodeID SizeOfArgID;
3242
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003243 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3244 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003245 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003246
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003247 QualType DestTy = Dest->getType();
3248 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3249 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00003250
Chandler Carruth000d4282011-06-16 09:09:40 +00003251 // Never warn about void type pointers. This can be used to suppress
3252 // false positives.
3253 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003254 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003255
Chandler Carruth000d4282011-06-16 09:09:40 +00003256 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3257 // actually comparing the expressions for equality. Because computing the
3258 // expression IDs can be expensive, we only do this if the diagnostic is
3259 // enabled.
3260 if (SizeOfArg &&
3261 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3262 SizeOfArg->getExprLoc())) {
3263 // We only compute IDs for expressions if the warning is enabled, and
3264 // cache the sizeof arg's ID.
3265 if (SizeOfArgID == llvm::FoldingSetNodeID())
3266 SizeOfArg->Profile(SizeOfArgID, Context, true);
3267 llvm::FoldingSetNodeID DestID;
3268 Dest->Profile(DestID, Context, true);
3269 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00003270 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3271 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00003272 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003273 StringRef ReadableName = FnName->getName();
3274
Chandler Carruth000d4282011-06-16 09:09:40 +00003275 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00003276 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00003277 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian7adf4172013-01-30 01:12:44 +00003278 if (!PointeeTy->isIncompleteType() &&
3279 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth000d4282011-06-16 09:09:40 +00003280 ActionIdx = 2; // If the pointee's size is sizeof(char),
3281 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003282
3283 // If the function is defined as a builtin macro, do not show macro
3284 // expansion.
3285 SourceLocation SL = SizeOfArg->getExprLoc();
3286 SourceRange DSR = Dest->getSourceRange();
3287 SourceRange SSR = SizeOfArg->getSourceRange();
3288 SourceManager &SM = PP.getSourceManager();
3289
3290 if (SM.isMacroArgExpansion(SL)) {
3291 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3292 SL = SM.getSpellingLoc(SL);
3293 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3294 SM.getSpellingLoc(DSR.getEnd()));
3295 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3296 SM.getSpellingLoc(SSR.getEnd()));
3297 }
3298
Anna Zaks90c78322012-05-30 23:14:52 +00003299 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00003300 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00003301 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00003302 << PointeeTy
3303 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00003304 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00003305 << SSR);
3306 DiagRuntimeBehavior(SL, SizeOfArg,
3307 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3308 << ActionIdx
3309 << SSR);
3310
Chandler Carruth000d4282011-06-16 09:09:40 +00003311 break;
3312 }
3313 }
3314
3315 // Also check for cases where the sizeof argument is the exact same
3316 // type as the memory argument, and where it points to a user-defined
3317 // record type.
3318 if (SizeOfArgTy != QualType()) {
3319 if (PointeeTy->isRecordType() &&
3320 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3321 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3322 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3323 << FnName << SizeOfArgTy << ArgIdx
3324 << PointeeTy << Dest->getSourceRange()
3325 << LenExpr->getSourceRange());
3326 break;
3327 }
Nico Webere4a1c642011-06-14 16:14:58 +00003328 }
3329
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003330 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00003331 if (isDynamicClassType(PointeeTy)) {
3332
3333 unsigned OperationType = 0;
3334 // "overwritten" if we're warning about the destination for any call
3335 // but memcmp; otherwise a verb appropriate to the call.
3336 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3337 if (BId == Builtin::BImemcpy)
3338 OperationType = 1;
3339 else if(BId == Builtin::BImemmove)
3340 OperationType = 2;
3341 else if (BId == Builtin::BImemcmp)
3342 OperationType = 3;
3343 }
3344
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003345 DiagRuntimeBehavior(
3346 Dest->getExprLoc(), Dest,
3347 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003348 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003349 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003350 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003351 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003352 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3353 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003354 DiagRuntimeBehavior(
3355 Dest->getExprLoc(), Dest,
3356 PDiag(diag::warn_arc_object_memaccess)
3357 << ArgIdx << FnName << PointeeTy
3358 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003359 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003360 continue;
John McCallf85e1932011-06-15 23:02:42 +00003361
3362 DiagRuntimeBehavior(
3363 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003364 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003365 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3366 break;
3367 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003368 }
3369}
3370
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003371// A little helper routine: ignore addition and subtraction of integer literals.
3372// This intentionally does not ignore all integer constant expressions because
3373// we don't want to remove sizeof().
3374static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3375 Ex = Ex->IgnoreParenCasts();
3376
3377 for (;;) {
3378 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3379 if (!BO || !BO->isAdditiveOp())
3380 break;
3381
3382 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3383 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3384
3385 if (isa<IntegerLiteral>(RHS))
3386 Ex = LHS;
3387 else if (isa<IntegerLiteral>(LHS))
3388 Ex = RHS;
3389 else
3390 break;
3391 }
3392
3393 return Ex;
3394}
3395
Anna Zaks0f38ace2012-08-08 21:42:23 +00003396static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3397 ASTContext &Context) {
3398 // Only handle constant-sized or VLAs, but not flexible members.
3399 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3400 // Only issue the FIXIT for arrays of size > 1.
3401 if (CAT->getSize().getSExtValue() <= 1)
3402 return false;
3403 } else if (!Ty->isVariableArrayType()) {
3404 return false;
3405 }
3406 return true;
3407}
3408
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003409// Warn if the user has made the 'size' argument to strlcpy or strlcat
3410// be the size of the source, instead of the destination.
3411void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3412 IdentifierInfo *FnName) {
3413
3414 // Don't crash if the user has the wrong number of arguments
3415 if (Call->getNumArgs() != 3)
3416 return;
3417
3418 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3419 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3420 const Expr *CompareWithSrc = NULL;
3421
3422 // Look for 'strlcpy(dst, x, sizeof(x))'
3423 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3424 CompareWithSrc = Ex;
3425 else {
3426 // Look for 'strlcpy(dst, x, strlen(x))'
3427 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003428 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003429 && SizeCall->getNumArgs() == 1)
3430 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3431 }
3432 }
3433
3434 if (!CompareWithSrc)
3435 return;
3436
3437 // Determine if the argument to sizeof/strlen is equal to the source
3438 // argument. In principle there's all kinds of things you could do
3439 // here, for instance creating an == expression and evaluating it with
3440 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3441 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3442 if (!SrcArgDRE)
3443 return;
3444
3445 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3446 if (!CompareWithSrcDRE ||
3447 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3448 return;
3449
3450 const Expr *OriginalSizeArg = Call->getArg(2);
3451 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3452 << OriginalSizeArg->getSourceRange() << FnName;
3453
3454 // Output a FIXIT hint if the destination is an array (rather than a
3455 // pointer to an array). This could be enhanced to handle some
3456 // pointers if we know the actual size, like if DstArg is 'array+2'
3457 // we could say 'sizeof(array)-2'.
3458 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00003459 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00003460 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00003461
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003462 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003463 llvm::raw_svector_ostream OS(sizeString);
3464 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003465 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003466 OS << ")";
3467
3468 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3469 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3470 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003471}
3472
Anna Zaksc36bedc2012-02-01 19:08:57 +00003473/// Check if two expressions refer to the same declaration.
3474static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3475 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3476 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3477 return D1->getDecl() == D2->getDecl();
3478 return false;
3479}
3480
3481static const Expr *getStrlenExprArg(const Expr *E) {
3482 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3483 const FunctionDecl *FD = CE->getDirectCallee();
3484 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3485 return 0;
3486 return CE->getArg(0)->IgnoreParenCasts();
3487 }
3488 return 0;
3489}
3490
3491// Warn on anti-patterns as the 'size' argument to strncat.
3492// The correct size argument should look like following:
3493// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3494void Sema::CheckStrncatArguments(const CallExpr *CE,
3495 IdentifierInfo *FnName) {
3496 // Don't crash if the user has the wrong number of arguments.
3497 if (CE->getNumArgs() < 3)
3498 return;
3499 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3500 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3501 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3502
3503 // Identify common expressions, which are wrongly used as the size argument
3504 // to strncat and may lead to buffer overflows.
3505 unsigned PatternType = 0;
3506 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3507 // - sizeof(dst)
3508 if (referToTheSameDecl(SizeOfArg, DstArg))
3509 PatternType = 1;
3510 // - sizeof(src)
3511 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3512 PatternType = 2;
3513 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3514 if (BE->getOpcode() == BO_Sub) {
3515 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3516 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3517 // - sizeof(dst) - strlen(dst)
3518 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3519 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3520 PatternType = 1;
3521 // - sizeof(src) - (anything)
3522 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3523 PatternType = 2;
3524 }
3525 }
3526
3527 if (PatternType == 0)
3528 return;
3529
Anna Zaksafdb0412012-02-03 01:27:37 +00003530 // Generate the diagnostic.
3531 SourceLocation SL = LenArg->getLocStart();
3532 SourceRange SR = LenArg->getSourceRange();
3533 SourceManager &SM = PP.getSourceManager();
3534
3535 // If the function is defined as a builtin macro, do not show macro expansion.
3536 if (SM.isMacroArgExpansion(SL)) {
3537 SL = SM.getSpellingLoc(SL);
3538 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3539 SM.getSpellingLoc(SR.getEnd()));
3540 }
3541
Anna Zaks0f38ace2012-08-08 21:42:23 +00003542 // Check if the destination is an array (rather than a pointer to an array).
3543 QualType DstTy = DstArg->getType();
3544 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3545 Context);
3546 if (!isKnownSizeArray) {
3547 if (PatternType == 1)
3548 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3549 else
3550 Diag(SL, diag::warn_strncat_src_size) << SR;
3551 return;
3552 }
3553
Anna Zaksc36bedc2012-02-01 19:08:57 +00003554 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003555 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003556 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003557 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003558
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003559 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003560 llvm::raw_svector_ostream OS(sizeString);
3561 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003562 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003563 OS << ") - ";
3564 OS << "strlen(";
Richard Smithd1420c62012-08-16 03:56:14 +00003565 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003566 OS << ") - 1";
3567
Anna Zaksafdb0412012-02-03 01:27:37 +00003568 Diag(SL, diag::note_strncat_wrong_size)
3569 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003570}
3571
Ted Kremenek06de2762007-08-17 16:46:58 +00003572//===--- CHECK: Return Address of Stack Variable --------------------------===//
3573
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003574static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3575 Decl *ParentDecl);
3576static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3577 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003578
3579/// CheckReturnStackAddr - Check if a return statement returns the address
3580/// of a stack variable.
3581void
3582Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3583 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003584
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003585 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003586 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003587
3588 // Perform checking for returned stack addresses, local blocks,
3589 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003590 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003591 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003592 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003593 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003594 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003595 }
3596
3597 if (stackE == 0)
3598 return; // Nothing suspicious was found.
3599
3600 SourceLocation diagLoc;
3601 SourceRange diagRange;
3602 if (refVars.empty()) {
3603 diagLoc = stackE->getLocStart();
3604 diagRange = stackE->getSourceRange();
3605 } else {
3606 // We followed through a reference variable. 'stackE' contains the
3607 // problematic expression but we will warn at the return statement pointing
3608 // at the reference variable. We will later display the "trail" of
3609 // reference variables using notes.
3610 diagLoc = refVars[0]->getLocStart();
3611 diagRange = refVars[0]->getSourceRange();
3612 }
3613
3614 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3615 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3616 : diag::warn_ret_stack_addr)
3617 << DR->getDecl()->getDeclName() << diagRange;
3618 } else if (isa<BlockExpr>(stackE)) { // local block.
3619 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3620 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3621 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3622 } else { // local temporary.
3623 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3624 : diag::warn_ret_local_temp_addr)
3625 << diagRange;
3626 }
3627
3628 // Display the "trail" of reference variables that we followed until we
3629 // found the problematic expression using notes.
3630 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3631 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3632 // If this var binds to another reference var, show the range of the next
3633 // var, otherwise the var binds to the problematic expression, in which case
3634 // show the range of the expression.
3635 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3636 : stackE->getSourceRange();
3637 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3638 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003639 }
3640}
3641
3642/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3643/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003644/// to a location on the stack, a local block, an address of a label, or a
3645/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003646/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003647/// encounter a subexpression that (1) clearly does not lead to one of the
3648/// above problematic expressions (2) is something we cannot determine leads to
3649/// a problematic expression based on such local checking.
3650///
3651/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3652/// the expression that they point to. Such variables are added to the
3653/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003654///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003655/// EvalAddr processes expressions that are pointers that are used as
3656/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003657/// At the base case of the recursion is a check for the above problematic
3658/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00003659///
3660/// This implementation handles:
3661///
3662/// * pointer-to-pointer casts
3663/// * implicit conversions from array references to pointers
3664/// * taking the address of fields
3665/// * arbitrary interplay between "&" and "*" operators
3666/// * pointer arithmetic from an address of a stack variable
3667/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003668static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3669 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003670 if (E->isTypeDependent())
3671 return NULL;
3672
Ted Kremenek06de2762007-08-17 16:46:58 +00003673 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00003674 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00003675 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003676 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003677 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00003678
Peter Collingbournef111d932011-04-15 00:35:48 +00003679 E = E->IgnoreParens();
3680
Ted Kremenek06de2762007-08-17 16:46:58 +00003681 // Our "symbolic interpreter" is just a dispatch off the currently
3682 // viewed AST node. We then recursively traverse the AST by calling
3683 // EvalAddr and EvalVal appropriately.
3684 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003685 case Stmt::DeclRefExprClass: {
3686 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3687
3688 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3689 // If this is a reference variable, follow through to the expression that
3690 // it points to.
3691 if (V->hasLocalStorage() &&
3692 V->getType()->isReferenceType() && V->hasInit()) {
3693 // Add the reference variable to the "trail".
3694 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003695 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003696 }
3697
3698 return NULL;
3699 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003700
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003701 case Stmt::UnaryOperatorClass: {
3702 // The only unary operator that make sense to handle here
3703 // is AddrOf. All others don't make sense as pointers.
3704 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003705
John McCall2de56d12010-08-25 11:45:40 +00003706 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003707 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003708 else
Ted Kremenek06de2762007-08-17 16:46:58 +00003709 return NULL;
3710 }
Mike Stump1eb44332009-09-09 15:08:12 +00003711
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003712 case Stmt::BinaryOperatorClass: {
3713 // Handle pointer arithmetic. All other binary operators are not valid
3714 // in this context.
3715 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00003716 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00003717
John McCall2de56d12010-08-25 11:45:40 +00003718 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003719 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00003720
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003721 Expr *Base = B->getLHS();
3722
3723 // Determine which argument is the real pointer base. It could be
3724 // the RHS argument instead of the LHS.
3725 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00003726
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003727 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003728 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003729 }
Steve Naroff61f40a22008-09-10 19:17:48 +00003730
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003731 // For conditional operators we need to see if either the LHS or RHS are
3732 // valid DeclRefExpr*s. If one of them is valid, we return it.
3733 case Stmt::ConditionalOperatorClass: {
3734 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003735
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003736 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003737 if (Expr *lhsExpr = C->getLHS()) {
3738 // In C++, we can have a throw-expression, which has 'void' type.
3739 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003740 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003741 return LHS;
3742 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003743
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003744 // In C++, we can have a throw-expression, which has 'void' type.
3745 if (C->getRHS()->getType()->isVoidType())
3746 return NULL;
3747
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003748 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003749 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003750
3751 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00003752 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003753 return E; // local block.
3754 return NULL;
3755
3756 case Stmt::AddrLabelExprClass:
3757 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00003758
John McCall80ee6e82011-11-10 05:35:25 +00003759 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003760 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
3761 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003762
Ted Kremenek54b52742008-08-07 00:49:01 +00003763 // For casts, we need to handle conversions from arrays to
3764 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00003765 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003766 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003767 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00003768 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00003769 case Stmt::CXXStaticCastExprClass:
3770 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00003771 case Stmt::CXXConstCastExprClass:
3772 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00003773 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3774 switch (cast<CastExpr>(E)->getCastKind()) {
3775 case CK_BitCast:
3776 case CK_LValueToRValue:
3777 case CK_NoOp:
3778 case CK_BaseToDerived:
3779 case CK_DerivedToBase:
3780 case CK_UncheckedDerivedToBase:
3781 case CK_Dynamic:
3782 case CK_CPointerToObjCPointerCast:
3783 case CK_BlockPointerToObjCPointerCast:
3784 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003785 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003786
3787 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003788 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003789
3790 default:
3791 return 0;
3792 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003793 }
Mike Stump1eb44332009-09-09 15:08:12 +00003794
Douglas Gregor03e80032011-06-21 17:03:29 +00003795 case Stmt::MaterializeTemporaryExprClass:
3796 if (Expr *Result = EvalAddr(
3797 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003798 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003799 return Result;
3800
3801 return E;
3802
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003803 // Everything else: we simply don't reason about them.
3804 default:
3805 return NULL;
3806 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003807}
Mike Stump1eb44332009-09-09 15:08:12 +00003808
Ted Kremenek06de2762007-08-17 16:46:58 +00003809
3810/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3811/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003812static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3813 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003814do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003815 // We should only be called for evaluating non-pointer expressions, or
3816 // expressions with a pointer type that are not used as references but instead
3817 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00003818
Ted Kremenek06de2762007-08-17 16:46:58 +00003819 // Our "symbolic interpreter" is just a dispatch off the currently
3820 // viewed AST node. We then recursively traverse the AST by calling
3821 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00003822
3823 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00003824 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003825 case Stmt::ImplicitCastExprClass: {
3826 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00003827 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003828 E = IE->getSubExpr();
3829 continue;
3830 }
3831 return NULL;
3832 }
3833
John McCall80ee6e82011-11-10 05:35:25 +00003834 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003835 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003836
Douglas Gregora2813ce2009-10-23 18:54:35 +00003837 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003838 // When we hit a DeclRefExpr we are looking at code that refers to a
3839 // variable's name. If it's not a reference variable we check if it has
3840 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00003841 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003842
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003843 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
3844 // Check if it refers to itself, e.g. "int& i = i;".
3845 if (V == ParentDecl)
3846 return DR;
3847
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003848 if (V->hasLocalStorage()) {
3849 if (!V->getType()->isReferenceType())
3850 return DR;
3851
3852 // Reference variable, follow through to the expression that
3853 // it points to.
3854 if (V->hasInit()) {
3855 // Add the reference variable to the "trail".
3856 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003857 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003858 }
3859 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003860 }
Mike Stump1eb44332009-09-09 15:08:12 +00003861
Ted Kremenek06de2762007-08-17 16:46:58 +00003862 return NULL;
3863 }
Mike Stump1eb44332009-09-09 15:08:12 +00003864
Ted Kremenek06de2762007-08-17 16:46:58 +00003865 case Stmt::UnaryOperatorClass: {
3866 // The only unary operator that make sense to handle here
3867 // is Deref. All others don't resolve to a "name." This includes
3868 // handling all sorts of rvalues passed to a unary operator.
3869 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003870
John McCall2de56d12010-08-25 11:45:40 +00003871 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003872 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003873
3874 return NULL;
3875 }
Mike Stump1eb44332009-09-09 15:08:12 +00003876
Ted Kremenek06de2762007-08-17 16:46:58 +00003877 case Stmt::ArraySubscriptExprClass: {
3878 // Array subscripts are potential references to data on the stack. We
3879 // retrieve the DeclRefExpr* for the array variable if it indeed
3880 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003881 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003882 }
Mike Stump1eb44332009-09-09 15:08:12 +00003883
Ted Kremenek06de2762007-08-17 16:46:58 +00003884 case Stmt::ConditionalOperatorClass: {
3885 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003886 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003887 ConditionalOperator *C = cast<ConditionalOperator>(E);
3888
Anders Carlsson39073232007-11-30 19:04:31 +00003889 // Handle the GNU extension for missing LHS.
3890 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003891 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00003892 return LHS;
3893
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003894 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003895 }
Mike Stump1eb44332009-09-09 15:08:12 +00003896
Ted Kremenek06de2762007-08-17 16:46:58 +00003897 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003898 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003899 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003900
Ted Kremenek06de2762007-08-17 16:46:58 +00003901 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003902 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003903 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003904
3905 // Check whether the member type is itself a reference, in which case
3906 // we're not going to refer to the member, but to what the member refers to.
3907 if (M->getMemberDecl()->getType()->isReferenceType())
3908 return NULL;
3909
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003910 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003911 }
Mike Stump1eb44332009-09-09 15:08:12 +00003912
Douglas Gregor03e80032011-06-21 17:03:29 +00003913 case Stmt::MaterializeTemporaryExprClass:
3914 if (Expr *Result = EvalVal(
3915 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003916 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003917 return Result;
3918
3919 return E;
3920
Ted Kremenek06de2762007-08-17 16:46:58 +00003921 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003922 // Check that we don't return or take the address of a reference to a
3923 // temporary. This is only useful in C++.
3924 if (!E->isTypeDependent() && E->isRValue())
3925 return E;
3926
3927 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003928 return NULL;
3929 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003930} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003931}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003932
3933//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3934
3935/// Check for comparisons of floating point operands using != and ==.
3936/// Issue a warning if these are no self-comparisons, as they are not likely
3937/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003938void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00003939 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3940 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003941
3942 // Special case: check for x == x (which is OK).
3943 // Do not emit warnings for such cases.
3944 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3945 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3946 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00003947 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003948
3949
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003950 // Special case: check for comparisons against literals that can be exactly
3951 // represented by APFloat. In such cases, do not emit a warning. This
3952 // is a heuristic: often comparison against such literals are used to
3953 // detect if a value in a variable has not changed. This clearly can
3954 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00003955 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3956 if (FLL->isExact())
3957 return;
3958 } else
3959 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
3960 if (FLR->isExact())
3961 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003962
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003963 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00003964 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
3965 if (CL->isBuiltinCall())
3966 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003967
David Blaikie980343b2012-07-16 20:47:22 +00003968 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
3969 if (CR->isBuiltinCall())
3970 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003971
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003972 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00003973 Diag(Loc, diag::warn_floatingpoint_eq)
3974 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003975}
John McCallba26e582010-01-04 23:21:16 +00003976
John McCallf2370c92010-01-06 05:24:50 +00003977//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3978//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003979
John McCallf2370c92010-01-06 05:24:50 +00003980namespace {
John McCallba26e582010-01-04 23:21:16 +00003981
John McCallf2370c92010-01-06 05:24:50 +00003982/// Structure recording the 'active' range of an integer-valued
3983/// expression.
3984struct IntRange {
3985 /// The number of bits active in the int.
3986 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003987
John McCallf2370c92010-01-06 05:24:50 +00003988 /// True if the int is known not to have negative values.
3989 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003990
John McCallf2370c92010-01-06 05:24:50 +00003991 IntRange(unsigned Width, bool NonNegative)
3992 : Width(Width), NonNegative(NonNegative)
3993 {}
John McCallba26e582010-01-04 23:21:16 +00003994
John McCall1844a6e2010-11-10 23:38:19 +00003995 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00003996 static IntRange forBoolType() {
3997 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00003998 }
3999
John McCall1844a6e2010-11-10 23:38:19 +00004000 /// Returns the range of an opaque value of the given integral type.
4001 static IntRange forValueOfType(ASTContext &C, QualType T) {
4002 return forValueOfCanonicalType(C,
4003 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00004004 }
4005
John McCall1844a6e2010-11-10 23:38:19 +00004006 /// Returns the range of an opaque value of a canonical integral type.
4007 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00004008 assert(T->isCanonicalUnqualified());
4009
4010 if (const VectorType *VT = dyn_cast<VectorType>(T))
4011 T = VT->getElementType().getTypePtr();
4012 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4013 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00004014
John McCall091f23f2010-11-09 22:22:12 +00004015 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00004016 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
4017 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00004018 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00004019 return IntRange(C.getIntWidth(QualType(T, 0)), false);
4020
John McCall323ed742010-05-06 08:58:33 +00004021 unsigned NumPositive = Enum->getNumPositiveBits();
4022 unsigned NumNegative = Enum->getNumNegativeBits();
4023
Richard Trieu8f50b242012-11-16 01:32:40 +00004024 if (NumNegative == 0)
4025 return IntRange(NumPositive, true/*NonNegative*/);
4026 else
4027 return IntRange(std::max(NumPositive + 1, NumNegative),
4028 false/*NonNegative*/);
John McCall323ed742010-05-06 08:58:33 +00004029 }
John McCallf2370c92010-01-06 05:24:50 +00004030
4031 const BuiltinType *BT = cast<BuiltinType>(T);
4032 assert(BT->isInteger());
4033
4034 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4035 }
4036
John McCall1844a6e2010-11-10 23:38:19 +00004037 /// Returns the "target" range of a canonical integral type, i.e.
4038 /// the range of values expressible in the type.
4039 ///
4040 /// This matches forValueOfCanonicalType except that enums have the
4041 /// full range of their type, not the range of their enumerators.
4042 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4043 assert(T->isCanonicalUnqualified());
4044
4045 if (const VectorType *VT = dyn_cast<VectorType>(T))
4046 T = VT->getElementType().getTypePtr();
4047 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4048 T = CT->getElementType().getTypePtr();
4049 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00004050 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00004051
4052 const BuiltinType *BT = cast<BuiltinType>(T);
4053 assert(BT->isInteger());
4054
4055 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4056 }
4057
4058 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004059 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00004060 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00004061 L.NonNegative && R.NonNegative);
4062 }
4063
John McCall1844a6e2010-11-10 23:38:19 +00004064 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004065 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00004066 return IntRange(std::min(L.Width, R.Width),
4067 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00004068 }
4069};
4070
Ted Kremenek0692a192012-01-31 05:37:37 +00004071static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4072 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004073 if (value.isSigned() && value.isNegative())
4074 return IntRange(value.getMinSignedBits(), false);
4075
4076 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00004077 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004078
4079 // isNonNegative() just checks the sign bit without considering
4080 // signedness.
4081 return IntRange(value.getActiveBits(), true);
4082}
4083
Ted Kremenek0692a192012-01-31 05:37:37 +00004084static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4085 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004086 if (result.isInt())
4087 return GetValueRange(C, result.getInt(), MaxWidth);
4088
4089 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00004090 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4091 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4092 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4093 R = IntRange::join(R, El);
4094 }
John McCallf2370c92010-01-06 05:24:50 +00004095 return R;
4096 }
4097
4098 if (result.isComplexInt()) {
4099 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4100 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4101 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00004102 }
4103
4104 // This can happen with lossless casts to intptr_t of "based" lvalues.
4105 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00004106 // FIXME: The only reason we need to pass the type in here is to get
4107 // the sign right on this one case. It would be nice if APValue
4108 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00004109 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004110 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00004111}
John McCallf2370c92010-01-06 05:24:50 +00004112
4113/// Pseudo-evaluate the given integer expression, estimating the
4114/// range of values it might take.
4115///
4116/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00004117static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004118 E = E->IgnoreParens();
4119
4120 // Try a full evaluation first.
4121 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004122 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00004123 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004124
4125 // I think we only want to look through implicit casts here; if the
4126 // user has an explicit widening cast, we should treat the value as
4127 // being of the new, wider type.
4128 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00004129 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00004130 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4131
John McCall1844a6e2010-11-10 23:38:19 +00004132 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00004133
John McCall2de56d12010-08-25 11:45:40 +00004134 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00004135
John McCallf2370c92010-01-06 05:24:50 +00004136 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00004137 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00004138 return OutputTypeRange;
4139
4140 IntRange SubRange
4141 = GetExprRange(C, CE->getSubExpr(),
4142 std::min(MaxWidth, OutputTypeRange.Width));
4143
4144 // Bail out if the subexpr's range is as wide as the cast type.
4145 if (SubRange.Width >= OutputTypeRange.Width)
4146 return OutputTypeRange;
4147
4148 // Otherwise, we take the smaller width, and we're non-negative if
4149 // either the output type or the subexpr is.
4150 return IntRange(SubRange.Width,
4151 SubRange.NonNegative || OutputTypeRange.NonNegative);
4152 }
4153
4154 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4155 // If we can fold the condition, just take that operand.
4156 bool CondResult;
4157 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4158 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4159 : CO->getFalseExpr(),
4160 MaxWidth);
4161
4162 // Otherwise, conservatively merge.
4163 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4164 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4165 return IntRange::join(L, R);
4166 }
4167
4168 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4169 switch (BO->getOpcode()) {
4170
4171 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00004172 case BO_LAnd:
4173 case BO_LOr:
4174 case BO_LT:
4175 case BO_GT:
4176 case BO_LE:
4177 case BO_GE:
4178 case BO_EQ:
4179 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00004180 return IntRange::forBoolType();
4181
John McCall862ff872011-07-13 06:35:24 +00004182 // The type of the assignments is the type of the LHS, so the RHS
4183 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00004184 case BO_MulAssign:
4185 case BO_DivAssign:
4186 case BO_RemAssign:
4187 case BO_AddAssign:
4188 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00004189 case BO_XorAssign:
4190 case BO_OrAssign:
4191 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00004192 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00004193
John McCall862ff872011-07-13 06:35:24 +00004194 // Simple assignments just pass through the RHS, which will have
4195 // been coerced to the LHS type.
4196 case BO_Assign:
4197 // TODO: bitfields?
4198 return GetExprRange(C, BO->getRHS(), MaxWidth);
4199
John McCallf2370c92010-01-06 05:24:50 +00004200 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004201 case BO_PtrMemD:
4202 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00004203 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004204
John McCall60fad452010-01-06 22:07:33 +00004205 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00004206 case BO_And:
4207 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00004208 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4209 GetExprRange(C, BO->getRHS(), MaxWidth));
4210
John McCallf2370c92010-01-06 05:24:50 +00004211 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00004212 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00004213 // ...except that we want to treat '1 << (blah)' as logically
4214 // positive. It's an important idiom.
4215 if (IntegerLiteral *I
4216 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4217 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00004218 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00004219 return IntRange(R.Width, /*NonNegative*/ true);
4220 }
4221 }
4222 // fallthrough
4223
John McCall2de56d12010-08-25 11:45:40 +00004224 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00004225 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004226
John McCall60fad452010-01-06 22:07:33 +00004227 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00004228 case BO_Shr:
4229 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00004230 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4231
4232 // If the shift amount is a positive constant, drop the width by
4233 // that much.
4234 llvm::APSInt shift;
4235 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4236 shift.isNonNegative()) {
4237 unsigned zext = shift.getZExtValue();
4238 if (zext >= L.Width)
4239 L.Width = (L.NonNegative ? 0 : 1);
4240 else
4241 L.Width -= zext;
4242 }
4243
4244 return L;
4245 }
4246
4247 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00004248 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00004249 return GetExprRange(C, BO->getRHS(), MaxWidth);
4250
John McCall60fad452010-01-06 22:07:33 +00004251 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00004252 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00004253 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00004254 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00004255 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00004256
John McCall00fe7612011-07-14 22:39:48 +00004257 // The width of a division result is mostly determined by the size
4258 // of the LHS.
4259 case BO_Div: {
4260 // Don't 'pre-truncate' the operands.
4261 unsigned opWidth = C.getIntWidth(E->getType());
4262 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4263
4264 // If the divisor is constant, use that.
4265 llvm::APSInt divisor;
4266 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4267 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4268 if (log2 >= L.Width)
4269 L.Width = (L.NonNegative ? 0 : 1);
4270 else
4271 L.Width = std::min(L.Width - log2, MaxWidth);
4272 return L;
4273 }
4274
4275 // Otherwise, just use the LHS's width.
4276 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4277 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4278 }
4279
4280 // The result of a remainder can't be larger than the result of
4281 // either side.
4282 case BO_Rem: {
4283 // Don't 'pre-truncate' the operands.
4284 unsigned opWidth = C.getIntWidth(E->getType());
4285 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4286 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4287
4288 IntRange meet = IntRange::meet(L, R);
4289 meet.Width = std::min(meet.Width, MaxWidth);
4290 return meet;
4291 }
4292
4293 // The default behavior is okay for these.
4294 case BO_Mul:
4295 case BO_Add:
4296 case BO_Xor:
4297 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00004298 break;
4299 }
4300
John McCall00fe7612011-07-14 22:39:48 +00004301 // The default case is to treat the operation as if it were closed
4302 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004303 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4304 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4305 return IntRange::join(L, R);
4306 }
4307
4308 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4309 switch (UO->getOpcode()) {
4310 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004311 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004312 return IntRange::forBoolType();
4313
4314 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004315 case UO_Deref:
4316 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00004317 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004318
4319 default:
4320 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4321 }
4322 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004323
4324 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00004325 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004326 }
John McCallf2370c92010-01-06 05:24:50 +00004327
John McCall993f43f2013-05-06 21:39:12 +00004328 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004329 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004330 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004331
John McCall1844a6e2010-11-10 23:38:19 +00004332 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004333}
John McCall51313c32010-01-04 23:31:57 +00004334
Ted Kremenek0692a192012-01-31 05:37:37 +00004335static IntRange GetExprRange(ASTContext &C, Expr *E) {
John McCall323ed742010-05-06 08:58:33 +00004336 return GetExprRange(C, E, C.getIntWidth(E->getType()));
4337}
4338
John McCall51313c32010-01-04 23:31:57 +00004339/// Checks whether the given value, which currently has the given
4340/// source semantics, has the same value when coerced through the
4341/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004342static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4343 const llvm::fltSemantics &Src,
4344 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004345 llvm::APFloat truncated = value;
4346
4347 bool ignored;
4348 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4349 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4350
4351 return truncated.bitwiseIsEqual(value);
4352}
4353
4354/// Checks whether the given value, which currently has the given
4355/// source semantics, has the same value when coerced through the
4356/// target semantics.
4357///
4358/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004359static bool IsSameFloatAfterCast(const APValue &value,
4360 const llvm::fltSemantics &Src,
4361 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004362 if (value.isFloat())
4363 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4364
4365 if (value.isVector()) {
4366 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4367 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4368 return false;
4369 return true;
4370 }
4371
4372 assert(value.isComplexFloat());
4373 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4374 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4375}
4376
Ted Kremenek0692a192012-01-31 05:37:37 +00004377static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004378
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004379static bool IsZero(Sema &S, Expr *E) {
4380 // Suppress cases where we are comparing against an enum constant.
4381 if (const DeclRefExpr *DR =
4382 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4383 if (isa<EnumConstantDecl>(DR->getDecl()))
4384 return false;
4385
4386 // Suppress cases where the '0' value is expanded from a macro.
4387 if (E->getLocStart().isMacroID())
4388 return false;
4389
John McCall323ed742010-05-06 08:58:33 +00004390 llvm::APSInt Value;
4391 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4392}
4393
John McCall372e1032010-10-06 00:25:24 +00004394static bool HasEnumType(Expr *E) {
4395 // Strip off implicit integral promotions.
4396 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004397 if (ICE->getCastKind() != CK_IntegralCast &&
4398 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004399 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004400 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004401 }
4402
4403 return E->getType()->isEnumeralType();
4404}
4405
Ted Kremenek0692a192012-01-31 05:37:37 +00004406static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004407 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004408 if (E->isValueDependent())
4409 return;
4410
John McCall2de56d12010-08-25 11:45:40 +00004411 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004412 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004413 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004414 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004415 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004416 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004417 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004418 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004419 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004420 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004421 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004422 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004423 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004424 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004425 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004426 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4427 }
4428}
4429
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004430static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004431 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004432 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004433 bool RhsConstant) {
Richard Trieu526e6272012-11-14 22:50:24 +00004434 // 0 values are handled later by CheckTrivialUnsignedComparison().
4435 if (Value == 0)
4436 return;
4437
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004438 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004439 QualType OtherT = Other->getType();
4440 QualType ConstantT = Constant->getType();
Richard Trieu526e6272012-11-14 22:50:24 +00004441 QualType CommonT = E->getLHS()->getType();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004442 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004443 return;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004444 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004445 && "comparison with non-integer type");
Richard Trieu526e6272012-11-14 22:50:24 +00004446
4447 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu526e6272012-11-14 22:50:24 +00004448 bool CommonSigned = CommonT->isSignedIntegerType();
4449
4450 bool EqualityOnly = false;
4451
4452 // TODO: Investigate using GetExprRange() to get tighter bounds on
4453 // on the bit ranges.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004454 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu526e6272012-11-14 22:50:24 +00004455 unsigned OtherWidth = OtherRange.Width;
4456
4457 if (CommonSigned) {
4458 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedmand87de7b2012-11-30 23:09:29 +00004459 if (!OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004460 // Check that the constant is representable in type OtherT.
4461 if (ConstantSigned) {
4462 if (OtherWidth >= Value.getMinSignedBits())
4463 return;
4464 } else { // !ConstantSigned
4465 if (OtherWidth >= Value.getActiveBits() + 1)
4466 return;
4467 }
4468 } else { // !OtherSigned
4469 // Check that the constant is representable in type OtherT.
4470 // Negative values are out of range.
4471 if (ConstantSigned) {
4472 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4473 return;
4474 } else { // !ConstantSigned
4475 if (OtherWidth >= Value.getActiveBits())
4476 return;
4477 }
4478 }
4479 } else { // !CommonSigned
Eli Friedmand87de7b2012-11-30 23:09:29 +00004480 if (OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004481 if (OtherWidth >= Value.getActiveBits())
4482 return;
Eli Friedmand87de7b2012-11-30 23:09:29 +00004483 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu526e6272012-11-14 22:50:24 +00004484 // Check to see if the constant is representable in OtherT.
4485 if (OtherWidth > Value.getActiveBits())
4486 return;
4487 // Check to see if the constant is equivalent to a negative value
4488 // cast to CommonT.
4489 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu5d1cf4f2012-11-15 03:43:50 +00004490 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu526e6272012-11-14 22:50:24 +00004491 return;
4492 // The constant value rests between values that OtherT can represent after
4493 // conversion. Relational comparison still works, but equality
4494 // comparisons will be tautological.
4495 EqualityOnly = true;
4496 } else { // OtherSigned && ConstantSigned
4497 assert(0 && "Two signed types converted to unsigned types.");
4498 }
4499 }
4500
4501 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4502
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004503 bool IsTrue = true;
Richard Trieu526e6272012-11-14 22:50:24 +00004504 if (op == BO_EQ || op == BO_NE) {
4505 IsTrue = op == BO_NE;
4506 } else if (EqualityOnly) {
4507 return;
4508 } else if (RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004509 if (op == BO_GT || op == BO_GE)
Richard Trieu526e6272012-11-14 22:50:24 +00004510 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004511 else // op == BO_LT || op == BO_LE
Richard Trieu526e6272012-11-14 22:50:24 +00004512 IsTrue = PositiveConstant;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004513 } else {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004514 if (op == BO_LT || op == BO_LE)
Richard Trieu526e6272012-11-14 22:50:24 +00004515 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004516 else // op == BO_GT || op == BO_GE
Richard Trieu526e6272012-11-14 22:50:24 +00004517 IsTrue = PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004518 }
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004519
4520 // If this is a comparison to an enum constant, include that
4521 // constant in the diagnostic.
4522 const EnumConstantDecl *ED = 0;
4523 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
4524 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
4525
4526 SmallString<64> PrettySourceValue;
4527 llvm::raw_svector_ostream OS(PrettySourceValue);
4528 if (ED)
Ted Kremenek9de50942013-03-15 22:02:46 +00004529 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004530 else
4531 OS << Value;
4532
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004533 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004534 << OS.str() << OtherT << IsTrue
Richard Trieu526e6272012-11-14 22:50:24 +00004535 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004536}
4537
John McCall323ed742010-05-06 08:58:33 +00004538/// Analyze the operands of the given comparison. Implements the
4539/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004540static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004541 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4542 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004543}
John McCall51313c32010-01-04 23:31:57 +00004544
John McCallba26e582010-01-04 23:21:16 +00004545/// \brief Implements -Wsign-compare.
4546///
Richard Trieudd225092011-09-15 21:56:47 +00004547/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004548static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004549 // The type the comparison is being performed in.
4550 QualType T = E->getLHS()->getType();
4551 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4552 && "comparison with mismatched types");
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00004553 if (E->isValueDependent())
4554 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004555
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004556 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4557 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004558
4559 bool IsComparisonConstant = false;
4560
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004561 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004562 // of 'true' or 'false'.
4563 if (T->isIntegralType(S.Context)) {
4564 llvm::APSInt RHSValue;
4565 bool IsRHSIntegralLiteral =
4566 RHS->isIntegerConstantExpr(RHSValue, S.Context);
4567 llvm::APSInt LHSValue;
4568 bool IsLHSIntegralLiteral =
4569 LHS->isIntegerConstantExpr(LHSValue, S.Context);
4570 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4571 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4572 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4573 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4574 else
4575 IsComparisonConstant =
4576 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004577 } else if (!T->hasUnsignedIntegerRepresentation())
4578 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004579
John McCall323ed742010-05-06 08:58:33 +00004580 // We don't do anything special if this isn't an unsigned integral
4581 // comparison: we're only interested in integral comparisons, and
4582 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004583 //
4584 // We also don't care about value-dependent expressions or expressions
4585 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004586 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00004587 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004588
John McCall323ed742010-05-06 08:58:33 +00004589 // Check to see if one of the (unmodified) operands is of different
4590 // signedness.
4591 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004592 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4593 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004594 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004595 signedOperand = LHS;
4596 unsignedOperand = RHS;
4597 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4598 signedOperand = RHS;
4599 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004600 } else {
John McCall323ed742010-05-06 08:58:33 +00004601 CheckTrivialUnsignedComparison(S, E);
4602 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004603 }
4604
John McCall323ed742010-05-06 08:58:33 +00004605 // Otherwise, calculate the effective range of the signed operand.
4606 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004607
John McCall323ed742010-05-06 08:58:33 +00004608 // Go ahead and analyze implicit conversions in the operands. Note
4609 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004610 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4611 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004612
John McCall323ed742010-05-06 08:58:33 +00004613 // If the signed range is non-negative, -Wsign-compare won't fire,
4614 // but we should still check for comparisons which are always true
4615 // or false.
4616 if (signedRange.NonNegative)
4617 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004618
4619 // For (in)equality comparisons, if the unsigned operand is a
4620 // constant which cannot collide with a overflowed signed operand,
4621 // then reinterpreting the signed operand as unsigned will not
4622 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00004623 if (E->isEqualityOp()) {
4624 unsigned comparisonWidth = S.Context.getIntWidth(T);
4625 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00004626
John McCall323ed742010-05-06 08:58:33 +00004627 // We should never be unable to prove that the unsigned operand is
4628 // non-negative.
4629 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
4630
4631 if (unsignedRange.Width < comparisonWidth)
4632 return;
4633 }
4634
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00004635 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4636 S.PDiag(diag::warn_mixed_sign_comparison)
4637 << LHS->getType() << RHS->getType()
4638 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00004639}
4640
John McCall15d7d122010-11-11 03:21:53 +00004641/// Analyzes an attempt to assign the given value to a bitfield.
4642///
4643/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00004644static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4645 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00004646 assert(Bitfield->isBitField());
4647 if (Bitfield->isInvalidDecl())
4648 return false;
4649
John McCall91b60142010-11-11 05:33:51 +00004650 // White-list bool bitfields.
4651 if (Bitfield->getType()->isBooleanType())
4652 return false;
4653
Douglas Gregor46ff3032011-02-04 13:09:01 +00004654 // Ignore value- or type-dependent expressions.
4655 if (Bitfield->getBitWidth()->isValueDependent() ||
4656 Bitfield->getBitWidth()->isTypeDependent() ||
4657 Init->isValueDependent() ||
4658 Init->isTypeDependent())
4659 return false;
4660
John McCall15d7d122010-11-11 03:21:53 +00004661 Expr *OriginalInit = Init->IgnoreParenImpCasts();
4662
Richard Smith80d4b552011-12-28 19:48:30 +00004663 llvm::APSInt Value;
4664 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00004665 return false;
4666
John McCall15d7d122010-11-11 03:21:53 +00004667 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004668 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00004669
4670 if (OriginalWidth <= FieldWidth)
4671 return false;
4672
Eli Friedman3a643af2012-01-26 23:11:39 +00004673 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004674 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00004675 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00004676
Eli Friedman3a643af2012-01-26 23:11:39 +00004677 // Check whether the stored value is equal to the original value.
4678 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00004679 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00004680 return false;
4681
Eli Friedman3a643af2012-01-26 23:11:39 +00004682 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00004683 // therefore don't strictly fit into a signed bitfield of width 1.
4684 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00004685 return false;
4686
John McCall15d7d122010-11-11 03:21:53 +00004687 std::string PrettyValue = Value.toString(10);
4688 std::string PrettyTrunc = TruncatedValue.toString(10);
4689
4690 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4691 << PrettyValue << PrettyTrunc << OriginalInit->getType()
4692 << Init->getSourceRange();
4693
4694 return true;
4695}
4696
John McCallbeb22aa2010-11-09 23:24:47 +00004697/// Analyze the given simple or compound assignment for warning-worthy
4698/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00004699static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00004700 // Just recurse on the LHS.
4701 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4702
4703 // We want to recurse on the RHS as normal unless we're assigning to
4704 // a bitfield.
John McCall993f43f2013-05-06 21:39:12 +00004705 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00004706 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall15d7d122010-11-11 03:21:53 +00004707 E->getOperatorLoc())) {
4708 // Recurse, ignoring any implicit conversions on the RHS.
4709 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
4710 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00004711 }
4712 }
4713
4714 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4715}
4716
John McCall51313c32010-01-04 23:31:57 +00004717/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004718static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004719 SourceLocation CContext, unsigned diag,
4720 bool pruneControlFlow = false) {
4721 if (pruneControlFlow) {
4722 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4723 S.PDiag(diag)
4724 << SourceType << T << E->getSourceRange()
4725 << SourceRange(CContext));
4726 return;
4727 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004728 S.Diag(E->getExprLoc(), diag)
4729 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
4730}
4731
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004732/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004733static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004734 SourceLocation CContext, unsigned diag,
4735 bool pruneControlFlow = false) {
4736 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004737}
4738
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004739/// Diagnose an implicit cast from a literal expression. Does not warn when the
4740/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004741void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
4742 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004743 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004744 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004745 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00004746 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
4747 T->hasUnsignedIntegerRepresentation());
4748 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00004749 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004750 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00004751 return;
4752
David Blaikiebe0ee872012-05-15 16:56:36 +00004753 SmallString<16> PrettySourceValue;
4754 Value.toString(PrettySourceValue);
David Blaikiede7e7b82012-05-15 17:18:27 +00004755 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00004756 if (T->isSpecificBuiltinType(BuiltinType::Bool))
4757 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
4758 else
David Blaikiede7e7b82012-05-15 17:18:27 +00004759 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00004760
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004761 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00004762 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
4763 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00004764}
4765
John McCall091f23f2010-11-09 22:22:12 +00004766std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
4767 if (!Range.Width) return "0";
4768
4769 llvm::APSInt ValueInRange = Value;
4770 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00004771 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00004772 return ValueInRange.toString(10);
4773}
4774
Hans Wennborg88617a22012-08-28 15:44:30 +00004775static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
4776 if (!isa<ImplicitCastExpr>(Ex))
4777 return false;
4778
4779 Expr *InnerE = Ex->IgnoreParenImpCasts();
4780 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
4781 const Type *Source =
4782 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4783 if (Target->isDependentType())
4784 return false;
4785
4786 const BuiltinType *FloatCandidateBT =
4787 dyn_cast<BuiltinType>(ToBool ? Source : Target);
4788 const Type *BoolCandidateType = ToBool ? Target : Source;
4789
4790 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
4791 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
4792}
4793
4794void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
4795 SourceLocation CC) {
4796 unsigned NumArgs = TheCall->getNumArgs();
4797 for (unsigned i = 0; i < NumArgs; ++i) {
4798 Expr *CurrA = TheCall->getArg(i);
4799 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
4800 continue;
4801
4802 bool IsSwapped = ((i > 0) &&
4803 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
4804 IsSwapped |= ((i < (NumArgs - 1)) &&
4805 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
4806 if (IsSwapped) {
4807 // Warn on this floating-point to bool conversion.
4808 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
4809 CurrA->getType(), CC,
4810 diag::warn_impcast_floating_point_to_bool);
4811 }
4812 }
4813}
4814
John McCall323ed742010-05-06 08:58:33 +00004815void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00004816 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00004817 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00004818
John McCall323ed742010-05-06 08:58:33 +00004819 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
4820 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
4821 if (Source == Target) return;
4822 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00004823
Chandler Carruth108f7562011-07-26 05:40:03 +00004824 // If the conversion context location is invalid don't complain. We also
4825 // don't want to emit a warning if the issue occurs from the expansion of
4826 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
4827 // delay this check as long as possible. Once we detect we are in that
4828 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00004829 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00004830 return;
4831
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004832 // Diagnose implicit casts to bool.
4833 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
4834 if (isa<StringLiteral>(E))
4835 // Warn on string literal to bool. Checks for string literals in logical
4836 // expressions, for instances, assert(0 && "error here"), is prevented
4837 // by a check in AnalyzeImplicitConversions().
4838 return DiagnoseImpCast(S, E, T, CC,
4839 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00004840 if (Source->isFunctionType()) {
4841 // Warn on function to bool. Checks free functions and static member
4842 // functions. Weakly imported functions are excluded from the check,
4843 // since it's common to test their value to check whether the linker
4844 // found a definition for them.
4845 ValueDecl *D = 0;
4846 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
4847 D = R->getDecl();
4848 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
4849 D = M->getMemberDecl();
4850 }
4851
4852 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00004853 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
4854 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
4855 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00004856 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
4857 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
4858 QualType ReturnType;
4859 UnresolvedSet<4> NonTemplateOverloads;
4860 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
4861 if (!ReturnType.isNull()
4862 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
4863 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
4864 << FixItHint::CreateInsertion(
4865 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00004866 return;
4867 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00004868 }
4869 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004870 }
John McCall51313c32010-01-04 23:31:57 +00004871
4872 // Strip vector types.
4873 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004874 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004875 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004876 return;
John McCallb4eb64d2010-10-08 02:01:28 +00004877 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004878 }
Chris Lattnerb792b302011-06-14 04:51:15 +00004879
4880 // If the vector cast is cast between two vectors of the same size, it is
4881 // a bitcast, not a conversion.
4882 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4883 return;
John McCall51313c32010-01-04 23:31:57 +00004884
4885 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4886 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4887 }
4888
4889 // Strip complex types.
4890 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004891 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004892 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004893 return;
4894
John McCallb4eb64d2010-10-08 02:01:28 +00004895 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004896 }
John McCall51313c32010-01-04 23:31:57 +00004897
4898 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4899 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4900 }
4901
4902 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4903 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4904
4905 // If the source is floating point...
4906 if (SourceBT && SourceBT->isFloatingPoint()) {
4907 // ...and the target is floating point...
4908 if (TargetBT && TargetBT->isFloatingPoint()) {
4909 // ...then warn if we're dropping FP rank.
4910
4911 // Builtin FP kinds are ordered by increasing FP rank.
4912 if (SourceBT->getKind() > TargetBT->getKind()) {
4913 // Don't warn about float constants that are precisely
4914 // representable in the target type.
4915 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004916 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00004917 // Value might be a float, a float vector, or a float complex.
4918 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00004919 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4920 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00004921 return;
4922 }
4923
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004924 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004925 return;
4926
John McCallb4eb64d2010-10-08 02:01:28 +00004927 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00004928 }
4929 return;
4930 }
4931
Ted Kremenekef9ff882011-03-10 20:03:42 +00004932 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00004933 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004934 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004935 return;
4936
Chandler Carrutha5b93322011-02-17 11:05:49 +00004937 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00004938 // We also want to warn on, e.g., "int i = -1.234"
4939 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4940 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4941 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
4942
Chandler Carruthf65076e2011-04-10 08:36:24 +00004943 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4944 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00004945 } else {
4946 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4947 }
4948 }
John McCall51313c32010-01-04 23:31:57 +00004949
Hans Wennborg88617a22012-08-28 15:44:30 +00004950 // If the target is bool, warn if expr is a function or method call.
4951 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
4952 isa<CallExpr>(E)) {
4953 // Check last argument of function call to see if it is an
4954 // implicit cast from a type matching the type the result
4955 // is being cast to.
4956 CallExpr *CEx = cast<CallExpr>(E);
4957 unsigned NumArgs = CEx->getNumArgs();
4958 if (NumArgs > 0) {
4959 Expr *LastA = CEx->getArg(NumArgs - 1);
4960 Expr *InnerE = LastA->IgnoreParenImpCasts();
4961 const Type *InnerType =
4962 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4963 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
4964 // Warn on this floating-point to bool conversion
4965 DiagnoseImpCast(S, E, T, CC,
4966 diag::warn_impcast_floating_point_to_bool);
4967 }
4968 }
4969 }
John McCall51313c32010-01-04 23:31:57 +00004970 return;
4971 }
4972
Richard Trieu1838ca52011-05-29 19:59:02 +00004973 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00004974 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiee81b43b2012-11-08 00:41:20 +00004975 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikie896c7dd2013-02-16 00:56:22 +00004976 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieb1360492012-03-16 20:30:12 +00004977 SourceLocation Loc = E->getSourceRange().getBegin();
4978 if (Loc.isMacroID())
4979 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00004980 if (!Loc.isMacroID() || CC.isMacroID())
4981 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
4982 << T << clang::SourceRange(CC)
4983 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
Richard Trieu1838ca52011-05-29 19:59:02 +00004984 }
4985
David Blaikieb26331b2012-06-19 21:19:06 +00004986 if (!Source->isIntegerType() || !Target->isIntegerType())
4987 return;
4988
David Blaikiebe0ee872012-05-15 16:56:36 +00004989 // TODO: remove this early return once the false positives for constant->bool
4990 // in templates, macros, etc, are reduced or removed.
4991 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
4992 return;
4993
John McCall323ed742010-05-06 08:58:33 +00004994 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00004995 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00004996
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00004997 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer25ffbef2013-03-28 19:07:11 +00004998 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00004999 // TODO: this should happen for bitfield stores, too.
5000 llvm::APSInt Value(32);
5001 if (E->isIntegerConstantExpr(Value, S.Context)) {
5002 if (S.SourceMgr.isInSystemMacro(CC))
5003 return;
5004
John McCall091f23f2010-11-09 22:22:12 +00005005 std::string PrettySourceValue = Value.toString(10);
5006 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005007
Ted Kremenek5e745da2011-10-22 02:37:33 +00005008 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5009 S.PDiag(diag::warn_impcast_integer_precision_constant)
5010 << PrettySourceValue << PrettyTargetValue
5011 << E->getType() << T << E->getSourceRange()
5012 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00005013 return;
5014 }
5015
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005016 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5017 if (S.SourceMgr.isInSystemMacro(CC))
5018 return;
5019
David Blaikie37050842012-04-12 22:40:54 +00005020 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00005021 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5022 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00005023 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00005024 }
5025
5026 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5027 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5028 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005029
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005030 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005031 return;
5032
John McCall323ed742010-05-06 08:58:33 +00005033 unsigned DiagID = diag::warn_impcast_integer_sign;
5034
5035 // Traditionally, gcc has warned about this under -Wsign-compare.
5036 // We also want to warn about it in -Wconversion.
5037 // So if -Wconversion is off, use a completely identical diagnostic
5038 // in the sign-compare group.
5039 // The conditional-checking code will
5040 if (ICContext) {
5041 DiagID = diag::warn_impcast_integer_sign_conditional;
5042 *ICContext = true;
5043 }
5044
John McCallb4eb64d2010-10-08 02:01:28 +00005045 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00005046 }
5047
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005048 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005049 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5050 // type, to give us better diagnostics.
5051 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00005052 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005053 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5054 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5055 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5056 SourceType = S.Context.getTypeDeclType(Enum);
5057 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5058 }
5059 }
5060
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005061 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5062 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall83972f12013-03-09 00:54:27 +00005063 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5064 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00005065 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005066 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005067 return;
5068
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005069 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005070 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005071 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005072
John McCall51313c32010-01-04 23:31:57 +00005073 return;
5074}
5075
David Blaikie9fb1ac52012-05-15 21:57:38 +00005076void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5077 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00005078
5079void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00005080 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00005081 E = E->IgnoreParenImpCasts();
5082
5083 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00005084 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00005085
John McCallb4eb64d2010-10-08 02:01:28 +00005086 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005087 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005088 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00005089 return;
5090}
5091
David Blaikie9fb1ac52012-05-15 21:57:38 +00005092void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5093 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00005094 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00005095
5096 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00005097 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5098 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005099
5100 // If -Wconversion would have warned about either of the candidates
5101 // for a signedness conversion to the context type...
5102 if (!Suspicious) return;
5103
5104 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005105 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5106 CC))
John McCall323ed742010-05-06 08:58:33 +00005107 return;
5108
John McCall323ed742010-05-06 08:58:33 +00005109 // ...then check whether it would have warned about either of the
5110 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00005111 if (E->getType() == T) return;
5112
5113 Suspicious = false;
5114 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5115 E->getType(), CC, &Suspicious);
5116 if (!Suspicious)
5117 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00005118 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005119}
5120
5121/// AnalyzeImplicitConversions - Find and report any interesting
5122/// implicit conversions in the given expression. There are a couple
5123/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005124void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005125 QualType T = OrigE->getType();
5126 Expr *E = OrigE->IgnoreParenImpCasts();
5127
Douglas Gregorf8b6e152011-10-10 17:38:18 +00005128 if (E->isTypeDependent() || E->isValueDependent())
5129 return;
5130
John McCall323ed742010-05-06 08:58:33 +00005131 // For conditional operators, we analyze the arguments as if they
5132 // were being fed directly into the output.
5133 if (isa<ConditionalOperator>(E)) {
5134 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00005135 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00005136 return;
5137 }
5138
Hans Wennborg88617a22012-08-28 15:44:30 +00005139 // Check implicit argument conversions for function calls.
5140 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5141 CheckImplicitArgumentConversions(S, Call, CC);
5142
John McCall323ed742010-05-06 08:58:33 +00005143 // Go ahead and check any implicit conversions we might have skipped.
5144 // The non-canonical typecheck is just an optimization;
5145 // CheckImplicitConversion will filter out dead implicit conversions.
5146 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005147 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00005148
5149 // Now continue drilling into this expression.
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005150
5151 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005152 if (POE->getResultExpr())
5153 E = POE->getResultExpr();
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005154 }
5155
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005156 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5157 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5158
John McCall323ed742010-05-06 08:58:33 +00005159 // Skip past explicit casts.
5160 if (isa<ExplicitCastExpr>(E)) {
5161 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00005162 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005163 }
5164
John McCallbeb22aa2010-11-09 23:24:47 +00005165 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5166 // Do a somewhat different check with comparison operators.
5167 if (BO->isComparisonOp())
5168 return AnalyzeComparison(S, BO);
5169
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005170 // And with simple assignments.
5171 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00005172 return AnalyzeAssignment(S, BO);
5173 }
John McCall323ed742010-05-06 08:58:33 +00005174
5175 // These break the otherwise-useful invariant below. Fortunately,
5176 // we don't really need to recurse into them, because any internal
5177 // expressions should have been analyzed already when they were
5178 // built into statements.
5179 if (isa<StmtExpr>(E)) return;
5180
5181 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005182 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00005183
5184 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00005185 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005186 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5187 bool IsLogicalOperator = BO && BO->isLogicalOp();
5188 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00005189 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00005190 if (!ChildExpr)
5191 continue;
5192
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005193 if (IsLogicalOperator &&
5194 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5195 // Ignore checking string literals that are in logical operators.
5196 continue;
5197 AnalyzeImplicitConversions(S, ChildExpr, CC);
5198 }
John McCall323ed742010-05-06 08:58:33 +00005199}
5200
5201} // end anonymous namespace
5202
5203/// Diagnoses "dangerous" implicit conversions within the given
5204/// expression (which is a full expression). Implements -Wconversion
5205/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005206///
5207/// \param CC the "context" location of the implicit conversion, i.e.
5208/// the most location of the syntactic entity requiring the implicit
5209/// conversion
5210void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005211 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00005212 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00005213 return;
5214
5215 // Don't diagnose for value- or type-dependent expressions.
5216 if (E->isTypeDependent() || E->isValueDependent())
5217 return;
5218
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005219 // Check for array bounds violations in cases where the check isn't triggered
5220 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5221 // ArraySubscriptExpr is on the RHS of a variable initialization.
5222 CheckArrayAccess(E);
5223
John McCallb4eb64d2010-10-08 02:01:28 +00005224 // This is not the right CC for (e.g.) a variable initialization.
5225 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005226}
5227
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005228/// Diagnose when expression is an integer constant expression and its evaluation
5229/// results in integer overflow
5230void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanian1fd8d462013-03-15 20:47:07 +00005231 if (isa<BinaryOperator>(E->IgnoreParens())) {
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005232 llvm::SmallVector<PartialDiagnosticAt, 4> Diags;
5233 E->EvaluateForOverflow(Context, &Diags);
5234 }
5235}
5236
Richard Smith6c3af3d2013-01-17 01:17:56 +00005237namespace {
5238/// \brief Visitor for expressions which looks for unsequenced operations on the
5239/// same object.
5240class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
5241 /// \brief A tree of sequenced regions within an expression. Two regions are
5242 /// unsequenced if one is an ancestor or a descendent of the other. When we
5243 /// finish processing an expression with sequencing, such as a comma
5244 /// expression, we fold its tree nodes into its parent, since they are
5245 /// unsequenced with respect to nodes we will visit later.
5246 class SequenceTree {
5247 struct Value {
5248 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5249 unsigned Parent : 31;
5250 bool Merged : 1;
5251 };
5252 llvm::SmallVector<Value, 8> Values;
5253
5254 public:
5255 /// \brief A region within an expression which may be sequenced with respect
5256 /// to some other region.
5257 class Seq {
5258 explicit Seq(unsigned N) : Index(N) {}
5259 unsigned Index;
5260 friend class SequenceTree;
5261 public:
5262 Seq() : Index(0) {}
5263 };
5264
5265 SequenceTree() { Values.push_back(Value(0)); }
5266 Seq root() const { return Seq(0); }
5267
5268 /// \brief Create a new sequence of operations, which is an unsequenced
5269 /// subset of \p Parent. This sequence of operations is sequenced with
5270 /// respect to other children of \p Parent.
5271 Seq allocate(Seq Parent) {
5272 Values.push_back(Value(Parent.Index));
5273 return Seq(Values.size() - 1);
5274 }
5275
5276 /// \brief Merge a sequence of operations into its parent.
5277 void merge(Seq S) {
5278 Values[S.Index].Merged = true;
5279 }
5280
5281 /// \brief Determine whether two operations are unsequenced. This operation
5282 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5283 /// should have been merged into its parent as appropriate.
5284 bool isUnsequenced(Seq Cur, Seq Old) {
5285 unsigned C = representative(Cur.Index);
5286 unsigned Target = representative(Old.Index);
5287 while (C >= Target) {
5288 if (C == Target)
5289 return true;
5290 C = Values[C].Parent;
5291 }
5292 return false;
5293 }
5294
5295 private:
5296 /// \brief Pick a representative for a sequence.
5297 unsigned representative(unsigned K) {
5298 if (Values[K].Merged)
5299 // Perform path compression as we go.
5300 return Values[K].Parent = representative(Values[K].Parent);
5301 return K;
5302 }
5303 };
5304
5305 /// An object for which we can track unsequenced uses.
5306 typedef NamedDecl *Object;
5307
5308 /// Different flavors of object usage which we track. We only track the
5309 /// least-sequenced usage of each kind.
5310 enum UsageKind {
5311 /// A read of an object. Multiple unsequenced reads are OK.
5312 UK_Use,
5313 /// A modification of an object which is sequenced before the value
5314 /// computation of the expression, such as ++n.
5315 UK_ModAsValue,
5316 /// A modification of an object which is not sequenced before the value
5317 /// computation of the expression, such as n++.
5318 UK_ModAsSideEffect,
5319
5320 UK_Count = UK_ModAsSideEffect + 1
5321 };
5322
5323 struct Usage {
5324 Usage() : Use(0), Seq() {}
5325 Expr *Use;
5326 SequenceTree::Seq Seq;
5327 };
5328
5329 struct UsageInfo {
5330 UsageInfo() : Diagnosed(false) {}
5331 Usage Uses[UK_Count];
5332 /// Have we issued a diagnostic for this variable already?
5333 bool Diagnosed;
5334 };
5335 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5336
5337 Sema &SemaRef;
5338 /// Sequenced regions within the expression.
5339 SequenceTree Tree;
5340 /// Declaration modifications and references which we have seen.
5341 UsageInfoMap UsageMap;
5342 /// The region we are currently within.
5343 SequenceTree::Seq Region;
5344 /// Filled in with declarations which were modified as a side-effect
5345 /// (that is, post-increment operations).
5346 llvm::SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smith1a2dcd52013-01-17 23:18:09 +00005347 /// Expressions to check later. We defer checking these to reduce
5348 /// stack usage.
5349 llvm::SmallVectorImpl<Expr*> &WorkList;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005350
5351 /// RAII object wrapping the visitation of a sequenced subexpression of an
5352 /// expression. At the end of this process, the side-effects of the evaluation
5353 /// become sequenced with respect to the value computation of the result, so
5354 /// we downgrade any UK_ModAsSideEffect within the evaluation to
5355 /// UK_ModAsValue.
5356 struct SequencedSubexpression {
5357 SequencedSubexpression(SequenceChecker &Self)
5358 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5359 Self.ModAsSideEffect = &ModAsSideEffect;
5360 }
5361 ~SequencedSubexpression() {
5362 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5363 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5364 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5365 Self.addUsage(U, ModAsSideEffect[I].first,
5366 ModAsSideEffect[I].second.Use, UK_ModAsValue);
5367 }
5368 Self.ModAsSideEffect = OldModAsSideEffect;
5369 }
5370
5371 SequenceChecker &Self;
5372 llvm::SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5373 llvm::SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
5374 };
5375
5376 /// \brief Find the object which is produced by the specified expression,
5377 /// if any.
5378 Object getObject(Expr *E, bool Mod) const {
5379 E = E->IgnoreParenCasts();
5380 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5381 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5382 return getObject(UO->getSubExpr(), Mod);
5383 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5384 if (BO->getOpcode() == BO_Comma)
5385 return getObject(BO->getRHS(), Mod);
5386 if (Mod && BO->isAssignmentOp())
5387 return getObject(BO->getLHS(), Mod);
5388 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5389 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5390 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5391 return ME->getMemberDecl();
5392 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5393 // FIXME: If this is a reference, map through to its value.
5394 return DRE->getDecl();
5395 return 0;
5396 }
5397
5398 /// \brief Note that an object was modified or used by an expression.
5399 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5400 Usage &U = UI.Uses[UK];
5401 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5402 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5403 ModAsSideEffect->push_back(std::make_pair(O, U));
5404 U.Use = Ref;
5405 U.Seq = Region;
5406 }
5407 }
5408 /// \brief Check whether a modification or use conflicts with a prior usage.
5409 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5410 bool IsModMod) {
5411 if (UI.Diagnosed)
5412 return;
5413
5414 const Usage &U = UI.Uses[OtherKind];
5415 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5416 return;
5417
5418 Expr *Mod = U.Use;
5419 Expr *ModOrUse = Ref;
5420 if (OtherKind == UK_Use)
5421 std::swap(Mod, ModOrUse);
5422
5423 SemaRef.Diag(Mod->getExprLoc(),
5424 IsModMod ? diag::warn_unsequenced_mod_mod
5425 : diag::warn_unsequenced_mod_use)
5426 << O << SourceRange(ModOrUse->getExprLoc());
5427 UI.Diagnosed = true;
5428 }
5429
5430 void notePreUse(Object O, Expr *Use) {
5431 UsageInfo &U = UsageMap[O];
5432 // Uses conflict with other modifications.
5433 checkUsage(O, U, Use, UK_ModAsValue, false);
5434 }
5435 void notePostUse(Object O, Expr *Use) {
5436 UsageInfo &U = UsageMap[O];
5437 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5438 addUsage(U, O, Use, UK_Use);
5439 }
5440
5441 void notePreMod(Object O, Expr *Mod) {
5442 UsageInfo &U = UsageMap[O];
5443 // Modifications conflict with other modifications and with uses.
5444 checkUsage(O, U, Mod, UK_ModAsValue, true);
5445 checkUsage(O, U, Mod, UK_Use, false);
5446 }
5447 void notePostMod(Object O, Expr *Use, UsageKind UK) {
5448 UsageInfo &U = UsageMap[O];
5449 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5450 addUsage(U, O, Use, UK);
5451 }
5452
5453public:
Richard Smith1a2dcd52013-01-17 23:18:09 +00005454 SequenceChecker(Sema &S, Expr *E,
5455 llvm::SmallVectorImpl<Expr*> &WorkList)
Richard Smithe5096c82013-01-17 01:40:50 +00005456 : EvaluatedExprVisitor<SequenceChecker>(S.Context), SemaRef(S),
Richard Smith1a2dcd52013-01-17 23:18:09 +00005457 Region(Tree.root()), ModAsSideEffect(0), WorkList(WorkList) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005458 Visit(E);
5459 }
5460
5461 void VisitStmt(Stmt *S) {
5462 // Skip all statements which aren't expressions for now.
5463 }
5464
5465 void VisitExpr(Expr *E) {
5466 // By default, just recurse to evaluated subexpressions.
Richard Smithe5096c82013-01-17 01:40:50 +00005467 EvaluatedExprVisitor<SequenceChecker>::VisitStmt(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005468 }
5469
5470 void VisitCastExpr(CastExpr *E) {
5471 Object O = Object();
5472 if (E->getCastKind() == CK_LValueToRValue)
5473 O = getObject(E->getSubExpr(), false);
5474
5475 if (O)
5476 notePreUse(O, E);
5477 VisitExpr(E);
5478 if (O)
5479 notePostUse(O, E);
5480 }
5481
5482 void VisitBinComma(BinaryOperator *BO) {
5483 // C++11 [expr.comma]p1:
5484 // Every value computation and side effect associated with the left
5485 // expression is sequenced before every value computation and side
5486 // effect associated with the right expression.
5487 SequenceTree::Seq LHS = Tree.allocate(Region);
5488 SequenceTree::Seq RHS = Tree.allocate(Region);
5489 SequenceTree::Seq OldRegion = Region;
5490
5491 {
5492 SequencedSubexpression SeqLHS(*this);
5493 Region = LHS;
5494 Visit(BO->getLHS());
5495 }
5496
5497 Region = RHS;
5498 Visit(BO->getRHS());
5499
5500 Region = OldRegion;
5501
5502 // Forget that LHS and RHS are sequenced. They are both unsequenced
5503 // with respect to other stuff.
5504 Tree.merge(LHS);
5505 Tree.merge(RHS);
5506 }
5507
5508 void VisitBinAssign(BinaryOperator *BO) {
5509 // The modification is sequenced after the value computation of the LHS
5510 // and RHS, so check it before inspecting the operands and update the
5511 // map afterwards.
5512 Object O = getObject(BO->getLHS(), true);
5513 if (!O)
5514 return VisitExpr(BO);
5515
5516 notePreMod(O, BO);
5517
5518 // C++11 [expr.ass]p7:
5519 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
5520 // only once.
5521 //
5522 // Therefore, for a compound assignment operator, O is considered used
5523 // everywhere except within the evaluation of E1 itself.
5524 if (isa<CompoundAssignOperator>(BO))
5525 notePreUse(O, BO);
5526
5527 Visit(BO->getLHS());
5528
5529 if (isa<CompoundAssignOperator>(BO))
5530 notePostUse(O, BO);
5531
5532 Visit(BO->getRHS());
5533
5534 notePostMod(O, BO, UK_ModAsValue);
5535 }
5536 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
5537 VisitBinAssign(CAO);
5538 }
5539
5540 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5541 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5542 void VisitUnaryPreIncDec(UnaryOperator *UO) {
5543 Object O = getObject(UO->getSubExpr(), true);
5544 if (!O)
5545 return VisitExpr(UO);
5546
5547 notePreMod(O, UO);
5548 Visit(UO->getSubExpr());
5549 notePostMod(O, UO, UK_ModAsValue);
5550 }
5551
5552 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5553 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5554 void VisitUnaryPostIncDec(UnaryOperator *UO) {
5555 Object O = getObject(UO->getSubExpr(), true);
5556 if (!O)
5557 return VisitExpr(UO);
5558
5559 notePreMod(O, UO);
5560 Visit(UO->getSubExpr());
5561 notePostMod(O, UO, UK_ModAsSideEffect);
5562 }
5563
5564 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
5565 void VisitBinLOr(BinaryOperator *BO) {
5566 // The side-effects of the LHS of an '&&' are sequenced before the
5567 // value computation of the RHS, and hence before the value computation
5568 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
5569 // as if they were unconditionally sequenced.
5570 {
5571 SequencedSubexpression Sequenced(*this);
5572 Visit(BO->getLHS());
5573 }
5574
5575 bool Result;
5576 if (!BO->getLHS()->isValueDependent() &&
Richard Smith995e4a72013-01-17 22:06:26 +00005577 BO->getLHS()->EvaluateAsBooleanCondition(Result, SemaRef.Context)) {
5578 if (!Result)
5579 Visit(BO->getRHS());
5580 } else {
5581 // Check for unsequenced operations in the RHS, treating it as an
5582 // entirely separate evaluation.
5583 //
5584 // FIXME: If there are operations in the RHS which are unsequenced
5585 // with respect to operations outside the RHS, and those operations
5586 // are unconditionally evaluated, diagnose them.
Richard Smith1a2dcd52013-01-17 23:18:09 +00005587 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00005588 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005589 }
5590 void VisitBinLAnd(BinaryOperator *BO) {
5591 {
5592 SequencedSubexpression Sequenced(*this);
5593 Visit(BO->getLHS());
5594 }
5595
5596 bool Result;
5597 if (!BO->getLHS()->isValueDependent() &&
Richard Smith995e4a72013-01-17 22:06:26 +00005598 BO->getLHS()->EvaluateAsBooleanCondition(Result, SemaRef.Context)) {
5599 if (Result)
5600 Visit(BO->getRHS());
5601 } else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005602 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00005603 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005604 }
5605
5606 // Only visit the condition, unless we can be sure which subexpression will
5607 // be chosen.
5608 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
5609 SequencedSubexpression Sequenced(*this);
5610 Visit(CO->getCond());
5611
5612 bool Result;
5613 if (!CO->getCond()->isValueDependent() &&
5614 CO->getCond()->EvaluateAsBooleanCondition(Result, SemaRef.Context))
5615 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00005616 else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005617 WorkList.push_back(CO->getTrueExpr());
5618 WorkList.push_back(CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00005619 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005620 }
5621
5622 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
5623 if (!CCE->isListInitialization())
5624 return VisitExpr(CCE);
5625
5626 // In C++11, list initializations are sequenced.
5627 llvm::SmallVector<SequenceTree::Seq, 32> Elts;
5628 SequenceTree::Seq Parent = Region;
5629 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
5630 E = CCE->arg_end();
5631 I != E; ++I) {
5632 Region = Tree.allocate(Parent);
5633 Elts.push_back(Region);
5634 Visit(*I);
5635 }
5636
5637 // Forget that the initializers are sequenced.
5638 Region = Parent;
5639 for (unsigned I = 0; I < Elts.size(); ++I)
5640 Tree.merge(Elts[I]);
5641 }
5642
5643 void VisitInitListExpr(InitListExpr *ILE) {
5644 if (!SemaRef.getLangOpts().CPlusPlus11)
5645 return VisitExpr(ILE);
5646
5647 // In C++11, list initializations are sequenced.
5648 llvm::SmallVector<SequenceTree::Seq, 32> Elts;
5649 SequenceTree::Seq Parent = Region;
5650 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
5651 Expr *E = ILE->getInit(I);
5652 if (!E) continue;
5653 Region = Tree.allocate(Parent);
5654 Elts.push_back(Region);
5655 Visit(E);
5656 }
5657
5658 // Forget that the initializers are sequenced.
5659 Region = Parent;
5660 for (unsigned I = 0; I < Elts.size(); ++I)
5661 Tree.merge(Elts[I]);
5662 }
5663};
5664}
5665
5666void Sema::CheckUnsequencedOperations(Expr *E) {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005667 llvm::SmallVector<Expr*, 8> WorkList;
5668 WorkList.push_back(E);
5669 while (!WorkList.empty()) {
5670 Expr *Item = WorkList.back();
5671 WorkList.pop_back();
5672 SequenceChecker(*this, Item, WorkList);
5673 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005674}
5675
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005676void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
5677 bool IsConstexpr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005678 CheckImplicitConversions(E, CheckLoc);
5679 CheckUnsequencedOperations(E);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005680 if (!IsConstexpr && !E->isValueDependent())
5681 CheckForIntOverflow(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005682}
5683
John McCall15d7d122010-11-11 03:21:53 +00005684void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
5685 FieldDecl *BitField,
5686 Expr *Init) {
5687 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
5688}
5689
Mike Stumpf8c49212010-01-21 03:59:47 +00005690/// CheckParmsForFunctionDef - Check that the parameters of the given
5691/// function are appropriate for the definition of a function. This
5692/// takes care of any checks that cannot be performed on the
5693/// declaration itself, e.g., that the types of each of the function
5694/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00005695bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
5696 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005697 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00005698 for (; P != PEnd; ++P) {
5699 ParmVarDecl *Param = *P;
5700
Mike Stumpf8c49212010-01-21 03:59:47 +00005701 // C99 6.7.5.3p4: the parameters in a parameter type list in a
5702 // function declarator that is part of a function definition of
5703 // that function shall not have incomplete type.
5704 //
5705 // This is also C++ [dcl.fct]p6.
5706 if (!Param->isInvalidDecl() &&
5707 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00005708 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005709 Param->setInvalidDecl();
5710 HasInvalidParm = true;
5711 }
5712
5713 // C99 6.9.1p5: If the declarator includes a parameter type list, the
5714 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00005715 if (CheckParameterNames &&
5716 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00005717 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005718 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00005719 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00005720
5721 // C99 6.7.5.3p12:
5722 // If the function declarator is not part of a definition of that
5723 // function, parameters may have incomplete type and may use the [*]
5724 // notation in their sequences of declarator specifiers to specify
5725 // variable length array types.
5726 QualType PType = Param->getOriginalType();
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00005727 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigd17e3402010-02-01 05:02:49 +00005728 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitfc093362013-03-01 21:41:22 +00005729 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00005730 // information is added for it.
5731 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00005732 break;
Sam Weinigd17e3402010-02-01 05:02:49 +00005733 }
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00005734 PType= AT->getElementType();
Sam Weinigd17e3402010-02-01 05:02:49 +00005735 }
Mike Stumpf8c49212010-01-21 03:59:47 +00005736 }
5737
5738 return HasInvalidParm;
5739}
John McCallb7f4ffe2010-08-12 21:44:57 +00005740
5741/// CheckCastAlign - Implements -Wcast-align, which warns when a
5742/// pointer cast increases the alignment requirements.
5743void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
5744 // This is actually a lot of work to potentially be doing on every
5745 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005746 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
5747 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00005748 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00005749 return;
5750
5751 // Ignore dependent types.
5752 if (T->isDependentType() || Op->getType()->isDependentType())
5753 return;
5754
5755 // Require that the destination be a pointer type.
5756 const PointerType *DestPtr = T->getAs<PointerType>();
5757 if (!DestPtr) return;
5758
5759 // If the destination has alignment 1, we're done.
5760 QualType DestPointee = DestPtr->getPointeeType();
5761 if (DestPointee->isIncompleteType()) return;
5762 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
5763 if (DestAlign.isOne()) return;
5764
5765 // Require that the source be a pointer type.
5766 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
5767 if (!SrcPtr) return;
5768 QualType SrcPointee = SrcPtr->getPointeeType();
5769
5770 // Whitelist casts from cv void*. We already implicitly
5771 // whitelisted casts to cv void*, since they have alignment 1.
5772 // Also whitelist casts involving incomplete types, which implicitly
5773 // includes 'void'.
5774 if (SrcPointee->isIncompleteType()) return;
5775
5776 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
5777 if (SrcAlign >= DestAlign) return;
5778
5779 Diag(TRange.getBegin(), diag::warn_cast_align)
5780 << Op->getType() << T
5781 << static_cast<unsigned>(SrcAlign.getQuantity())
5782 << static_cast<unsigned>(DestAlign.getQuantity())
5783 << TRange << Op->getSourceRange();
5784}
5785
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005786static const Type* getElementType(const Expr *BaseExpr) {
5787 const Type* EltType = BaseExpr->getType().getTypePtr();
5788 if (EltType->isAnyPointerType())
5789 return EltType->getPointeeType().getTypePtr();
5790 else if (EltType->isArrayType())
5791 return EltType->getBaseElementTypeUnsafe();
5792 return EltType;
5793}
5794
Chandler Carruthc2684342011-08-05 09:10:50 +00005795/// \brief Check whether this array fits the idiom of a size-one tail padded
5796/// array member of a struct.
5797///
5798/// We avoid emitting out-of-bounds access warnings for such arrays as they are
5799/// commonly used to emulate flexible arrays in C89 code.
5800static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
5801 const NamedDecl *ND) {
5802 if (Size != 1 || !ND) return false;
5803
5804 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
5805 if (!FD) return false;
5806
5807 // Don't consider sizes resulting from macro expansions or template argument
5808 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00005809
5810 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005811 while (TInfo) {
5812 TypeLoc TL = TInfo->getTypeLoc();
5813 // Look through typedefs.
David Blaikie39e6ab42013-02-18 22:06:02 +00005814 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
5815 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005816 TInfo = TDL->getTypeSourceInfo();
5817 continue;
5818 }
David Blaikie39e6ab42013-02-18 22:06:02 +00005819 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
5820 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier5e253012013-02-06 00:58:34 +00005821 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
5822 return false;
5823 }
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005824 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00005825 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005826
5827 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00005828 if (!RD) return false;
5829 if (RD->isUnion()) return false;
5830 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
5831 if (!CRD->isStandardLayout()) return false;
5832 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005833
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00005834 // See if this is the last field decl in the record.
5835 const Decl *D = FD;
5836 while ((D = D->getNextDeclInContext()))
5837 if (isa<FieldDecl>(D))
5838 return false;
5839 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00005840}
5841
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005842void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005843 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00005844 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00005845 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005846 if (IndexExpr->isValueDependent())
5847 return;
5848
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00005849 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005850 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00005851 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005852 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00005853 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00005854 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00005855
Chandler Carruth34064582011-02-17 20:55:08 +00005856 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005857 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00005858 return;
Richard Smith25b009a2011-12-16 19:31:14 +00005859 if (IndexNegated)
5860 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00005861
Chandler Carruthba447122011-08-05 08:07:29 +00005862 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00005863 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5864 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00005865 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00005866 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00005867
Ted Kremenek9e060ca2011-02-23 23:06:04 +00005868 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00005869 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00005870 if (!size.isStrictlyPositive())
5871 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005872
5873 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00005874 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005875 // Make sure we're comparing apples to apples when comparing index to size
5876 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
5877 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00005878 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00005879 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005880 if (ptrarith_typesize != array_typesize) {
5881 // There's a cast to a different size type involved
5882 uint64_t ratio = array_typesize / ptrarith_typesize;
5883 // TODO: Be smarter about handling cases where array_typesize is not a
5884 // multiple of ptrarith_typesize
5885 if (ptrarith_typesize * ratio == array_typesize)
5886 size *= llvm::APInt(size.getBitWidth(), ratio);
5887 }
5888 }
5889
Chandler Carruth34064582011-02-17 20:55:08 +00005890 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005891 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005892 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005893 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005894
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005895 // For array subscripting the index must be less than size, but for pointer
5896 // arithmetic also allow the index (offset) to be equal to size since
5897 // computing the next address after the end of the array is legal and
5898 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00005899 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00005900 return;
5901
5902 // Also don't warn for arrays of size 1 which are members of some
5903 // structure. These are often used to approximate flexible arrays in C89
5904 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005905 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00005906 return;
Chandler Carruth34064582011-02-17 20:55:08 +00005907
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005908 // Suppress the warning if the subscript expression (as identified by the
5909 // ']' location) and the index expression are both from macro expansions
5910 // within a system header.
5911 if (ASE) {
5912 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
5913 ASE->getRBracketLoc());
5914 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
5915 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
5916 IndexExpr->getLocStart());
5917 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
5918 return;
5919 }
5920 }
5921
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005922 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005923 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005924 DiagID = diag::warn_array_index_exceeds_bounds;
5925
5926 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
5927 PDiag(DiagID) << index.toString(10, true)
5928 << size.toString(10, true)
5929 << (unsigned)size.getLimitedValue(~0U)
5930 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00005931 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005932 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005933 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005934 DiagID = diag::warn_ptr_arith_precedes_bounds;
5935 if (index.isNegative()) index = -index;
5936 }
5937
5938 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
5939 PDiag(DiagID) << index.toString(10, true)
5940 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00005941 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00005942
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00005943 if (!ND) {
5944 // Try harder to find a NamedDecl to point at in the note.
5945 while (const ArraySubscriptExpr *ASE =
5946 dyn_cast<ArraySubscriptExpr>(BaseExpr))
5947 BaseExpr = ASE->getBase()->IgnoreParenCasts();
5948 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5949 ND = dyn_cast<NamedDecl>(DRE->getDecl());
5950 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
5951 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
5952 }
5953
Chandler Carruth35001ca2011-02-17 21:10:52 +00005954 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005955 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
5956 PDiag(diag::note_array_index_out_of_bounds)
5957 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00005958}
5959
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005960void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005961 int AllowOnePastEnd = 0;
5962 while (expr) {
5963 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005964 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005965 case Stmt::ArraySubscriptExprClass: {
5966 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005967 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005968 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005969 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005970 }
5971 case Stmt::UnaryOperatorClass: {
5972 // Only unwrap the * and & unary operators
5973 const UnaryOperator *UO = cast<UnaryOperator>(expr);
5974 expr = UO->getSubExpr();
5975 switch (UO->getOpcode()) {
5976 case UO_AddrOf:
5977 AllowOnePastEnd++;
5978 break;
5979 case UO_Deref:
5980 AllowOnePastEnd--;
5981 break;
5982 default:
5983 return;
5984 }
5985 break;
5986 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005987 case Stmt::ConditionalOperatorClass: {
5988 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
5989 if (const Expr *lhs = cond->getLHS())
5990 CheckArrayAccess(lhs);
5991 if (const Expr *rhs = cond->getRHS())
5992 CheckArrayAccess(rhs);
5993 return;
5994 }
5995 default:
5996 return;
5997 }
Peter Collingbournef111d932011-04-15 00:35:48 +00005998 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005999}
John McCallf85e1932011-06-15 23:02:42 +00006000
6001//===--- CHECK: Objective-C retain cycles ----------------------------------//
6002
6003namespace {
6004 struct RetainCycleOwner {
6005 RetainCycleOwner() : Variable(0), Indirect(false) {}
6006 VarDecl *Variable;
6007 SourceRange Range;
6008 SourceLocation Loc;
6009 bool Indirect;
6010
6011 void setLocsFrom(Expr *e) {
6012 Loc = e->getExprLoc();
6013 Range = e->getSourceRange();
6014 }
6015 };
6016}
6017
6018/// Consider whether capturing the given variable can possibly lead to
6019/// a retain cycle.
6020static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00006021 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00006022 // lifetime. In MRR, it's captured strongly if the variable is
6023 // __block and has an appropriate type.
6024 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6025 return false;
6026
6027 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00006028 if (ref)
6029 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00006030 return true;
6031}
6032
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006033static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00006034 while (true) {
6035 e = e->IgnoreParens();
6036 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6037 switch (cast->getCastKind()) {
6038 case CK_BitCast:
6039 case CK_LValueBitCast:
6040 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00006041 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00006042 e = cast->getSubExpr();
6043 continue;
6044
John McCallf85e1932011-06-15 23:02:42 +00006045 default:
6046 return false;
6047 }
6048 }
6049
6050 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6051 ObjCIvarDecl *ivar = ref->getDecl();
6052 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6053 return false;
6054
6055 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006056 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006057 return false;
6058
6059 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6060 owner.Indirect = true;
6061 return true;
6062 }
6063
6064 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6065 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6066 if (!var) return false;
6067 return considerVariable(var, ref, owner);
6068 }
6069
John McCallf85e1932011-06-15 23:02:42 +00006070 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6071 if (member->isArrow()) return false;
6072
6073 // Don't count this as an indirect ownership.
6074 e = member->getBase();
6075 continue;
6076 }
6077
John McCall4b9c2d22011-11-06 09:01:30 +00006078 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6079 // Only pay attention to pseudo-objects on property references.
6080 ObjCPropertyRefExpr *pre
6081 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6082 ->IgnoreParens());
6083 if (!pre) return false;
6084 if (pre->isImplicitProperty()) return false;
6085 ObjCPropertyDecl *property = pre->getExplicitProperty();
6086 if (!property->isRetaining() &&
6087 !(property->getPropertyIvarDecl() &&
6088 property->getPropertyIvarDecl()->getType()
6089 .getObjCLifetime() == Qualifiers::OCL_Strong))
6090 return false;
6091
6092 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006093 if (pre->isSuperReceiver()) {
6094 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6095 if (!owner.Variable)
6096 return false;
6097 owner.Loc = pre->getLocation();
6098 owner.Range = pre->getSourceRange();
6099 return true;
6100 }
John McCall4b9c2d22011-11-06 09:01:30 +00006101 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6102 ->getSourceExpr());
6103 continue;
6104 }
6105
John McCallf85e1932011-06-15 23:02:42 +00006106 // Array ivars?
6107
6108 return false;
6109 }
6110}
6111
6112namespace {
6113 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6114 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6115 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6116 Variable(variable), Capturer(0) {}
6117
6118 VarDecl *Variable;
6119 Expr *Capturer;
6120
6121 void VisitDeclRefExpr(DeclRefExpr *ref) {
6122 if (ref->getDecl() == Variable && !Capturer)
6123 Capturer = ref;
6124 }
6125
John McCallf85e1932011-06-15 23:02:42 +00006126 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6127 if (Capturer) return;
6128 Visit(ref->getBase());
6129 if (Capturer && ref->isFreeIvar())
6130 Capturer = ref;
6131 }
6132
6133 void VisitBlockExpr(BlockExpr *block) {
6134 // Look inside nested blocks
6135 if (block->getBlockDecl()->capturesVariable(Variable))
6136 Visit(block->getBlockDecl()->getBody());
6137 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00006138
6139 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6140 if (Capturer) return;
6141 if (OVE->getSourceExpr())
6142 Visit(OVE->getSourceExpr());
6143 }
John McCallf85e1932011-06-15 23:02:42 +00006144 };
6145}
6146
6147/// Check whether the given argument is a block which captures a
6148/// variable.
6149static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6150 assert(owner.Variable && owner.Loc.isValid());
6151
6152 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00006153
6154 // Look through [^{...} copy] and Block_copy(^{...}).
6155 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6156 Selector Cmd = ME->getSelector();
6157 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6158 e = ME->getInstanceReceiver();
6159 if (!e)
6160 return 0;
6161 e = e->IgnoreParenCasts();
6162 }
6163 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6164 if (CE->getNumArgs() == 1) {
6165 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00006166 if (Fn) {
6167 const IdentifierInfo *FnI = Fn->getIdentifier();
6168 if (FnI && FnI->isStr("_Block_copy")) {
6169 e = CE->getArg(0)->IgnoreParenCasts();
6170 }
6171 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00006172 }
6173 }
6174
John McCallf85e1932011-06-15 23:02:42 +00006175 BlockExpr *block = dyn_cast<BlockExpr>(e);
6176 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6177 return 0;
6178
6179 FindCaptureVisitor visitor(S.Context, owner.Variable);
6180 visitor.Visit(block->getBlockDecl()->getBody());
6181 return visitor.Capturer;
6182}
6183
6184static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6185 RetainCycleOwner &owner) {
6186 assert(capturer);
6187 assert(owner.Variable && owner.Loc.isValid());
6188
6189 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6190 << owner.Variable << capturer->getSourceRange();
6191 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6192 << owner.Indirect << owner.Range;
6193}
6194
6195/// Check for a keyword selector that starts with the word 'add' or
6196/// 'set'.
6197static bool isSetterLikeSelector(Selector sel) {
6198 if (sel.isUnarySelector()) return false;
6199
Chris Lattner5f9e2722011-07-23 10:55:15 +00006200 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00006201 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006202 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00006203 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006204 else if (str.startswith("add")) {
6205 // Specially whitelist 'addOperationWithBlock:'.
6206 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6207 return false;
6208 str = str.substr(3);
6209 }
John McCallf85e1932011-06-15 23:02:42 +00006210 else
6211 return false;
6212
6213 if (str.empty()) return true;
Jordan Rose3f6f51e2013-02-08 22:30:41 +00006214 return !isLowercase(str.front());
John McCallf85e1932011-06-15 23:02:42 +00006215}
6216
6217/// Check a message send to see if it's likely to cause a retain cycle.
6218void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6219 // Only check instance methods whose selector looks like a setter.
6220 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6221 return;
6222
6223 // Try to find a variable that the receiver is strongly owned by.
6224 RetainCycleOwner owner;
6225 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006226 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006227 return;
6228 } else {
6229 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6230 owner.Variable = getCurMethodDecl()->getSelfDecl();
6231 owner.Loc = msg->getSuperLoc();
6232 owner.Range = msg->getSuperLoc();
6233 }
6234
6235 // Check whether the receiver is captured by any of the arguments.
6236 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6237 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6238 return diagnoseRetainCycle(*this, capturer, owner);
6239}
6240
6241/// Check a property assign to see if it's likely to cause a retain cycle.
6242void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6243 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006244 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00006245 return;
6246
6247 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6248 diagnoseRetainCycle(*this, capturer, owner);
6249}
6250
Jordan Rosee10f4d32012-09-15 02:48:31 +00006251void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6252 RetainCycleOwner Owner;
6253 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6254 return;
6255
6256 // Because we don't have an expression for the variable, we have to set the
6257 // location explicitly here.
6258 Owner.Loc = Var->getLocation();
6259 Owner.Range = Var->getSourceRange();
6260
6261 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6262 diagnoseRetainCycle(*this, Capturer, Owner);
6263}
6264
Ted Kremenek9d084012012-12-21 08:04:28 +00006265static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6266 Expr *RHS, bool isProperty) {
6267 // Check if RHS is an Objective-C object literal, which also can get
6268 // immediately zapped in a weak reference. Note that we explicitly
6269 // allow ObjCStringLiterals, since those are designed to never really die.
6270 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006271
Ted Kremenekd3292c82012-12-21 22:46:35 +00006272 // This enum needs to match with the 'select' in
6273 // warn_objc_arc_literal_assign (off-by-1).
6274 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6275 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6276 return false;
Ted Kremenekf530ff72012-12-21 21:59:39 +00006277
6278 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenekd3292c82012-12-21 22:46:35 +00006279 << (unsigned) Kind
Ted Kremenek9d084012012-12-21 08:04:28 +00006280 << (isProperty ? 0 : 1)
6281 << RHS->getSourceRange();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006282
6283 return true;
Ted Kremenek9d084012012-12-21 08:04:28 +00006284}
6285
Ted Kremenekb29b30f2012-12-21 19:45:30 +00006286static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6287 Qualifiers::ObjCLifetime LT,
6288 Expr *RHS, bool isProperty) {
6289 // Strip off any implicit cast added to get to the one ARC-specific.
6290 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6291 if (cast->getCastKind() == CK_ARCConsumeObject) {
6292 S.Diag(Loc, diag::warn_arc_retained_assign)
6293 << (LT == Qualifiers::OCL_ExplicitNone)
6294 << (isProperty ? 0 : 1)
6295 << RHS->getSourceRange();
6296 return true;
6297 }
6298 RHS = cast->getSubExpr();
6299 }
6300
6301 if (LT == Qualifiers::OCL_Weak &&
6302 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6303 return true;
6304
6305 return false;
6306}
6307
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006308bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6309 QualType LHS, Expr *RHS) {
6310 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6311
6312 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6313 return false;
6314
6315 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6316 return true;
6317
6318 return false;
6319}
6320
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006321void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6322 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006323 QualType LHSType;
6324 // PropertyRef on LHS type need be directly obtained from
6325 // its declaration as it has a PsuedoType.
6326 ObjCPropertyRefExpr *PRE
6327 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6328 if (PRE && !PRE->isImplicitProperty()) {
6329 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6330 if (PD)
6331 LHSType = PD->getType();
6332 }
6333
6334 if (LHSType.isNull())
6335 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00006336
6337 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6338
6339 if (LT == Qualifiers::OCL_Weak) {
6340 DiagnosticsEngine::Level Level =
6341 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6342 if (Level != DiagnosticsEngine::Ignored)
6343 getCurFunction()->markSafeWeakUse(LHS);
6344 }
6345
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006346 if (checkUnsafeAssigns(Loc, LHSType, RHS))
6347 return;
Jordan Rose7a270482012-09-28 22:21:35 +00006348
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006349 // FIXME. Check for other life times.
6350 if (LT != Qualifiers::OCL_None)
6351 return;
6352
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006353 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006354 if (PRE->isImplicitProperty())
6355 return;
6356 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6357 if (!PD)
6358 return;
6359
Bill Wendlingad017fa2012-12-20 19:22:21 +00006360 unsigned Attributes = PD->getPropertyAttributes();
6361 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006362 // when 'assign' attribute was not explicitly specified
6363 // by user, ignore it and rely on property type itself
6364 // for lifetime info.
6365 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6366 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6367 LHSType->isObjCRetainableType())
6368 return;
6369
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006370 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00006371 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006372 Diag(Loc, diag::warn_arc_retained_property_assign)
6373 << RHS->getSourceRange();
6374 return;
6375 }
6376 RHS = cast->getSubExpr();
6377 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006378 }
Bill Wendlingad017fa2012-12-20 19:22:21 +00006379 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006380 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6381 return;
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00006382 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006383 }
6384}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00006385
6386//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6387
6388namespace {
6389bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6390 SourceLocation StmtLoc,
6391 const NullStmt *Body) {
6392 // Do not warn if the body is a macro that expands to nothing, e.g:
6393 //
6394 // #define CALL(x)
6395 // if (condition)
6396 // CALL(0);
6397 //
6398 if (Body->hasLeadingEmptyMacro())
6399 return false;
6400
6401 // Get line numbers of statement and body.
6402 bool StmtLineInvalid;
6403 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6404 &StmtLineInvalid);
6405 if (StmtLineInvalid)
6406 return false;
6407
6408 bool BodyLineInvalid;
6409 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
6410 &BodyLineInvalid);
6411 if (BodyLineInvalid)
6412 return false;
6413
6414 // Warn if null statement and body are on the same line.
6415 if (StmtLine != BodyLine)
6416 return false;
6417
6418 return true;
6419}
6420} // Unnamed namespace
6421
6422void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
6423 const Stmt *Body,
6424 unsigned DiagID) {
6425 // Since this is a syntactic check, don't emit diagnostic for template
6426 // instantiations, this just adds noise.
6427 if (CurrentInstantiationScope)
6428 return;
6429
6430 // The body should be a null statement.
6431 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6432 if (!NBody)
6433 return;
6434
6435 // Do the usual checks.
6436 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6437 return;
6438
6439 Diag(NBody->getSemiLoc(), DiagID);
6440 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6441}
6442
6443void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
6444 const Stmt *PossibleBody) {
6445 assert(!CurrentInstantiationScope); // Ensured by caller
6446
6447 SourceLocation StmtLoc;
6448 const Stmt *Body;
6449 unsigned DiagID;
6450 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
6451 StmtLoc = FS->getRParenLoc();
6452 Body = FS->getBody();
6453 DiagID = diag::warn_empty_for_body;
6454 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
6455 StmtLoc = WS->getCond()->getSourceRange().getEnd();
6456 Body = WS->getBody();
6457 DiagID = diag::warn_empty_while_body;
6458 } else
6459 return; // Neither `for' nor `while'.
6460
6461 // The body should be a null statement.
6462 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6463 if (!NBody)
6464 return;
6465
6466 // Skip expensive checks if diagnostic is disabled.
6467 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
6468 DiagnosticsEngine::Ignored)
6469 return;
6470
6471 // Do the usual checks.
6472 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6473 return;
6474
6475 // `for(...);' and `while(...);' are popular idioms, so in order to keep
6476 // noise level low, emit diagnostics only if for/while is followed by a
6477 // CompoundStmt, e.g.:
6478 // for (int i = 0; i < n; i++);
6479 // {
6480 // a(i);
6481 // }
6482 // or if for/while is followed by a statement with more indentation
6483 // than for/while itself:
6484 // for (int i = 0; i < n; i++);
6485 // a(i);
6486 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
6487 if (!ProbableTypo) {
6488 bool BodyColInvalid;
6489 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
6490 PossibleBody->getLocStart(),
6491 &BodyColInvalid);
6492 if (BodyColInvalid)
6493 return;
6494
6495 bool StmtColInvalid;
6496 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
6497 S->getLocStart(),
6498 &StmtColInvalid);
6499 if (StmtColInvalid)
6500 return;
6501
6502 if (BodyCol > StmtCol)
6503 ProbableTypo = true;
6504 }
6505
6506 if (ProbableTypo) {
6507 Diag(NBody->getSemiLoc(), DiagID);
6508 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6509 }
6510}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006511
6512//===--- Layout compatibility ----------------------------------------------//
6513
6514namespace {
6515
6516bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
6517
6518/// \brief Check if two enumeration types are layout-compatible.
6519bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
6520 // C++11 [dcl.enum] p8:
6521 // Two enumeration types are layout-compatible if they have the same
6522 // underlying type.
6523 return ED1->isComplete() && ED2->isComplete() &&
6524 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
6525}
6526
6527/// \brief Check if two fields are layout-compatible.
6528bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
6529 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
6530 return false;
6531
6532 if (Field1->isBitField() != Field2->isBitField())
6533 return false;
6534
6535 if (Field1->isBitField()) {
6536 // Make sure that the bit-fields are the same length.
6537 unsigned Bits1 = Field1->getBitWidthValue(C);
6538 unsigned Bits2 = Field2->getBitWidthValue(C);
6539
6540 if (Bits1 != Bits2)
6541 return false;
6542 }
6543
6544 return true;
6545}
6546
6547/// \brief Check if two standard-layout structs are layout-compatible.
6548/// (C++11 [class.mem] p17)
6549bool isLayoutCompatibleStruct(ASTContext &C,
6550 RecordDecl *RD1,
6551 RecordDecl *RD2) {
6552 // If both records are C++ classes, check that base classes match.
6553 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
6554 // If one of records is a CXXRecordDecl we are in C++ mode,
6555 // thus the other one is a CXXRecordDecl, too.
6556 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
6557 // Check number of base classes.
6558 if (D1CXX->getNumBases() != D2CXX->getNumBases())
6559 return false;
6560
6561 // Check the base classes.
6562 for (CXXRecordDecl::base_class_const_iterator
6563 Base1 = D1CXX->bases_begin(),
6564 BaseEnd1 = D1CXX->bases_end(),
6565 Base2 = D2CXX->bases_begin();
6566 Base1 != BaseEnd1;
6567 ++Base1, ++Base2) {
6568 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
6569 return false;
6570 }
6571 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
6572 // If only RD2 is a C++ class, it should have zero base classes.
6573 if (D2CXX->getNumBases() > 0)
6574 return false;
6575 }
6576
6577 // Check the fields.
6578 RecordDecl::field_iterator Field2 = RD2->field_begin(),
6579 Field2End = RD2->field_end(),
6580 Field1 = RD1->field_begin(),
6581 Field1End = RD1->field_end();
6582 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
6583 if (!isLayoutCompatible(C, *Field1, *Field2))
6584 return false;
6585 }
6586 if (Field1 != Field1End || Field2 != Field2End)
6587 return false;
6588
6589 return true;
6590}
6591
6592/// \brief Check if two standard-layout unions are layout-compatible.
6593/// (C++11 [class.mem] p18)
6594bool isLayoutCompatibleUnion(ASTContext &C,
6595 RecordDecl *RD1,
6596 RecordDecl *RD2) {
6597 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
6598 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
6599 Field2End = RD2->field_end();
6600 Field2 != Field2End; ++Field2) {
6601 UnmatchedFields.insert(*Field2);
6602 }
6603
6604 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
6605 Field1End = RD1->field_end();
6606 Field1 != Field1End; ++Field1) {
6607 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
6608 I = UnmatchedFields.begin(),
6609 E = UnmatchedFields.end();
6610
6611 for ( ; I != E; ++I) {
6612 if (isLayoutCompatible(C, *Field1, *I)) {
6613 bool Result = UnmatchedFields.erase(*I);
6614 (void) Result;
6615 assert(Result);
6616 break;
6617 }
6618 }
6619 if (I == E)
6620 return false;
6621 }
6622
6623 return UnmatchedFields.empty();
6624}
6625
6626bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
6627 if (RD1->isUnion() != RD2->isUnion())
6628 return false;
6629
6630 if (RD1->isUnion())
6631 return isLayoutCompatibleUnion(C, RD1, RD2);
6632 else
6633 return isLayoutCompatibleStruct(C, RD1, RD2);
6634}
6635
6636/// \brief Check if two types are layout-compatible in C++11 sense.
6637bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
6638 if (T1.isNull() || T2.isNull())
6639 return false;
6640
6641 // C++11 [basic.types] p11:
6642 // If two types T1 and T2 are the same type, then T1 and T2 are
6643 // layout-compatible types.
6644 if (C.hasSameType(T1, T2))
6645 return true;
6646
6647 T1 = T1.getCanonicalType().getUnqualifiedType();
6648 T2 = T2.getCanonicalType().getUnqualifiedType();
6649
6650 const Type::TypeClass TC1 = T1->getTypeClass();
6651 const Type::TypeClass TC2 = T2->getTypeClass();
6652
6653 if (TC1 != TC2)
6654 return false;
6655
6656 if (TC1 == Type::Enum) {
6657 return isLayoutCompatible(C,
6658 cast<EnumType>(T1)->getDecl(),
6659 cast<EnumType>(T2)->getDecl());
6660 } else if (TC1 == Type::Record) {
6661 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
6662 return false;
6663
6664 return isLayoutCompatible(C,
6665 cast<RecordType>(T1)->getDecl(),
6666 cast<RecordType>(T2)->getDecl());
6667 }
6668
6669 return false;
6670}
6671}
6672
6673//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
6674
6675namespace {
6676/// \brief Given a type tag expression find the type tag itself.
6677///
6678/// \param TypeExpr Type tag expression, as it appears in user's code.
6679///
6680/// \param VD Declaration of an identifier that appears in a type tag.
6681///
6682/// \param MagicValue Type tag magic value.
6683bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
6684 const ValueDecl **VD, uint64_t *MagicValue) {
6685 while(true) {
6686 if (!TypeExpr)
6687 return false;
6688
6689 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
6690
6691 switch (TypeExpr->getStmtClass()) {
6692 case Stmt::UnaryOperatorClass: {
6693 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
6694 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
6695 TypeExpr = UO->getSubExpr();
6696 continue;
6697 }
6698 return false;
6699 }
6700
6701 case Stmt::DeclRefExprClass: {
6702 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
6703 *VD = DRE->getDecl();
6704 return true;
6705 }
6706
6707 case Stmt::IntegerLiteralClass: {
6708 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
6709 llvm::APInt MagicValueAPInt = IL->getValue();
6710 if (MagicValueAPInt.getActiveBits() <= 64) {
6711 *MagicValue = MagicValueAPInt.getZExtValue();
6712 return true;
6713 } else
6714 return false;
6715 }
6716
6717 case Stmt::BinaryConditionalOperatorClass:
6718 case Stmt::ConditionalOperatorClass: {
6719 const AbstractConditionalOperator *ACO =
6720 cast<AbstractConditionalOperator>(TypeExpr);
6721 bool Result;
6722 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
6723 if (Result)
6724 TypeExpr = ACO->getTrueExpr();
6725 else
6726 TypeExpr = ACO->getFalseExpr();
6727 continue;
6728 }
6729 return false;
6730 }
6731
6732 case Stmt::BinaryOperatorClass: {
6733 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
6734 if (BO->getOpcode() == BO_Comma) {
6735 TypeExpr = BO->getRHS();
6736 continue;
6737 }
6738 return false;
6739 }
6740
6741 default:
6742 return false;
6743 }
6744 }
6745}
6746
6747/// \brief Retrieve the C type corresponding to type tag TypeExpr.
6748///
6749/// \param TypeExpr Expression that specifies a type tag.
6750///
6751/// \param MagicValues Registered magic values.
6752///
6753/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
6754/// kind.
6755///
6756/// \param TypeInfo Information about the corresponding C type.
6757///
6758/// \returns true if the corresponding C type was found.
6759bool GetMatchingCType(
6760 const IdentifierInfo *ArgumentKind,
6761 const Expr *TypeExpr, const ASTContext &Ctx,
6762 const llvm::DenseMap<Sema::TypeTagMagicValue,
6763 Sema::TypeTagData> *MagicValues,
6764 bool &FoundWrongKind,
6765 Sema::TypeTagData &TypeInfo) {
6766 FoundWrongKind = false;
6767
6768 // Variable declaration that has type_tag_for_datatype attribute.
6769 const ValueDecl *VD = NULL;
6770
6771 uint64_t MagicValue;
6772
6773 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
6774 return false;
6775
6776 if (VD) {
6777 for (specific_attr_iterator<TypeTagForDatatypeAttr>
6778 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
6779 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
6780 I != E; ++I) {
6781 if (I->getArgumentKind() != ArgumentKind) {
6782 FoundWrongKind = true;
6783 return false;
6784 }
6785 TypeInfo.Type = I->getMatchingCType();
6786 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
6787 TypeInfo.MustBeNull = I->getMustBeNull();
6788 return true;
6789 }
6790 return false;
6791 }
6792
6793 if (!MagicValues)
6794 return false;
6795
6796 llvm::DenseMap<Sema::TypeTagMagicValue,
6797 Sema::TypeTagData>::const_iterator I =
6798 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
6799 if (I == MagicValues->end())
6800 return false;
6801
6802 TypeInfo = I->second;
6803 return true;
6804}
6805} // unnamed namespace
6806
6807void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
6808 uint64_t MagicValue, QualType Type,
6809 bool LayoutCompatible,
6810 bool MustBeNull) {
6811 if (!TypeTagForDatatypeMagicValues)
6812 TypeTagForDatatypeMagicValues.reset(
6813 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
6814
6815 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
6816 (*TypeTagForDatatypeMagicValues)[Magic] =
6817 TypeTagData(Type, LayoutCompatible, MustBeNull);
6818}
6819
6820namespace {
6821bool IsSameCharType(QualType T1, QualType T2) {
6822 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
6823 if (!BT1)
6824 return false;
6825
6826 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
6827 if (!BT2)
6828 return false;
6829
6830 BuiltinType::Kind T1Kind = BT1->getKind();
6831 BuiltinType::Kind T2Kind = BT2->getKind();
6832
6833 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
6834 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
6835 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
6836 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
6837}
6838} // unnamed namespace
6839
6840void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
6841 const Expr * const *ExprArgs) {
6842 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
6843 bool IsPointerAttr = Attr->getIsPointer();
6844
6845 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
6846 bool FoundWrongKind;
6847 TypeTagData TypeInfo;
6848 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
6849 TypeTagForDatatypeMagicValues.get(),
6850 FoundWrongKind, TypeInfo)) {
6851 if (FoundWrongKind)
6852 Diag(TypeTagExpr->getExprLoc(),
6853 diag::warn_type_tag_for_datatype_wrong_kind)
6854 << TypeTagExpr->getSourceRange();
6855 return;
6856 }
6857
6858 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
6859 if (IsPointerAttr) {
6860 // Skip implicit cast of pointer to `void *' (as a function argument).
6861 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5a249802012-11-03 16:07:49 +00006862 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkob57ce4e2012-11-03 22:10:18 +00006863 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006864 ArgumentExpr = ICE->getSubExpr();
6865 }
6866 QualType ArgumentType = ArgumentExpr->getType();
6867
6868 // Passing a `void*' pointer shouldn't trigger a warning.
6869 if (IsPointerAttr && ArgumentType->isVoidPointerType())
6870 return;
6871
6872 if (TypeInfo.MustBeNull) {
6873 // Type tag with matching void type requires a null pointer.
6874 if (!ArgumentExpr->isNullPointerConstant(Context,
6875 Expr::NPC_ValueDependentIsNotNull)) {
6876 Diag(ArgumentExpr->getExprLoc(),
6877 diag::warn_type_safety_null_pointer_required)
6878 << ArgumentKind->getName()
6879 << ArgumentExpr->getSourceRange()
6880 << TypeTagExpr->getSourceRange();
6881 }
6882 return;
6883 }
6884
6885 QualType RequiredType = TypeInfo.Type;
6886 if (IsPointerAttr)
6887 RequiredType = Context.getPointerType(RequiredType);
6888
6889 bool mismatch = false;
6890 if (!TypeInfo.LayoutCompatible) {
6891 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
6892
6893 // C++11 [basic.fundamental] p1:
6894 // Plain char, signed char, and unsigned char are three distinct types.
6895 //
6896 // But we treat plain `char' as equivalent to `signed char' or `unsigned
6897 // char' depending on the current char signedness mode.
6898 if (mismatch)
6899 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
6900 RequiredType->getPointeeType())) ||
6901 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
6902 mismatch = false;
6903 } else
6904 if (IsPointerAttr)
6905 mismatch = !isLayoutCompatible(Context,
6906 ArgumentType->getPointeeType(),
6907 RequiredType->getPointeeType());
6908 else
6909 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
6910
6911 if (mismatch)
6912 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
6913 << ArgumentType << ArgumentKind->getName()
6914 << TypeInfo.LayoutCompatible << RequiredType
6915 << ArgumentExpr->getSourceRange()
6916 << TypeTagExpr->getSourceRange();
6917}