blob: e14635ee25d8cc658638f077543bf958d06d37d5 [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
Anders Carlsson88cf2262008-02-11 04:20:54 +00001358 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1359 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001360 // FIXME: This isn't correct for methods (results in bogus warning).
1361 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001362 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001363 if (CurBlock)
1364 LastArg = *(CurBlock->TheDecl->param_end()-1);
1365 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001366 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001367 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001368 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001369 SecondArgIsLastNamedArgument = PV == LastArg;
1370 }
1371 }
Mike Stump1eb44332009-09-09 15:08:12 +00001372
Chris Lattner30ce3442007-12-19 23:59:04 +00001373 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001374 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001375 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1376 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001377}
Chris Lattner30ce3442007-12-19 23:59:04 +00001378
Chris Lattner1b9a0792007-12-20 00:26:33 +00001379/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1380/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001381bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1382 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001383 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001384 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001385 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001386 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001387 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001388 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001389 << SourceRange(TheCall->getArg(2)->getLocStart(),
1390 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001391
John Wiegley429bb272011-04-08 18:41:53 +00001392 ExprResult OrigArg0 = TheCall->getArg(0);
1393 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001394
Chris Lattner1b9a0792007-12-20 00:26:33 +00001395 // Do standard promotions between the two arguments, returning their common
1396 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001397 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001398 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1399 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001400
1401 // Make sure any conversions are pushed back into the call; this is
1402 // type safe since unordered compare builtins are declared as "_Bool
1403 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001404 TheCall->setArg(0, OrigArg0.get());
1405 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001406
John Wiegley429bb272011-04-08 18:41:53 +00001407 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001408 return false;
1409
Chris Lattner1b9a0792007-12-20 00:26:33 +00001410 // If the common type isn't a real floating type, then the arguments were
1411 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001412 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001413 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001414 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001415 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1416 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001417
Chris Lattner1b9a0792007-12-20 00:26:33 +00001418 return false;
1419}
1420
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001421/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1422/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001423/// to check everything. We expect the last argument to be a floating point
1424/// value.
1425bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1426 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001427 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001428 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001429 if (TheCall->getNumArgs() > NumArgs)
1430 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001431 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001432 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001433 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001434 (*(TheCall->arg_end()-1))->getLocEnd());
1435
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001436 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001437
Eli Friedman9ac6f622009-08-31 20:06:00 +00001438 if (OrigArg->isTypeDependent())
1439 return false;
1440
Chris Lattner81368fb2010-05-06 05:50:07 +00001441 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001442 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001443 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001444 diag::err_typecheck_call_invalid_unary_fp)
1445 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001446
Chris Lattner81368fb2010-05-06 05:50:07 +00001447 // If this is an implicit conversion from float -> double, remove it.
1448 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1449 Expr *CastArg = Cast->getSubExpr();
1450 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1451 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1452 "promotion from float to double is the only expected cast here");
1453 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001454 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001455 }
1456 }
1457
Eli Friedman9ac6f622009-08-31 20:06:00 +00001458 return false;
1459}
1460
Eli Friedmand38617c2008-05-14 19:38:39 +00001461/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1462// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001463ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001464 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001465 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001466 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001467 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001468 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001469
Nate Begeman37b6a572010-06-08 00:16:34 +00001470 // Determine which of the following types of shufflevector we're checking:
1471 // 1) unary, vector mask: (lhs, mask)
1472 // 2) binary, vector mask: (lhs, rhs, mask)
1473 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1474 QualType resType = TheCall->getArg(0)->getType();
1475 unsigned numElements = 0;
1476
Douglas Gregorcde01732009-05-19 22:10:17 +00001477 if (!TheCall->getArg(0)->isTypeDependent() &&
1478 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001479 QualType LHSType = TheCall->getArg(0)->getType();
1480 QualType RHSType = TheCall->getArg(1)->getType();
1481
1482 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001483 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001484 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001485 TheCall->getArg(1)->getLocEnd());
1486 return ExprError();
1487 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001488
1489 numElements = LHSType->getAs<VectorType>()->getNumElements();
1490 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001491
Nate Begeman37b6a572010-06-08 00:16:34 +00001492 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1493 // with mask. If so, verify that RHS is an integer vector type with the
1494 // same number of elts as lhs.
1495 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001496 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001497 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1498 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1499 << SourceRange(TheCall->getArg(1)->getLocStart(),
1500 TheCall->getArg(1)->getLocEnd());
1501 numResElements = numElements;
1502 }
1503 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001504 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001505 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001506 TheCall->getArg(1)->getLocEnd());
1507 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001508 } else if (numElements != numResElements) {
1509 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001510 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001511 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001512 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001513 }
1514
1515 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001516 if (TheCall->getArg(i)->isTypeDependent() ||
1517 TheCall->getArg(i)->isValueDependent())
1518 continue;
1519
Nate Begeman37b6a572010-06-08 00:16:34 +00001520 llvm::APSInt Result(32);
1521 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1522 return ExprError(Diag(TheCall->getLocStart(),
1523 diag::err_shufflevector_nonconstant_argument)
1524 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001525
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001526 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001527 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001528 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001529 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001530 }
1531
Chris Lattner5f9e2722011-07-23 10:55:15 +00001532 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001533
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001534 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001535 exprs.push_back(TheCall->getArg(i));
1536 TheCall->setArg(i, 0);
1537 }
1538
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001539 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001540 TheCall->getCallee()->getLocStart(),
1541 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001542}
Chris Lattner30ce3442007-12-19 23:59:04 +00001543
Daniel Dunbar4493f792008-07-21 22:59:13 +00001544/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1545// This is declared to take (const void*, ...) and can take two
1546// optional constant int args.
1547bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001548 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001549
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001550 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001551 return Diag(TheCall->getLocEnd(),
1552 diag::err_typecheck_call_too_many_args_at_most)
1553 << 0 /*function call*/ << 3 << NumArgs
1554 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001555
1556 // Argument 0 is checked for us and the remaining arguments must be
1557 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001558 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001559 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001560
1561 // We can't check the value of a dependent argument.
1562 if (Arg->isTypeDependent() || Arg->isValueDependent())
1563 continue;
1564
Eli Friedman9aef7262009-12-04 00:30:06 +00001565 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001566 if (SemaBuiltinConstantArg(TheCall, i, Result))
1567 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001568
Daniel Dunbar4493f792008-07-21 22:59:13 +00001569 // FIXME: gcc issues a warning and rewrites these to 0. These
1570 // seems especially odd for the third argument since the default
1571 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001572 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001573 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001574 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001575 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001576 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001577 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001578 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001579 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001580 }
1581 }
1582
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001583 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001584}
1585
Eric Christopher691ebc32010-04-17 02:26:23 +00001586/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1587/// TheCall is a constant expression.
1588bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1589 llvm::APSInt &Result) {
1590 Expr *Arg = TheCall->getArg(ArgNum);
1591 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1592 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1593
1594 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1595
1596 if (!Arg->isIntegerConstantExpr(Result, Context))
1597 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001598 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001599
Chris Lattner21fb98e2009-09-23 06:06:36 +00001600 return false;
1601}
1602
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001603/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1604/// int type). This simply type checks that type is one of the defined
1605/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001606// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001607bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001608 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001609
1610 // We can't check the value of a dependent argument.
1611 if (TheCall->getArg(1)->isTypeDependent() ||
1612 TheCall->getArg(1)->isValueDependent())
1613 return false;
1614
Eric Christopher691ebc32010-04-17 02:26:23 +00001615 // Check constant-ness first.
1616 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1617 return true;
1618
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001619 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001620 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001621 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1622 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001623 }
1624
1625 return false;
1626}
1627
Eli Friedman586d6a82009-05-03 06:04:26 +00001628/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001629/// This checks that val is a constant 1.
1630bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1631 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001632 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001633
Eric Christopher691ebc32010-04-17 02:26:23 +00001634 // TODO: This is less than ideal. Overload this to take a value.
1635 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1636 return true;
1637
1638 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001639 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1640 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1641
1642 return false;
1643}
1644
Richard Smith831421f2012-06-25 20:30:08 +00001645// Determine if an expression is a string literal or constant string.
1646// If this function returns false on the arguments to a function expecting a
1647// format string, we will usually need to emit a warning.
1648// True string literals are then checked by CheckFormatString.
1649Sema::StringLiteralCheckType
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001650Sema::checkFormatStringExpr(const Expr *E, ArrayRef<const Expr *> Args,
1651 bool HasVAListArg,
Richard Smith831421f2012-06-25 20:30:08 +00001652 unsigned format_idx, unsigned firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001653 FormatStringType Type, VariadicCallType CallType,
1654 bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001655 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001656 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001657 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001658
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001659 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001660
David Blaikiea73cdcb2012-02-10 21:07:25 +00001661 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1662 // Technically -Wformat-nonliteral does not warn about this case.
1663 // The behavior of printf and friends in this case is implementation
1664 // dependent. Ideally if the format string cannot be null then
1665 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith831421f2012-06-25 20:30:08 +00001666 return SLCT_CheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001667
Ted Kremenekd30ef872009-01-12 23:09:09 +00001668 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001669 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001670 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001671 // The expression is a literal if both sub-expressions were, and it was
1672 // completely checked only if both sub-expressions were checked.
1673 const AbstractConditionalOperator *C =
1674 cast<AbstractConditionalOperator>(E);
1675 StringLiteralCheckType Left =
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001676 checkFormatStringExpr(C->getTrueExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001677 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001678 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001679 if (Left == SLCT_NotALiteral)
1680 return SLCT_NotALiteral;
1681 StringLiteralCheckType Right =
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001682 checkFormatStringExpr(C->getFalseExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001683 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001684 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001685 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001686 }
1687
1688 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001689 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1690 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001691 }
1692
John McCall56ca35d2011-02-17 10:25:35 +00001693 case Stmt::OpaqueValueExprClass:
1694 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1695 E = src;
1696 goto tryAgain;
1697 }
Richard Smith831421f2012-06-25 20:30:08 +00001698 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00001699
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001700 case Stmt::PredefinedExprClass:
1701 // While __func__, etc., are technically not string literals, they
1702 // cannot contain format specifiers and thus are not a security
1703 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00001704 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001705
Ted Kremenek082d9362009-03-20 21:35:28 +00001706 case Stmt::DeclRefExprClass: {
1707 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001708
Ted Kremenek082d9362009-03-20 21:35:28 +00001709 // As an exception, do not flag errors for variables binding to
1710 // const string literals.
1711 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1712 bool isConstant = false;
1713 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001714
Ted Kremenek082d9362009-03-20 21:35:28 +00001715 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1716 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001717 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001718 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001719 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001720 } else if (T->isObjCObjectPointerType()) {
1721 // In ObjC, there is usually no "const ObjectPointer" type,
1722 // so don't check if the pointee type is constant.
1723 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001724 }
Mike Stump1eb44332009-09-09 15:08:12 +00001725
Ted Kremenek082d9362009-03-20 21:35:28 +00001726 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001727 if (const Expr *Init = VD->getAnyInitializer()) {
1728 // Look through initializers like const char c[] = { "foo" }
1729 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
1730 if (InitList->isStringLiteralInit())
1731 Init = InitList->getInit(0)->IgnoreParenImpCasts();
1732 }
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001733 return checkFormatStringExpr(Init, Args,
Richard Smith831421f2012-06-25 20:30:08 +00001734 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001735 firstDataArg, Type, CallType,
Richard Smith831421f2012-06-25 20:30:08 +00001736 /*inFunctionCall*/false);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001737 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001738 }
Mike Stump1eb44332009-09-09 15:08:12 +00001739
Anders Carlssond966a552009-06-28 19:55:58 +00001740 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1741 // special check to see if the format string is a function parameter
1742 // of the function calling the printf function. If the function
1743 // has an attribute indicating it is a printf-like function, then we
1744 // should suppress warnings concerning non-literals being used in a call
1745 // to a vprintf function. For example:
1746 //
1747 // void
1748 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1749 // va_list ap;
1750 // va_start(ap, fmt);
1751 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1752 // ...
1753 //
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001754 if (HasVAListArg) {
1755 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1756 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1757 int PVIndex = PV->getFunctionScopeIndex() + 1;
1758 for (specific_attr_iterator<FormatAttr>
1759 i = ND->specific_attr_begin<FormatAttr>(),
1760 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1761 FormatAttr *PVFormat = *i;
1762 // adjust for implicit parameter
1763 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1764 if (MD->isInstance())
1765 ++PVIndex;
1766 // We also check if the formats are compatible.
1767 // We can't pass a 'scanf' string to a 'printf' function.
1768 if (PVIndex == PVFormat->getFormatIdx() &&
1769 Type == GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00001770 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001771 }
1772 }
1773 }
1774 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001775 }
Mike Stump1eb44332009-09-09 15:08:12 +00001776
Richard Smith831421f2012-06-25 20:30:08 +00001777 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00001778 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001779
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001780 case Stmt::CallExprClass:
1781 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001782 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001783 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1784 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1785 unsigned ArgIndex = FA->getFormatIdx();
1786 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1787 if (MD->isInstance())
1788 --ArgIndex;
1789 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001790
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001791 return checkFormatStringExpr(Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00001792 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001793 Type, CallType, inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001794 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1795 unsigned BuiltinID = FD->getBuiltinID();
1796 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
1797 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
1798 const Expr *Arg = CE->getArg(0);
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001799 return checkFormatStringExpr(Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00001800 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001801 firstDataArg, Type, CallType,
1802 inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001803 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00001804 }
1805 }
Mike Stump1eb44332009-09-09 15:08:12 +00001806
Richard Smith831421f2012-06-25 20:30:08 +00001807 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00001808 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001809 case Stmt::ObjCStringLiteralClass:
1810 case Stmt::StringLiteralClass: {
1811 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001812
Ted Kremenek082d9362009-03-20 21:35:28 +00001813 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001814 StrE = ObjCFExpr->getString();
1815 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001816 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001817
Ted Kremenekd30ef872009-01-12 23:09:09 +00001818 if (StrE) {
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001819 CheckFormatString(StrE, E, Args, HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001820 firstDataArg, Type, inFunctionCall, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001821 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001822 }
Mike Stump1eb44332009-09-09 15:08:12 +00001823
Richard Smith831421f2012-06-25 20:30:08 +00001824 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001825 }
Mike Stump1eb44332009-09-09 15:08:12 +00001826
Ted Kremenek082d9362009-03-20 21:35:28 +00001827 default:
Richard Smith831421f2012-06-25 20:30:08 +00001828 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001829 }
1830}
1831
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001832void
Mike Stump1eb44332009-09-09 15:08:12 +00001833Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001834 const Expr * const *ExprArgs,
1835 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001836 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1837 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001838 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001839 const Expr *ArgExpr = ExprArgs[*i];
Nick Lewycky3edf3872013-01-23 05:08:29 +00001840
1841 // As a special case, transparent unions initialized with zero are
1842 // considered null for the purposes of the nonnull attribute.
1843 if (const RecordType *UT = ArgExpr->getType()->getAsUnionType()) {
1844 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1845 if (const CompoundLiteralExpr *CLE =
1846 dyn_cast<CompoundLiteralExpr>(ArgExpr))
1847 if (const InitListExpr *ILE =
1848 dyn_cast<InitListExpr>(CLE->getInitializer()))
1849 ArgExpr = ILE->getInit(0);
1850 }
1851
1852 bool Result;
1853 if (ArgExpr->EvaluateAsBooleanCondition(Result, Context) && !Result)
Nick Lewycky909a70d2011-03-25 01:44:32 +00001854 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001855 }
1856}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001857
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001858Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1859 return llvm::StringSwitch<FormatStringType>(Format->getType())
1860 .Case("scanf", FST_Scanf)
1861 .Cases("printf", "printf0", FST_Printf)
1862 .Cases("NSString", "CFString", FST_NSString)
1863 .Case("strftime", FST_Strftime)
1864 .Case("strfmon", FST_Strfmon)
1865 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1866 .Default(FST_Unknown);
1867}
1868
Jordan Roseddcfbc92012-07-19 18:10:23 +00001869/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00001870/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00001871/// Returns true if a format string has been fully checked.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001872bool Sema::CheckFormatArguments(const FormatAttr *Format,
1873 ArrayRef<const Expr *> Args,
1874 bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001875 VariadicCallType CallType,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001876 SourceLocation Loc, SourceRange Range) {
Richard Smith831421f2012-06-25 20:30:08 +00001877 FormatStringInfo FSI;
1878 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001879 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith831421f2012-06-25 20:30:08 +00001880 FSI.FirstDataArg, GetFormatStringType(Format),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001881 CallType, Loc, Range);
Richard Smith831421f2012-06-25 20:30:08 +00001882 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001883}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001884
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001885bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001886 bool HasVAListArg, unsigned format_idx,
1887 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001888 VariadicCallType CallType,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001889 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001890 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001891 if (format_idx >= Args.size()) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001892 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00001893 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00001894 }
Mike Stump1eb44332009-09-09 15:08:12 +00001895
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001896 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001897
Chris Lattner59907c42007-08-10 20:18:51 +00001898 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001899 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001900 // Dynamically generated format strings are difficult to
1901 // automatically vet at compile time. Requiring that format strings
1902 // are string literals: (1) permits the checking of format strings by
1903 // the compiler and thereby (2) can practically remove the source of
1904 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001905
Mike Stump1eb44332009-09-09 15:08:12 +00001906 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001907 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001908 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001909 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00001910 StringLiteralCheckType CT =
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001911 checkFormatStringExpr(OrigFormatExpr, Args, HasVAListArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001912 format_idx, firstDataArg, Type, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001913 if (CT != SLCT_NotALiteral)
1914 // Literal format string found, check done!
1915 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001916
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001917 // Strftime is particular as it always uses a single 'time' argument,
1918 // so it is safe to pass a non-literal string.
1919 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00001920 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001921
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001922 // Do not emit diag when the string param is a macro expansion and the
1923 // format is either NSString or CFString. This is a hack to prevent
1924 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1925 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00001926 if (Type == FST_NSString &&
1927 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00001928 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001929
Chris Lattner655f1412009-04-29 04:59:47 +00001930 // If there are no arguments specified, warn with -Wformat-security, otherwise
1931 // warn only with -Wformat-nonliteral.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001932 if (Args.size() == format_idx+1)
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001933 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001934 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001935 << OrigFormatExpr->getSourceRange();
1936 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001937 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001938 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001939 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00001940 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001941}
Ted Kremenek71895b92007-08-14 17:39:48 +00001942
Ted Kremeneke0e53132010-01-28 23:39:18 +00001943namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001944class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1945protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001946 Sema &S;
1947 const StringLiteral *FExpr;
1948 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001949 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001950 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001951 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001952 const bool HasVAListArg;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001953 ArrayRef<const Expr *> Args;
Ted Kremenek0d277352010-01-29 01:06:55 +00001954 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001955 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001956 bool usesPositionalArgs;
1957 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001958 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00001959 Sema::VariadicCallType CallType;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001960public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001961 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001962 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00001963 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001964 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001965 unsigned formatIdx, bool inFunctionCall,
1966 Sema::VariadicCallType callType)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001967 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00001968 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
1969 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001970 Args(Args), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001971 usesPositionalArgs(false), atFirstArg(true),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001972 inFunctionCall(inFunctionCall), CallType(callType) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001973 CoveredArgs.resize(numDataArgs);
1974 CoveredArgs.reset();
1975 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001976
Ted Kremenek07d161f2010-01-29 01:50:07 +00001977 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001978
Ted Kremenek826a3452010-07-16 02:11:22 +00001979 void HandleIncompleteSpecifier(const char *startSpecifier,
1980 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00001981
Jordan Rosebbb6bb42012-09-08 04:00:03 +00001982 void HandleInvalidLengthModifier(
1983 const analyze_format_string::FormatSpecifier &FS,
1984 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00001985 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00001986
Hans Wennborg76517422012-02-22 10:17:01 +00001987 void HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00001988 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00001989 const char *startSpecifier, unsigned specifierLen);
1990
1991 void HandleNonStandardConversionSpecifier(
1992 const analyze_format_string::ConversionSpecifier &CS,
1993 const char *startSpecifier, unsigned specifierLen);
1994
Hans Wennborgf8562642012-03-09 10:10:54 +00001995 virtual void HandlePosition(const char *startPos, unsigned posLen);
1996
Ted Kremenekefaff192010-02-27 01:41:03 +00001997 virtual void HandleInvalidPosition(const char *startSpecifier,
1998 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001999 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00002000
2001 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2002
Ted Kremeneke0e53132010-01-28 23:39:18 +00002003 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002004
Richard Trieu55733de2011-10-28 00:41:25 +00002005 template <typename Range>
2006 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2007 const Expr *ArgumentExpr,
2008 PartialDiagnostic PDiag,
2009 SourceLocation StringLoc,
2010 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002011 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002012
Ted Kremenek826a3452010-07-16 02:11:22 +00002013protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002014 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2015 const char *startSpec,
2016 unsigned specifierLen,
2017 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00002018
2019 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2020 const char *startSpec,
2021 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002022
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002023 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00002024 CharSourceRange getSpecifierRange(const char *startSpecifier,
2025 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002026 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002027
Ted Kremenek0d277352010-01-29 01:06:55 +00002028 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00002029
2030 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2031 const analyze_format_string::ConversionSpecifier &CS,
2032 const char *startSpecifier, unsigned specifierLen,
2033 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00002034
2035 template <typename Range>
2036 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2037 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002038 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002039
2040 void CheckPositionalAndNonpositionalArgs(
2041 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002042};
2043}
2044
Ted Kremenek826a3452010-07-16 02:11:22 +00002045SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002046 return OrigFormatExpr->getSourceRange();
2047}
2048
Ted Kremenek826a3452010-07-16 02:11:22 +00002049CharSourceRange CheckFormatHandler::
2050getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002051 SourceLocation Start = getLocationOfByte(startSpecifier);
2052 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2053
2054 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002055 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002056
2057 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002058}
2059
Ted Kremenek826a3452010-07-16 02:11:22 +00002060SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002061 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002062}
2063
Ted Kremenek826a3452010-07-16 02:11:22 +00002064void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2065 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002066 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2067 getLocationOfByte(startSpecifier),
2068 /*IsStringLocation*/true,
2069 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002070}
2071
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002072void CheckFormatHandler::HandleInvalidLengthModifier(
2073 const analyze_format_string::FormatSpecifier &FS,
2074 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002075 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002076 using namespace analyze_format_string;
2077
2078 const LengthModifier &LM = FS.getLengthModifier();
2079 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2080
2081 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002082 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002083 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002084 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002085 getLocationOfByte(LM.getStart()),
2086 /*IsStringLocation*/true,
2087 getSpecifierRange(startSpecifier, specifierLen));
2088
2089 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2090 << FixedLM->toString()
2091 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2092
2093 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00002094 FixItHint Hint;
2095 if (DiagID == diag::warn_format_nonsensical_length)
2096 Hint = FixItHint::CreateRemoval(LMRange);
2097
2098 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),
Jordan Rose8be066e2012-09-08 04:00:12 +00002102 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002103 }
2104}
2105
Hans Wennborg76517422012-02-22 10:17:01 +00002106void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002107 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002108 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002109 using namespace analyze_format_string;
2110
2111 const LengthModifier &LM = FS.getLengthModifier();
2112 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2113
2114 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002115 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose8be066e2012-09-08 04:00:12 +00002116 if (FixedLM) {
2117 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2118 << LM.toString() << 0,
2119 getLocationOfByte(LM.getStart()),
2120 /*IsStringLocation*/true,
2121 getSpecifierRange(startSpecifier, specifierLen));
2122
2123 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2124 << FixedLM->toString()
2125 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2126
2127 } else {
2128 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2129 << LM.toString() << 0,
2130 getLocationOfByte(LM.getStart()),
2131 /*IsStringLocation*/true,
2132 getSpecifierRange(startSpecifier, specifierLen));
2133 }
Hans Wennborg76517422012-02-22 10:17:01 +00002134}
2135
2136void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2137 const analyze_format_string::ConversionSpecifier &CS,
2138 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002139 using namespace analyze_format_string;
2140
2141 // See if we know how to fix this conversion specifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002142 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose670941c2012-09-13 02:11:15 +00002143 if (FixedCS) {
2144 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2145 << CS.toString() << /*conversion specifier*/1,
2146 getLocationOfByte(CS.getStart()),
2147 /*IsStringLocation*/true,
2148 getSpecifierRange(startSpecifier, specifierLen));
2149
2150 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2151 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2152 << FixedCS->toString()
2153 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2154 } else {
2155 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2156 << CS.toString() << /*conversion specifier*/1,
2157 getLocationOfByte(CS.getStart()),
2158 /*IsStringLocation*/true,
2159 getSpecifierRange(startSpecifier, specifierLen));
2160 }
Hans Wennborg76517422012-02-22 10:17:01 +00002161}
2162
Hans Wennborgf8562642012-03-09 10:10:54 +00002163void CheckFormatHandler::HandlePosition(const char *startPos,
2164 unsigned posLen) {
2165 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2166 getLocationOfByte(startPos),
2167 /*IsStringLocation*/true,
2168 getSpecifierRange(startPos, posLen));
2169}
2170
Ted Kremenekefaff192010-02-27 01:41:03 +00002171void
Ted Kremenek826a3452010-07-16 02:11:22 +00002172CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2173 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002174 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2175 << (unsigned) p,
2176 getLocationOfByte(startPos), /*IsStringLocation*/true,
2177 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002178}
2179
Ted Kremenek826a3452010-07-16 02:11:22 +00002180void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002181 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002182 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2183 getLocationOfByte(startPos),
2184 /*IsStringLocation*/true,
2185 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002186}
2187
Ted Kremenek826a3452010-07-16 02:11:22 +00002188void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002189 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002190 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002191 EmitFormatDiagnostic(
2192 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2193 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2194 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002195 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002196}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002197
Jordan Rose48716662012-07-19 18:10:08 +00002198// Note that this may return NULL if there was an error parsing or building
2199// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002200const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002201 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002202}
2203
2204void CheckFormatHandler::DoneProcessing() {
2205 // Does the number of data arguments exceed the number of
2206 // format conversions in the format string?
2207 if (!HasVAListArg) {
2208 // Find any arguments that weren't covered.
2209 CoveredArgs.flip();
2210 signed notCoveredArg = CoveredArgs.find_first();
2211 if (notCoveredArg >= 0) {
2212 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002213 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2214 SourceLocation Loc = E->getLocStart();
2215 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2216 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2217 Loc, /*IsStringLocation*/false,
2218 getFormatStringRange());
2219 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002220 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002221 }
2222 }
2223}
2224
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002225bool
2226CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2227 SourceLocation Loc,
2228 const char *startSpec,
2229 unsigned specifierLen,
2230 const char *csStart,
2231 unsigned csLen) {
2232
2233 bool keepGoing = true;
2234 if (argIndex < NumDataArgs) {
2235 // Consider the argument coverered, even though the specifier doesn't
2236 // make sense.
2237 CoveredArgs.set(argIndex);
2238 }
2239 else {
2240 // If argIndex exceeds the number of data arguments we
2241 // don't issue a warning because that is just a cascade of warnings (and
2242 // they may have intended '%%' anyway). We don't want to continue processing
2243 // the format string after this point, however, as we will like just get
2244 // gibberish when trying to match arguments.
2245 keepGoing = false;
2246 }
2247
Richard Trieu55733de2011-10-28 00:41:25 +00002248 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2249 << StringRef(csStart, csLen),
2250 Loc, /*IsStringLocation*/true,
2251 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002252
2253 return keepGoing;
2254}
2255
Richard Trieu55733de2011-10-28 00:41:25 +00002256void
2257CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2258 const char *startSpec,
2259 unsigned specifierLen) {
2260 EmitFormatDiagnostic(
2261 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2262 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2263}
2264
Ted Kremenek666a1972010-07-26 19:45:42 +00002265bool
2266CheckFormatHandler::CheckNumArgs(
2267 const analyze_format_string::FormatSpecifier &FS,
2268 const analyze_format_string::ConversionSpecifier &CS,
2269 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2270
2271 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002272 PartialDiagnostic PDiag = FS.usesPositionalArg()
2273 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2274 << (argIndex+1) << NumDataArgs)
2275 : S.PDiag(diag::warn_printf_insufficient_data_args);
2276 EmitFormatDiagnostic(
2277 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2278 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002279 return false;
2280 }
2281 return true;
2282}
2283
Richard Trieu55733de2011-10-28 00:41:25 +00002284template<typename Range>
2285void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2286 SourceLocation Loc,
2287 bool IsStringLocation,
2288 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002289 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002290 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002291 Loc, IsStringLocation, StringRange, FixIt);
2292}
2293
2294/// \brief If the format string is not within the funcion call, emit a note
2295/// so that the function call and string are in diagnostic messages.
2296///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002297/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002298/// call and only one diagnostic message will be produced. Otherwise, an
2299/// extra note will be emitted pointing to location of the format string.
2300///
2301/// \param ArgumentExpr the expression that is passed as the format string
2302/// argument in the function call. Used for getting locations when two
2303/// diagnostics are emitted.
2304///
2305/// \param PDiag the callee should already have provided any strings for the
2306/// diagnostic message. This function only adds locations and fixits
2307/// to diagnostics.
2308///
2309/// \param Loc primary location for diagnostic. If two diagnostics are
2310/// required, one will be at Loc and a new SourceLocation will be created for
2311/// the other one.
2312///
2313/// \param IsStringLocation if true, Loc points to the format string should be
2314/// used for the note. Otherwise, Loc points to the argument list and will
2315/// be used with PDiag.
2316///
2317/// \param StringRange some or all of the string to highlight. This is
2318/// templated so it can accept either a CharSourceRange or a SourceRange.
2319///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002320/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002321template<typename Range>
2322void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2323 const Expr *ArgumentExpr,
2324 PartialDiagnostic PDiag,
2325 SourceLocation Loc,
2326 bool IsStringLocation,
2327 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002328 ArrayRef<FixItHint> FixIt) {
2329 if (InFunctionCall) {
2330 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2331 D << StringRange;
2332 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2333 I != E; ++I) {
2334 D << *I;
2335 }
2336 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00002337 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2338 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00002339
2340 const Sema::SemaDiagnosticBuilder &Note =
2341 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2342 diag::note_format_string_defined);
2343
2344 Note << StringRange;
2345 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2346 I != E; ++I) {
2347 Note << *I;
2348 }
Richard Trieu55733de2011-10-28 00:41:25 +00002349 }
2350}
2351
Ted Kremenek826a3452010-07-16 02:11:22 +00002352//===--- CHECK: Printf format string checking ------------------------------===//
2353
2354namespace {
2355class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002356 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002357public:
2358 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2359 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002360 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002361 const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002362 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002363 unsigned formatIdx, bool inFunctionCall,
2364 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002365 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002366 numDataArgs, beg, hasVAListArg, Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002367 formatIdx, inFunctionCall, CallType), ObjCContext(isObjC)
2368 {}
2369
Ted Kremenek826a3452010-07-16 02:11:22 +00002370
2371 bool HandleInvalidPrintfConversionSpecifier(
2372 const analyze_printf::PrintfSpecifier &FS,
2373 const char *startSpecifier,
2374 unsigned specifierLen);
2375
2376 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2377 const char *startSpecifier,
2378 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002379 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2380 const char *StartSpecifier,
2381 unsigned SpecifierLen,
2382 const Expr *E);
2383
Ted Kremenek826a3452010-07-16 02:11:22 +00002384 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2385 const char *startSpecifier, unsigned specifierLen);
2386 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2387 const analyze_printf::OptionalAmount &Amt,
2388 unsigned type,
2389 const char *startSpecifier, unsigned specifierLen);
2390 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2391 const analyze_printf::OptionalFlag &flag,
2392 const char *startSpecifier, unsigned specifierLen);
2393 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2394 const analyze_printf::OptionalFlag &ignoredFlag,
2395 const analyze_printf::OptionalFlag &flag,
2396 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002397 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith831421f2012-06-25 20:30:08 +00002398 const Expr *E, const CharSourceRange &CSR);
2399
Ted Kremenek826a3452010-07-16 02:11:22 +00002400};
2401}
2402
2403bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2404 const analyze_printf::PrintfSpecifier &FS,
2405 const char *startSpecifier,
2406 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002407 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002408 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002409
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002410 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2411 getLocationOfByte(CS.getStart()),
2412 startSpecifier, specifierLen,
2413 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002414}
2415
Ted Kremenek826a3452010-07-16 02:11:22 +00002416bool CheckPrintfHandler::HandleAmount(
2417 const analyze_format_string::OptionalAmount &Amt,
2418 unsigned k, const char *startSpecifier,
2419 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002420
2421 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002422 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002423 unsigned argIndex = Amt.getArgIndex();
2424 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002425 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2426 << k,
2427 getLocationOfByte(Amt.getStart()),
2428 /*IsStringLocation*/true,
2429 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002430 // Don't do any more checking. We will just emit
2431 // spurious errors.
2432 return false;
2433 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002434
Ted Kremenek0d277352010-01-29 01:06:55 +00002435 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002436 // Although not in conformance with C99, we also allow the argument to be
2437 // an 'unsigned int' as that is a reasonably safe case. GCC also
2438 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002439 CoveredArgs.set(argIndex);
2440 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002441 if (!Arg)
2442 return false;
2443
Ted Kremenek0d277352010-01-29 01:06:55 +00002444 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002445
Hans Wennborgf3749f42012-08-07 08:11:26 +00002446 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2447 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002448
Hans Wennborgf3749f42012-08-07 08:11:26 +00002449 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002450 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002451 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002452 << T << Arg->getSourceRange(),
2453 getLocationOfByte(Amt.getStart()),
2454 /*IsStringLocation*/true,
2455 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002456 // Don't do any more checking. We will just emit
2457 // spurious errors.
2458 return false;
2459 }
2460 }
2461 }
2462 return true;
2463}
Ted Kremenek0d277352010-01-29 01:06:55 +00002464
Tom Caree4ee9662010-06-17 19:00:27 +00002465void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002466 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002467 const analyze_printf::OptionalAmount &Amt,
2468 unsigned type,
2469 const char *startSpecifier,
2470 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002471 const analyze_printf::PrintfConversionSpecifier &CS =
2472 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002473
Richard Trieu55733de2011-10-28 00:41:25 +00002474 FixItHint fixit =
2475 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2476 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2477 Amt.getConstantLength()))
2478 : FixItHint();
2479
2480 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2481 << type << CS.toString(),
2482 getLocationOfByte(Amt.getStart()),
2483 /*IsStringLocation*/true,
2484 getSpecifierRange(startSpecifier, specifierLen),
2485 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002486}
2487
Ted Kremenek826a3452010-07-16 02:11:22 +00002488void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002489 const analyze_printf::OptionalFlag &flag,
2490 const char *startSpecifier,
2491 unsigned specifierLen) {
2492 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002493 const analyze_printf::PrintfConversionSpecifier &CS =
2494 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002495 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2496 << flag.toString() << CS.toString(),
2497 getLocationOfByte(flag.getPosition()),
2498 /*IsStringLocation*/true,
2499 getSpecifierRange(startSpecifier, specifierLen),
2500 FixItHint::CreateRemoval(
2501 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002502}
2503
2504void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002505 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002506 const analyze_printf::OptionalFlag &ignoredFlag,
2507 const analyze_printf::OptionalFlag &flag,
2508 const char *startSpecifier,
2509 unsigned specifierLen) {
2510 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002511 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2512 << ignoredFlag.toString() << flag.toString(),
2513 getLocationOfByte(ignoredFlag.getPosition()),
2514 /*IsStringLocation*/true,
2515 getSpecifierRange(startSpecifier, specifierLen),
2516 FixItHint::CreateRemoval(
2517 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002518}
2519
Richard Smith831421f2012-06-25 20:30:08 +00002520// Determines if the specified is a C++ class or struct containing
2521// a member with the specified name and kind (e.g. a CXXMethodDecl named
2522// "c_str()").
2523template<typename MemberKind>
2524static llvm::SmallPtrSet<MemberKind*, 1>
2525CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2526 const RecordType *RT = Ty->getAs<RecordType>();
2527 llvm::SmallPtrSet<MemberKind*, 1> Results;
2528
2529 if (!RT)
2530 return Results;
2531 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2532 if (!RD)
2533 return Results;
2534
2535 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2536 Sema::LookupMemberName);
2537
2538 // We just need to include all members of the right kind turned up by the
2539 // filter, at this point.
2540 if (S.LookupQualifiedName(R, RT->getDecl()))
2541 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2542 NamedDecl *decl = (*I)->getUnderlyingDecl();
2543 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2544 Results.insert(FK);
2545 }
2546 return Results;
2547}
2548
2549// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002550// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002551// Returns true when a c_str() conversion method is found.
2552bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgf3749f42012-08-07 08:11:26 +00002553 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith831421f2012-06-25 20:30:08 +00002554 const CharSourceRange &CSR) {
2555 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2556
2557 MethodSet Results =
2558 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2559
2560 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2561 MI != ME; ++MI) {
2562 const CXXMethodDecl *Method = *MI;
2563 if (Method->getNumParams() == 0 &&
Hans Wennborgf3749f42012-08-07 08:11:26 +00002564 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith831421f2012-06-25 20:30:08 +00002565 // FIXME: Suggest parens if the expression needs them.
2566 SourceLocation EndLoc =
2567 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2568 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2569 << "c_str()"
2570 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2571 return true;
2572 }
2573 }
2574
2575 return false;
2576}
2577
Ted Kremeneke0e53132010-01-28 23:39:18 +00002578bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002579CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002580 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002581 const char *startSpecifier,
2582 unsigned specifierLen) {
2583
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002584 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002585 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002586 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002587
Ted Kremenekbaa40062010-07-19 22:01:06 +00002588 if (FS.consumesDataArgument()) {
2589 if (atFirstArg) {
2590 atFirstArg = false;
2591 usesPositionalArgs = FS.usesPositionalArg();
2592 }
2593 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002594 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2595 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002596 return false;
2597 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002598 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002599
Ted Kremenekefaff192010-02-27 01:41:03 +00002600 // First check if the field width, precision, and conversion specifier
2601 // have matching data arguments.
2602 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2603 startSpecifier, specifierLen)) {
2604 return false;
2605 }
2606
2607 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2608 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002609 return false;
2610 }
2611
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002612 if (!CS.consumesDataArgument()) {
2613 // FIXME: Technically specifying a precision or field width here
2614 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002615 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002616 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002617
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002618 // Consume the argument.
2619 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002620 if (argIndex < NumDataArgs) {
2621 // The check to see if the argIndex is valid will come later.
2622 // We set the bit here because we may exit early from this
2623 // function if we encounter some other error.
2624 CoveredArgs.set(argIndex);
2625 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002626
2627 // Check for using an Objective-C specific conversion specifier
2628 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002629 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002630 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2631 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002632 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002633
Tom Caree4ee9662010-06-17 19:00:27 +00002634 // Check for invalid use of field width
2635 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002636 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002637 startSpecifier, specifierLen);
2638 }
2639
2640 // Check for invalid use of precision
2641 if (!FS.hasValidPrecision()) {
2642 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2643 startSpecifier, specifierLen);
2644 }
2645
2646 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002647 if (!FS.hasValidThousandsGroupingPrefix())
2648 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002649 if (!FS.hasValidLeadingZeros())
2650 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2651 if (!FS.hasValidPlusPrefix())
2652 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002653 if (!FS.hasValidSpacePrefix())
2654 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002655 if (!FS.hasValidAlternativeForm())
2656 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2657 if (!FS.hasValidLeftJustified())
2658 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2659
2660 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002661 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2662 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2663 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002664 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2665 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2666 startSpecifier, specifierLen);
2667
2668 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002669 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00002670 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2671 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002672 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00002673 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002674 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00002675 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2676 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00002677
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002678 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
2679 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2680
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002681 // The remaining checks depend on the data arguments.
2682 if (HasVAListArg)
2683 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002684
Ted Kremenek666a1972010-07-26 19:45:42 +00002685 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002686 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002687
Jordan Rose48716662012-07-19 18:10:08 +00002688 const Expr *Arg = getDataArg(argIndex);
2689 if (!Arg)
2690 return true;
2691
2692 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00002693}
2694
Jordan Roseec087352012-09-05 22:56:26 +00002695static bool requiresParensToAddCast(const Expr *E) {
2696 // FIXME: We should have a general way to reason about operator
2697 // precedence and whether parens are actually needed here.
2698 // Take care of a few common cases where they aren't.
2699 const Expr *Inside = E->IgnoreImpCasts();
2700 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
2701 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
2702
2703 switch (Inside->getStmtClass()) {
2704 case Stmt::ArraySubscriptExprClass:
2705 case Stmt::CallExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002706 case Stmt::CharacterLiteralClass:
2707 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002708 case Stmt::DeclRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002709 case Stmt::FloatingLiteralClass:
2710 case Stmt::IntegerLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00002711 case Stmt::MemberExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002712 case Stmt::ObjCArrayLiteralClass:
2713 case Stmt::ObjCBoolLiteralExprClass:
2714 case Stmt::ObjCBoxedExprClass:
2715 case Stmt::ObjCDictionaryLiteralClass:
2716 case Stmt::ObjCEncodeExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002717 case Stmt::ObjCIvarRefExprClass:
2718 case Stmt::ObjCMessageExprClass:
2719 case Stmt::ObjCPropertyRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002720 case Stmt::ObjCStringLiteralClass:
2721 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002722 case Stmt::ParenExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002723 case Stmt::StringLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00002724 case Stmt::UnaryOperatorClass:
2725 return false;
2726 default:
2727 return true;
2728 }
2729}
2730
Richard Smith831421f2012-06-25 20:30:08 +00002731bool
2732CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2733 const char *StartSpecifier,
2734 unsigned SpecifierLen,
2735 const Expr *E) {
2736 using namespace analyze_format_string;
2737 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002738 // Now type check the data expression that matches the
2739 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00002740 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
2741 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00002742 if (!AT.isValid())
2743 return true;
Jordan Roseec087352012-09-05 22:56:26 +00002744
Jordan Rose448ac3e2012-12-05 18:44:40 +00002745 QualType ExprTy = E->getType();
Ted Kremenek02be9682013-04-10 06:26:26 +00002746 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
2747 ExprTy = TET->getUnderlyingExpr()->getType();
2748 }
2749
Jordan Rose448ac3e2012-12-05 18:44:40 +00002750 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002751 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00002752
Jordan Rose614a8652012-09-05 22:56:19 +00002753 // Look through argument promotions for our error message's reported type.
2754 // This includes the integral and floating promotions, but excludes array
2755 // and function pointer decay; seeing that an argument intended to be a
2756 // string has type 'char [6]' is probably more confusing than 'char *'.
2757 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2758 if (ICE->getCastKind() == CK_IntegralCast ||
2759 ICE->getCastKind() == CK_FloatingCast) {
2760 E = ICE->getSubExpr();
Jordan Rose448ac3e2012-12-05 18:44:40 +00002761 ExprTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00002762
2763 // Check if we didn't match because of an implicit cast from a 'char'
2764 // or 'short' to an 'int'. This is done because printf is a varargs
2765 // function.
2766 if (ICE->getType() == S.Context.IntTy ||
2767 ICE->getType() == S.Context.UnsignedIntTy) {
2768 // All further checking is done on the subexpression.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002769 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002770 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002771 }
Jordan Roseee0259d2012-06-04 22:48:57 +00002772 }
Jordan Rose448ac3e2012-12-05 18:44:40 +00002773 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
2774 // Special case for 'a', which has type 'int' in C.
2775 // Note, however, that we do /not/ want to treat multibyte constants like
2776 // 'MooV' as characters! This form is deprecated but still exists.
2777 if (ExprTy == S.Context.IntTy)
2778 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
2779 ExprTy = S.Context.CharTy;
Jordan Rose614a8652012-09-05 22:56:19 +00002780 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002781
Jordan Rose2cd34402012-12-05 18:44:49 +00002782 // %C in an Objective-C context prints a unichar, not a wchar_t.
2783 // If the argument is an integer of some kind, believe the %C and suggest
2784 // a cast instead of changing the conversion specifier.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002785 QualType IntendedTy = ExprTy;
Jordan Rose2cd34402012-12-05 18:44:49 +00002786 if (ObjCContext &&
2787 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
2788 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
2789 !ExprTy->isCharType()) {
2790 // 'unichar' is defined as a typedef of unsigned short, but we should
2791 // prefer using the typedef if it is visible.
2792 IntendedTy = S.Context.UnsignedShortTy;
2793
2794 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
2795 Sema::LookupOrdinaryName);
2796 if (S.LookupName(Result, S.getCurScope())) {
2797 NamedDecl *ND = Result.getFoundDecl();
2798 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
2799 if (TD->getUnderlyingType() == IntendedTy)
2800 IntendedTy = S.Context.getTypedefType(TD);
2801 }
2802 }
2803 }
2804
2805 // Special-case some of Darwin's platform-independence types by suggesting
2806 // casts to primitive types that are known to be large enough.
2807 bool ShouldNotPrintDirectly = false;
Jordan Roseec087352012-09-05 22:56:26 +00002808 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenek6edb0292013-03-25 22:28:37 +00002809 // Use a 'while' to peel off layers of typedefs.
2810 QualType TyTy = IntendedTy;
2811 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseec087352012-09-05 22:56:26 +00002812 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose2cd34402012-12-05 18:44:49 +00002813 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseec087352012-09-05 22:56:26 +00002814 .Case("NSInteger", S.Context.LongTy)
2815 .Case("NSUInteger", S.Context.UnsignedLongTy)
2816 .Case("SInt32", S.Context.IntTy)
2817 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose2cd34402012-12-05 18:44:49 +00002818 .Default(QualType());
2819
2820 if (!CastTy.isNull()) {
2821 ShouldNotPrintDirectly = true;
2822 IntendedTy = CastTy;
Ted Kremenek6edb0292013-03-25 22:28:37 +00002823 break;
Jordan Rose2cd34402012-12-05 18:44:49 +00002824 }
Ted Kremenek6edb0292013-03-25 22:28:37 +00002825 TyTy = UserTy->desugar();
Jordan Roseec087352012-09-05 22:56:26 +00002826 }
2827 }
2828
Jordan Rose614a8652012-09-05 22:56:19 +00002829 // We may be able to offer a FixItHint if it is a supported type.
2830 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00002831 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00002832 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002833
Jordan Rose614a8652012-09-05 22:56:19 +00002834 if (success) {
2835 // Get the fix string from the fixed format specifier
2836 SmallString<16> buf;
2837 llvm::raw_svector_ostream os(buf);
2838 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002839
Jordan Roseec087352012-09-05 22:56:26 +00002840 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
2841
Jordan Rose2cd34402012-12-05 18:44:49 +00002842 if (IntendedTy == ExprTy) {
2843 // In this case, the specifier is wrong and should be changed to match
2844 // the argument.
2845 EmitFormatDiagnostic(
2846 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2847 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
2848 << E->getSourceRange(),
2849 E->getLocStart(),
2850 /*IsStringLocation*/false,
2851 SpecRange,
2852 FixItHint::CreateReplacement(SpecRange, os.str()));
2853
2854 } else {
Jordan Roseec087352012-09-05 22:56:26 +00002855 // The canonical type for formatting this value is different from the
2856 // actual type of the expression. (This occurs, for example, with Darwin's
2857 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
2858 // should be printed as 'long' for 64-bit compatibility.)
2859 // Rather than emitting a normal format/argument mismatch, we want to
2860 // add a cast to the recommended type (and correct the format string
2861 // if necessary).
2862 SmallString<16> CastBuf;
2863 llvm::raw_svector_ostream CastFix(CastBuf);
2864 CastFix << "(";
2865 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
2866 CastFix << ")";
2867
2868 SmallVector<FixItHint,4> Hints;
2869 if (!AT.matchesType(S.Context, IntendedTy))
2870 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
2871
2872 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
2873 // If there's already a cast present, just replace it.
2874 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
2875 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
2876
2877 } else if (!requiresParensToAddCast(E)) {
2878 // If the expression has high enough precedence,
2879 // just write the C-style cast.
2880 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2881 CastFix.str()));
2882 } else {
2883 // Otherwise, add parens around the expression as well as the cast.
2884 CastFix << "(";
2885 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2886 CastFix.str()));
2887
2888 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
2889 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
2890 }
2891
Jordan Rose2cd34402012-12-05 18:44:49 +00002892 if (ShouldNotPrintDirectly) {
2893 // The expression has a type that should not be printed directly.
2894 // We extract the name from the typedef because we don't want to show
2895 // the underlying type in the diagnostic.
2896 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseec087352012-09-05 22:56:26 +00002897
Jordan Rose2cd34402012-12-05 18:44:49 +00002898 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
2899 << Name << IntendedTy
2900 << E->getSourceRange(),
2901 E->getLocStart(), /*IsStringLocation=*/false,
2902 SpecRange, Hints);
2903 } else {
2904 // In this case, the expression could be printed using a different
2905 // specifier, but we've decided that the specifier is probably correct
2906 // and we should cast instead. Just use the normal warning message.
2907 EmitFormatDiagnostic(
2908 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2909 << AT.getRepresentativeTypeName(S.Context) << ExprTy
2910 << E->getSourceRange(),
2911 E->getLocStart(), /*IsStringLocation*/false,
2912 SpecRange, Hints);
2913 }
Jordan Roseec087352012-09-05 22:56:26 +00002914 }
Jordan Rose614a8652012-09-05 22:56:19 +00002915 } else {
2916 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
2917 SpecifierLen);
2918 // Since the warning for passing non-POD types to variadic functions
2919 // was deferred until now, we emit a warning for non-POD
2920 // arguments here.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002921 if (S.isValidVarArgType(ExprTy) == Sema::VAK_Invalid) {
Jordan Rose614a8652012-09-05 22:56:19 +00002922 unsigned DiagKind;
Jordan Rose448ac3e2012-12-05 18:44:40 +00002923 if (ExprTy->isObjCObjectType())
Jordan Rose614a8652012-09-05 22:56:19 +00002924 DiagKind = diag::err_cannot_pass_objc_interface_to_vararg_format;
2925 else
2926 DiagKind = diag::warn_non_pod_vararg_with_format_string;
2927
2928 EmitFormatDiagnostic(
2929 S.PDiag(DiagKind)
Richard Smith80ad52f2013-01-02 11:42:31 +00002930 << S.getLangOpts().CPlusPlus11
Jordan Rose448ac3e2012-12-05 18:44:40 +00002931 << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00002932 << CallType
2933 << AT.getRepresentativeTypeName(S.Context)
2934 << CSR
2935 << E->getSourceRange(),
2936 E->getLocStart(), /*IsStringLocation*/false, CSR);
2937
2938 checkForCStrMembers(AT, E, CSR);
2939 } else
Richard Trieu55733de2011-10-28 00:41:25 +00002940 EmitFormatDiagnostic(
2941 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Jordan Rose448ac3e2012-12-05 18:44:40 +00002942 << AT.getRepresentativeTypeName(S.Context) << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00002943 << CSR
Richard Smith831421f2012-06-25 20:30:08 +00002944 << E->getSourceRange(),
Jordan Rose614a8652012-09-05 22:56:19 +00002945 E->getLocStart(), /*IsStringLocation*/false, CSR);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002946 }
2947
Ted Kremeneke0e53132010-01-28 23:39:18 +00002948 return true;
2949}
2950
Ted Kremenek826a3452010-07-16 02:11:22 +00002951//===--- CHECK: Scanf format string checking ------------------------------===//
2952
2953namespace {
2954class CheckScanfHandler : public CheckFormatHandler {
2955public:
2956 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2957 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002958 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002959 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002960 unsigned formatIdx, bool inFunctionCall,
2961 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002962 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002963 numDataArgs, beg, hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002964 Args, formatIdx, inFunctionCall, CallType)
Jordan Roseddcfbc92012-07-19 18:10:23 +00002965 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002966
2967 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2968 const char *startSpecifier,
2969 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002970
2971 bool HandleInvalidScanfConversionSpecifier(
2972 const analyze_scanf::ScanfSpecifier &FS,
2973 const char *startSpecifier,
2974 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002975
2976 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002977};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002978}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002979
Ted Kremenekb7c21012010-07-16 18:28:03 +00002980void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2981 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002982 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2983 getLocationOfByte(end), /*IsStringLocation*/true,
2984 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002985}
2986
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002987bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2988 const analyze_scanf::ScanfSpecifier &FS,
2989 const char *startSpecifier,
2990 unsigned specifierLen) {
2991
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002992 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002993 FS.getConversionSpecifier();
2994
2995 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2996 getLocationOfByte(CS.getStart()),
2997 startSpecifier, specifierLen,
2998 CS.getStart(), CS.getLength());
2999}
3000
Ted Kremenek826a3452010-07-16 02:11:22 +00003001bool CheckScanfHandler::HandleScanfSpecifier(
3002 const analyze_scanf::ScanfSpecifier &FS,
3003 const char *startSpecifier,
3004 unsigned specifierLen) {
3005
3006 using namespace analyze_scanf;
3007 using namespace analyze_format_string;
3008
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003009 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00003010
Ted Kremenekbaa40062010-07-19 22:01:06 +00003011 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3012 // be used to decide if we are using positional arguments consistently.
3013 if (FS.consumesDataArgument()) {
3014 if (atFirstArg) {
3015 atFirstArg = false;
3016 usesPositionalArgs = FS.usesPositionalArg();
3017 }
3018 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003019 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3020 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003021 return false;
3022 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003023 }
3024
3025 // Check if the field with is non-zero.
3026 const OptionalAmount &Amt = FS.getFieldWidth();
3027 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3028 if (Amt.getConstantAmount() == 0) {
3029 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3030 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00003031 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3032 getLocationOfByte(Amt.getStart()),
3033 /*IsStringLocation*/true, R,
3034 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00003035 }
3036 }
3037
3038 if (!FS.consumesDataArgument()) {
3039 // FIXME: Technically specifying a precision or field width here
3040 // makes no sense. Worth issuing a warning at some point.
3041 return true;
3042 }
3043
3044 // Consume the argument.
3045 unsigned argIndex = FS.getArgIndex();
3046 if (argIndex < NumDataArgs) {
3047 // The check to see if the argIndex is valid will come later.
3048 // We set the bit here because we may exit early from this
3049 // function if we encounter some other error.
3050 CoveredArgs.set(argIndex);
3051 }
3052
Ted Kremenek1e51c202010-07-20 20:04:47 +00003053 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003054 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003055 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3056 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003057 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003058 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003059 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003060 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3061 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00003062
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003063 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3064 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3065
Ted Kremenek826a3452010-07-16 02:11:22 +00003066 // The remaining checks depend on the data arguments.
3067 if (HasVAListArg)
3068 return true;
3069
Ted Kremenek666a1972010-07-26 19:45:42 +00003070 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00003071 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00003072
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003073 // Check that the argument type matches the format specifier.
3074 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00003075 if (!Ex)
3076 return true;
3077
Hans Wennborg58e1e542012-08-07 08:59:46 +00003078 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3079 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003080 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00003081 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00003082 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003083
3084 if (success) {
3085 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003086 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003087 llvm::raw_svector_ostream os(buf);
3088 fixedFS.toString(os);
3089
3090 EmitFormatDiagnostic(
3091 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003092 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003093 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003094 Ex->getLocStart(),
3095 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003096 getSpecifierRange(startSpecifier, specifierLen),
3097 FixItHint::CreateReplacement(
3098 getSpecifierRange(startSpecifier, specifierLen),
3099 os.str()));
3100 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003101 EmitFormatDiagnostic(
3102 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003103 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003104 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003105 Ex->getLocStart(),
3106 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003107 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003108 }
3109 }
3110
Ted Kremenek826a3452010-07-16 02:11:22 +00003111 return true;
3112}
3113
3114void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003115 const Expr *OrigFormatExpr,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003116 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003117 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003118 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003119 bool inFunctionCall, VariadicCallType CallType) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003120
Ted Kremeneke0e53132010-01-28 23:39:18 +00003121 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00003122 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003123 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003124 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003125 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3126 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003127 return;
3128 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003129
Ted Kremeneke0e53132010-01-28 23:39:18 +00003130 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00003131 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003132 const char *Str = StrRef.data();
3133 unsigned StrLen = StrRef.size();
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003134 const unsigned numDataArgs = Args.size() - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00003135
Ted Kremeneke0e53132010-01-28 23:39:18 +00003136 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00003137 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00003138 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003139 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003140 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3141 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003142 return;
3143 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003144
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003145 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003146 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003147 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003148 Str, HasVAListArg, Args, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003149 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003150
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003151 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003152 getLangOpts(),
3153 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003154 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003155 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00003156 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003157 Str, HasVAListArg, Args, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003158 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003159
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003160 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003161 getLangOpts(),
3162 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003163 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003164 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00003165}
3166
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003167//===--- CHECK: Standard memory functions ---------------------------------===//
3168
Douglas Gregor2a053a32011-05-03 20:05:22 +00003169/// \brief Determine whether the given type is a dynamic class type (e.g.,
3170/// whether it has a vtable).
3171static bool isDynamicClassType(QualType T) {
3172 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3173 if (CXXRecordDecl *Definition = Record->getDefinition())
3174 if (Definition->isDynamicClass())
3175 return true;
3176
3177 return false;
3178}
3179
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003180/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00003181/// otherwise returns NULL.
3182static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00003183 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00003184 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3185 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3186 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003187
Chandler Carruth000d4282011-06-16 09:09:40 +00003188 return 0;
3189}
3190
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003191/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00003192static QualType getSizeOfArgType(const Expr* E) {
3193 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3194 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3195 if (SizeOf->getKind() == clang::UETT_SizeOf)
3196 return SizeOf->getTypeOfArgument();
3197
3198 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00003199}
3200
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003201/// \brief Check for dangerous or invalid arguments to memset().
3202///
Chandler Carruth929f0132011-06-03 06:23:57 +00003203/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003204/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3205/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003206///
3207/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003208void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00003209 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003210 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00003211 assert(BId != 0);
3212
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003213 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00003214 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00003215 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00003216 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003217 return;
3218
Anna Zaks0a151a12012-01-17 00:37:07 +00003219 unsigned LastArg = (BId == Builtin::BImemset ||
3220 BId == Builtin::BIstrndup ? 1 : 2);
3221 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00003222 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00003223
3224 // We have special checking when the length is a sizeof expression.
3225 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3226 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3227 llvm::FoldingSetNodeID SizeOfArgID;
3228
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003229 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3230 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003231 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003232
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003233 QualType DestTy = Dest->getType();
3234 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3235 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00003236
Chandler Carruth000d4282011-06-16 09:09:40 +00003237 // Never warn about void type pointers. This can be used to suppress
3238 // false positives.
3239 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003240 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003241
Chandler Carruth000d4282011-06-16 09:09:40 +00003242 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3243 // actually comparing the expressions for equality. Because computing the
3244 // expression IDs can be expensive, we only do this if the diagnostic is
3245 // enabled.
3246 if (SizeOfArg &&
3247 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3248 SizeOfArg->getExprLoc())) {
3249 // We only compute IDs for expressions if the warning is enabled, and
3250 // cache the sizeof arg's ID.
3251 if (SizeOfArgID == llvm::FoldingSetNodeID())
3252 SizeOfArg->Profile(SizeOfArgID, Context, true);
3253 llvm::FoldingSetNodeID DestID;
3254 Dest->Profile(DestID, Context, true);
3255 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00003256 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3257 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00003258 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003259 StringRef ReadableName = FnName->getName();
3260
Chandler Carruth000d4282011-06-16 09:09:40 +00003261 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00003262 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00003263 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian7adf4172013-01-30 01:12:44 +00003264 if (!PointeeTy->isIncompleteType() &&
3265 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth000d4282011-06-16 09:09:40 +00003266 ActionIdx = 2; // If the pointee's size is sizeof(char),
3267 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003268
3269 // If the function is defined as a builtin macro, do not show macro
3270 // expansion.
3271 SourceLocation SL = SizeOfArg->getExprLoc();
3272 SourceRange DSR = Dest->getSourceRange();
3273 SourceRange SSR = SizeOfArg->getSourceRange();
3274 SourceManager &SM = PP.getSourceManager();
3275
3276 if (SM.isMacroArgExpansion(SL)) {
3277 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3278 SL = SM.getSpellingLoc(SL);
3279 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3280 SM.getSpellingLoc(DSR.getEnd()));
3281 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3282 SM.getSpellingLoc(SSR.getEnd()));
3283 }
3284
Anna Zaks90c78322012-05-30 23:14:52 +00003285 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00003286 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00003287 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00003288 << PointeeTy
3289 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00003290 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00003291 << SSR);
3292 DiagRuntimeBehavior(SL, SizeOfArg,
3293 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3294 << ActionIdx
3295 << SSR);
3296
Chandler Carruth000d4282011-06-16 09:09:40 +00003297 break;
3298 }
3299 }
3300
3301 // Also check for cases where the sizeof argument is the exact same
3302 // type as the memory argument, and where it points to a user-defined
3303 // record type.
3304 if (SizeOfArgTy != QualType()) {
3305 if (PointeeTy->isRecordType() &&
3306 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3307 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3308 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3309 << FnName << SizeOfArgTy << ArgIdx
3310 << PointeeTy << Dest->getSourceRange()
3311 << LenExpr->getSourceRange());
3312 break;
3313 }
Nico Webere4a1c642011-06-14 16:14:58 +00003314 }
3315
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003316 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00003317 if (isDynamicClassType(PointeeTy)) {
3318
3319 unsigned OperationType = 0;
3320 // "overwritten" if we're warning about the destination for any call
3321 // but memcmp; otherwise a verb appropriate to the call.
3322 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3323 if (BId == Builtin::BImemcpy)
3324 OperationType = 1;
3325 else if(BId == Builtin::BImemmove)
3326 OperationType = 2;
3327 else if (BId == Builtin::BImemcmp)
3328 OperationType = 3;
3329 }
3330
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003331 DiagRuntimeBehavior(
3332 Dest->getExprLoc(), Dest,
3333 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003334 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003335 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003336 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003337 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003338 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3339 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003340 DiagRuntimeBehavior(
3341 Dest->getExprLoc(), Dest,
3342 PDiag(diag::warn_arc_object_memaccess)
3343 << ArgIdx << FnName << PointeeTy
3344 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003345 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003346 continue;
John McCallf85e1932011-06-15 23:02:42 +00003347
3348 DiagRuntimeBehavior(
3349 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003350 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003351 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3352 break;
3353 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003354 }
3355}
3356
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003357// A little helper routine: ignore addition and subtraction of integer literals.
3358// This intentionally does not ignore all integer constant expressions because
3359// we don't want to remove sizeof().
3360static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3361 Ex = Ex->IgnoreParenCasts();
3362
3363 for (;;) {
3364 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3365 if (!BO || !BO->isAdditiveOp())
3366 break;
3367
3368 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3369 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3370
3371 if (isa<IntegerLiteral>(RHS))
3372 Ex = LHS;
3373 else if (isa<IntegerLiteral>(LHS))
3374 Ex = RHS;
3375 else
3376 break;
3377 }
3378
3379 return Ex;
3380}
3381
Anna Zaks0f38ace2012-08-08 21:42:23 +00003382static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3383 ASTContext &Context) {
3384 // Only handle constant-sized or VLAs, but not flexible members.
3385 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3386 // Only issue the FIXIT for arrays of size > 1.
3387 if (CAT->getSize().getSExtValue() <= 1)
3388 return false;
3389 } else if (!Ty->isVariableArrayType()) {
3390 return false;
3391 }
3392 return true;
3393}
3394
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003395// Warn if the user has made the 'size' argument to strlcpy or strlcat
3396// be the size of the source, instead of the destination.
3397void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3398 IdentifierInfo *FnName) {
3399
3400 // Don't crash if the user has the wrong number of arguments
3401 if (Call->getNumArgs() != 3)
3402 return;
3403
3404 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3405 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3406 const Expr *CompareWithSrc = NULL;
3407
3408 // Look for 'strlcpy(dst, x, sizeof(x))'
3409 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3410 CompareWithSrc = Ex;
3411 else {
3412 // Look for 'strlcpy(dst, x, strlen(x))'
3413 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003414 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003415 && SizeCall->getNumArgs() == 1)
3416 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3417 }
3418 }
3419
3420 if (!CompareWithSrc)
3421 return;
3422
3423 // Determine if the argument to sizeof/strlen is equal to the source
3424 // argument. In principle there's all kinds of things you could do
3425 // here, for instance creating an == expression and evaluating it with
3426 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3427 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3428 if (!SrcArgDRE)
3429 return;
3430
3431 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3432 if (!CompareWithSrcDRE ||
3433 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3434 return;
3435
3436 const Expr *OriginalSizeArg = Call->getArg(2);
3437 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3438 << OriginalSizeArg->getSourceRange() << FnName;
3439
3440 // Output a FIXIT hint if the destination is an array (rather than a
3441 // pointer to an array). This could be enhanced to handle some
3442 // pointers if we know the actual size, like if DstArg is 'array+2'
3443 // we could say 'sizeof(array)-2'.
3444 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00003445 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00003446 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00003447
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003448 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003449 llvm::raw_svector_ostream OS(sizeString);
3450 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003451 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003452 OS << ")";
3453
3454 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3455 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3456 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003457}
3458
Anna Zaksc36bedc2012-02-01 19:08:57 +00003459/// Check if two expressions refer to the same declaration.
3460static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3461 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3462 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3463 return D1->getDecl() == D2->getDecl();
3464 return false;
3465}
3466
3467static const Expr *getStrlenExprArg(const Expr *E) {
3468 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3469 const FunctionDecl *FD = CE->getDirectCallee();
3470 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3471 return 0;
3472 return CE->getArg(0)->IgnoreParenCasts();
3473 }
3474 return 0;
3475}
3476
3477// Warn on anti-patterns as the 'size' argument to strncat.
3478// The correct size argument should look like following:
3479// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3480void Sema::CheckStrncatArguments(const CallExpr *CE,
3481 IdentifierInfo *FnName) {
3482 // Don't crash if the user has the wrong number of arguments.
3483 if (CE->getNumArgs() < 3)
3484 return;
3485 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3486 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3487 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3488
3489 // Identify common expressions, which are wrongly used as the size argument
3490 // to strncat and may lead to buffer overflows.
3491 unsigned PatternType = 0;
3492 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3493 // - sizeof(dst)
3494 if (referToTheSameDecl(SizeOfArg, DstArg))
3495 PatternType = 1;
3496 // - sizeof(src)
3497 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3498 PatternType = 2;
3499 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3500 if (BE->getOpcode() == BO_Sub) {
3501 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3502 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3503 // - sizeof(dst) - strlen(dst)
3504 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3505 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3506 PatternType = 1;
3507 // - sizeof(src) - (anything)
3508 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3509 PatternType = 2;
3510 }
3511 }
3512
3513 if (PatternType == 0)
3514 return;
3515
Anna Zaksafdb0412012-02-03 01:27:37 +00003516 // Generate the diagnostic.
3517 SourceLocation SL = LenArg->getLocStart();
3518 SourceRange SR = LenArg->getSourceRange();
3519 SourceManager &SM = PP.getSourceManager();
3520
3521 // If the function is defined as a builtin macro, do not show macro expansion.
3522 if (SM.isMacroArgExpansion(SL)) {
3523 SL = SM.getSpellingLoc(SL);
3524 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3525 SM.getSpellingLoc(SR.getEnd()));
3526 }
3527
Anna Zaks0f38ace2012-08-08 21:42:23 +00003528 // Check if the destination is an array (rather than a pointer to an array).
3529 QualType DstTy = DstArg->getType();
3530 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3531 Context);
3532 if (!isKnownSizeArray) {
3533 if (PatternType == 1)
3534 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3535 else
3536 Diag(SL, diag::warn_strncat_src_size) << SR;
3537 return;
3538 }
3539
Anna Zaksc36bedc2012-02-01 19:08:57 +00003540 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003541 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003542 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003543 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003544
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003545 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003546 llvm::raw_svector_ostream OS(sizeString);
3547 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003548 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003549 OS << ") - ";
3550 OS << "strlen(";
Richard Smithd1420c62012-08-16 03:56:14 +00003551 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003552 OS << ") - 1";
3553
Anna Zaksafdb0412012-02-03 01:27:37 +00003554 Diag(SL, diag::note_strncat_wrong_size)
3555 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003556}
3557
Ted Kremenek06de2762007-08-17 16:46:58 +00003558//===--- CHECK: Return Address of Stack Variable --------------------------===//
3559
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003560static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3561 Decl *ParentDecl);
3562static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3563 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003564
3565/// CheckReturnStackAddr - Check if a return statement returns the address
3566/// of a stack variable.
3567void
3568Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3569 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003570
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003571 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003572 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003573
3574 // Perform checking for returned stack addresses, local blocks,
3575 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003576 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003577 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003578 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003579 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003580 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003581 }
3582
3583 if (stackE == 0)
3584 return; // Nothing suspicious was found.
3585
3586 SourceLocation diagLoc;
3587 SourceRange diagRange;
3588 if (refVars.empty()) {
3589 diagLoc = stackE->getLocStart();
3590 diagRange = stackE->getSourceRange();
3591 } else {
3592 // We followed through a reference variable. 'stackE' contains the
3593 // problematic expression but we will warn at the return statement pointing
3594 // at the reference variable. We will later display the "trail" of
3595 // reference variables using notes.
3596 diagLoc = refVars[0]->getLocStart();
3597 diagRange = refVars[0]->getSourceRange();
3598 }
3599
3600 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3601 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3602 : diag::warn_ret_stack_addr)
3603 << DR->getDecl()->getDeclName() << diagRange;
3604 } else if (isa<BlockExpr>(stackE)) { // local block.
3605 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3606 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3607 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3608 } else { // local temporary.
3609 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3610 : diag::warn_ret_local_temp_addr)
3611 << diagRange;
3612 }
3613
3614 // Display the "trail" of reference variables that we followed until we
3615 // found the problematic expression using notes.
3616 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3617 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3618 // If this var binds to another reference var, show the range of the next
3619 // var, otherwise the var binds to the problematic expression, in which case
3620 // show the range of the expression.
3621 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3622 : stackE->getSourceRange();
3623 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3624 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003625 }
3626}
3627
3628/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3629/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003630/// to a location on the stack, a local block, an address of a label, or a
3631/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003632/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003633/// encounter a subexpression that (1) clearly does not lead to one of the
3634/// above problematic expressions (2) is something we cannot determine leads to
3635/// a problematic expression based on such local checking.
3636///
3637/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3638/// the expression that they point to. Such variables are added to the
3639/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003640///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003641/// EvalAddr processes expressions that are pointers that are used as
3642/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003643/// At the base case of the recursion is a check for the above problematic
3644/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00003645///
3646/// This implementation handles:
3647///
3648/// * pointer-to-pointer casts
3649/// * implicit conversions from array references to pointers
3650/// * taking the address of fields
3651/// * arbitrary interplay between "&" and "*" operators
3652/// * pointer arithmetic from an address of a stack variable
3653/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003654static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3655 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003656 if (E->isTypeDependent())
3657 return NULL;
3658
Ted Kremenek06de2762007-08-17 16:46:58 +00003659 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00003660 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00003661 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003662 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003663 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00003664
Peter Collingbournef111d932011-04-15 00:35:48 +00003665 E = E->IgnoreParens();
3666
Ted Kremenek06de2762007-08-17 16:46:58 +00003667 // Our "symbolic interpreter" is just a dispatch off the currently
3668 // viewed AST node. We then recursively traverse the AST by calling
3669 // EvalAddr and EvalVal appropriately.
3670 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003671 case Stmt::DeclRefExprClass: {
3672 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3673
3674 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3675 // If this is a reference variable, follow through to the expression that
3676 // it points to.
3677 if (V->hasLocalStorage() &&
3678 V->getType()->isReferenceType() && V->hasInit()) {
3679 // Add the reference variable to the "trail".
3680 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003681 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003682 }
3683
3684 return NULL;
3685 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003686
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003687 case Stmt::UnaryOperatorClass: {
3688 // The only unary operator that make sense to handle here
3689 // is AddrOf. All others don't make sense as pointers.
3690 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003691
John McCall2de56d12010-08-25 11:45:40 +00003692 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003693 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003694 else
Ted Kremenek06de2762007-08-17 16:46:58 +00003695 return NULL;
3696 }
Mike Stump1eb44332009-09-09 15:08:12 +00003697
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003698 case Stmt::BinaryOperatorClass: {
3699 // Handle pointer arithmetic. All other binary operators are not valid
3700 // in this context.
3701 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00003702 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00003703
John McCall2de56d12010-08-25 11:45:40 +00003704 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003705 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00003706
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003707 Expr *Base = B->getLHS();
3708
3709 // Determine which argument is the real pointer base. It could be
3710 // the RHS argument instead of the LHS.
3711 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00003712
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003713 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003714 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003715 }
Steve Naroff61f40a22008-09-10 19:17:48 +00003716
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003717 // For conditional operators we need to see if either the LHS or RHS are
3718 // valid DeclRefExpr*s. If one of them is valid, we return it.
3719 case Stmt::ConditionalOperatorClass: {
3720 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003721
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003722 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003723 if (Expr *lhsExpr = C->getLHS()) {
3724 // In C++, we can have a throw-expression, which has 'void' type.
3725 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003726 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003727 return LHS;
3728 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003729
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003730 // In C++, we can have a throw-expression, which has 'void' type.
3731 if (C->getRHS()->getType()->isVoidType())
3732 return NULL;
3733
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003734 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003735 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003736
3737 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00003738 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003739 return E; // local block.
3740 return NULL;
3741
3742 case Stmt::AddrLabelExprClass:
3743 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00003744
John McCall80ee6e82011-11-10 05:35:25 +00003745 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003746 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
3747 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003748
Ted Kremenek54b52742008-08-07 00:49:01 +00003749 // For casts, we need to handle conversions from arrays to
3750 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00003751 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003752 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003753 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00003754 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00003755 case Stmt::CXXStaticCastExprClass:
3756 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00003757 case Stmt::CXXConstCastExprClass:
3758 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00003759 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3760 switch (cast<CastExpr>(E)->getCastKind()) {
3761 case CK_BitCast:
3762 case CK_LValueToRValue:
3763 case CK_NoOp:
3764 case CK_BaseToDerived:
3765 case CK_DerivedToBase:
3766 case CK_UncheckedDerivedToBase:
3767 case CK_Dynamic:
3768 case CK_CPointerToObjCPointerCast:
3769 case CK_BlockPointerToObjCPointerCast:
3770 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003771 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003772
3773 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003774 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003775
3776 default:
3777 return 0;
3778 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003779 }
Mike Stump1eb44332009-09-09 15:08:12 +00003780
Douglas Gregor03e80032011-06-21 17:03:29 +00003781 case Stmt::MaterializeTemporaryExprClass:
3782 if (Expr *Result = EvalAddr(
3783 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003784 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003785 return Result;
3786
3787 return E;
3788
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003789 // Everything else: we simply don't reason about them.
3790 default:
3791 return NULL;
3792 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003793}
Mike Stump1eb44332009-09-09 15:08:12 +00003794
Ted Kremenek06de2762007-08-17 16:46:58 +00003795
3796/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3797/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003798static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3799 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003800do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003801 // We should only be called for evaluating non-pointer expressions, or
3802 // expressions with a pointer type that are not used as references but instead
3803 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00003804
Ted Kremenek06de2762007-08-17 16:46:58 +00003805 // Our "symbolic interpreter" is just a dispatch off the currently
3806 // viewed AST node. We then recursively traverse the AST by calling
3807 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00003808
3809 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00003810 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003811 case Stmt::ImplicitCastExprClass: {
3812 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00003813 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003814 E = IE->getSubExpr();
3815 continue;
3816 }
3817 return NULL;
3818 }
3819
John McCall80ee6e82011-11-10 05:35:25 +00003820 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003821 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003822
Douglas Gregora2813ce2009-10-23 18:54:35 +00003823 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003824 // When we hit a DeclRefExpr we are looking at code that refers to a
3825 // variable's name. If it's not a reference variable we check if it has
3826 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00003827 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003828
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003829 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
3830 // Check if it refers to itself, e.g. "int& i = i;".
3831 if (V == ParentDecl)
3832 return DR;
3833
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003834 if (V->hasLocalStorage()) {
3835 if (!V->getType()->isReferenceType())
3836 return DR;
3837
3838 // Reference variable, follow through to the expression that
3839 // it points to.
3840 if (V->hasInit()) {
3841 // Add the reference variable to the "trail".
3842 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003843 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003844 }
3845 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003846 }
Mike Stump1eb44332009-09-09 15:08:12 +00003847
Ted Kremenek06de2762007-08-17 16:46:58 +00003848 return NULL;
3849 }
Mike Stump1eb44332009-09-09 15:08:12 +00003850
Ted Kremenek06de2762007-08-17 16:46:58 +00003851 case Stmt::UnaryOperatorClass: {
3852 // The only unary operator that make sense to handle here
3853 // is Deref. All others don't resolve to a "name." This includes
3854 // handling all sorts of rvalues passed to a unary operator.
3855 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003856
John McCall2de56d12010-08-25 11:45:40 +00003857 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003858 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003859
3860 return NULL;
3861 }
Mike Stump1eb44332009-09-09 15:08:12 +00003862
Ted Kremenek06de2762007-08-17 16:46:58 +00003863 case Stmt::ArraySubscriptExprClass: {
3864 // Array subscripts are potential references to data on the stack. We
3865 // retrieve the DeclRefExpr* for the array variable if it indeed
3866 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003867 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003868 }
Mike Stump1eb44332009-09-09 15:08:12 +00003869
Ted Kremenek06de2762007-08-17 16:46:58 +00003870 case Stmt::ConditionalOperatorClass: {
3871 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003872 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003873 ConditionalOperator *C = cast<ConditionalOperator>(E);
3874
Anders Carlsson39073232007-11-30 19:04:31 +00003875 // Handle the GNU extension for missing LHS.
3876 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003877 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00003878 return LHS;
3879
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003880 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003881 }
Mike Stump1eb44332009-09-09 15:08:12 +00003882
Ted Kremenek06de2762007-08-17 16:46:58 +00003883 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003884 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003885 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003886
Ted Kremenek06de2762007-08-17 16:46:58 +00003887 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003888 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003889 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003890
3891 // Check whether the member type is itself a reference, in which case
3892 // we're not going to refer to the member, but to what the member refers to.
3893 if (M->getMemberDecl()->getType()->isReferenceType())
3894 return NULL;
3895
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003896 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003897 }
Mike Stump1eb44332009-09-09 15:08:12 +00003898
Douglas Gregor03e80032011-06-21 17:03:29 +00003899 case Stmt::MaterializeTemporaryExprClass:
3900 if (Expr *Result = EvalVal(
3901 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003902 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003903 return Result;
3904
3905 return E;
3906
Ted Kremenek06de2762007-08-17 16:46:58 +00003907 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003908 // Check that we don't return or take the address of a reference to a
3909 // temporary. This is only useful in C++.
3910 if (!E->isTypeDependent() && E->isRValue())
3911 return E;
3912
3913 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003914 return NULL;
3915 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003916} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003917}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003918
3919//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3920
3921/// Check for comparisons of floating point operands using != and ==.
3922/// Issue a warning if these are no self-comparisons, as they are not likely
3923/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003924void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00003925 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3926 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003927
3928 // Special case: check for x == x (which is OK).
3929 // Do not emit warnings for such cases.
3930 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3931 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3932 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00003933 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003934
3935
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003936 // Special case: check for comparisons against literals that can be exactly
3937 // represented by APFloat. In such cases, do not emit a warning. This
3938 // is a heuristic: often comparison against such literals are used to
3939 // detect if a value in a variable has not changed. This clearly can
3940 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00003941 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3942 if (FLL->isExact())
3943 return;
3944 } else
3945 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
3946 if (FLR->isExact())
3947 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003948
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003949 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00003950 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
3951 if (CL->isBuiltinCall())
3952 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003953
David Blaikie980343b2012-07-16 20:47:22 +00003954 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
3955 if (CR->isBuiltinCall())
3956 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003957
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003958 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00003959 Diag(Loc, diag::warn_floatingpoint_eq)
3960 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003961}
John McCallba26e582010-01-04 23:21:16 +00003962
John McCallf2370c92010-01-06 05:24:50 +00003963//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3964//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003965
John McCallf2370c92010-01-06 05:24:50 +00003966namespace {
John McCallba26e582010-01-04 23:21:16 +00003967
John McCallf2370c92010-01-06 05:24:50 +00003968/// Structure recording the 'active' range of an integer-valued
3969/// expression.
3970struct IntRange {
3971 /// The number of bits active in the int.
3972 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003973
John McCallf2370c92010-01-06 05:24:50 +00003974 /// True if the int is known not to have negative values.
3975 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003976
John McCallf2370c92010-01-06 05:24:50 +00003977 IntRange(unsigned Width, bool NonNegative)
3978 : Width(Width), NonNegative(NonNegative)
3979 {}
John McCallba26e582010-01-04 23:21:16 +00003980
John McCall1844a6e2010-11-10 23:38:19 +00003981 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00003982 static IntRange forBoolType() {
3983 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00003984 }
3985
John McCall1844a6e2010-11-10 23:38:19 +00003986 /// Returns the range of an opaque value of the given integral type.
3987 static IntRange forValueOfType(ASTContext &C, QualType T) {
3988 return forValueOfCanonicalType(C,
3989 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00003990 }
3991
John McCall1844a6e2010-11-10 23:38:19 +00003992 /// Returns the range of an opaque value of a canonical integral type.
3993 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00003994 assert(T->isCanonicalUnqualified());
3995
3996 if (const VectorType *VT = dyn_cast<VectorType>(T))
3997 T = VT->getElementType().getTypePtr();
3998 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3999 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00004000
John McCall091f23f2010-11-09 22:22:12 +00004001 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00004002 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
4003 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00004004 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00004005 return IntRange(C.getIntWidth(QualType(T, 0)), false);
4006
John McCall323ed742010-05-06 08:58:33 +00004007 unsigned NumPositive = Enum->getNumPositiveBits();
4008 unsigned NumNegative = Enum->getNumNegativeBits();
4009
Richard Trieu8f50b242012-11-16 01:32:40 +00004010 if (NumNegative == 0)
4011 return IntRange(NumPositive, true/*NonNegative*/);
4012 else
4013 return IntRange(std::max(NumPositive + 1, NumNegative),
4014 false/*NonNegative*/);
John McCall323ed742010-05-06 08:58:33 +00004015 }
John McCallf2370c92010-01-06 05:24:50 +00004016
4017 const BuiltinType *BT = cast<BuiltinType>(T);
4018 assert(BT->isInteger());
4019
4020 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4021 }
4022
John McCall1844a6e2010-11-10 23:38:19 +00004023 /// Returns the "target" range of a canonical integral type, i.e.
4024 /// the range of values expressible in the type.
4025 ///
4026 /// This matches forValueOfCanonicalType except that enums have the
4027 /// full range of their type, not the range of their enumerators.
4028 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4029 assert(T->isCanonicalUnqualified());
4030
4031 if (const VectorType *VT = dyn_cast<VectorType>(T))
4032 T = VT->getElementType().getTypePtr();
4033 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4034 T = CT->getElementType().getTypePtr();
4035 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00004036 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00004037
4038 const BuiltinType *BT = cast<BuiltinType>(T);
4039 assert(BT->isInteger());
4040
4041 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4042 }
4043
4044 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004045 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00004046 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00004047 L.NonNegative && R.NonNegative);
4048 }
4049
John McCall1844a6e2010-11-10 23:38:19 +00004050 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004051 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00004052 return IntRange(std::min(L.Width, R.Width),
4053 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00004054 }
4055};
4056
Ted Kremenek0692a192012-01-31 05:37:37 +00004057static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4058 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004059 if (value.isSigned() && value.isNegative())
4060 return IntRange(value.getMinSignedBits(), false);
4061
4062 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00004063 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004064
4065 // isNonNegative() just checks the sign bit without considering
4066 // signedness.
4067 return IntRange(value.getActiveBits(), true);
4068}
4069
Ted Kremenek0692a192012-01-31 05:37:37 +00004070static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4071 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004072 if (result.isInt())
4073 return GetValueRange(C, result.getInt(), MaxWidth);
4074
4075 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00004076 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4077 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4078 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4079 R = IntRange::join(R, El);
4080 }
John McCallf2370c92010-01-06 05:24:50 +00004081 return R;
4082 }
4083
4084 if (result.isComplexInt()) {
4085 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4086 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4087 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00004088 }
4089
4090 // This can happen with lossless casts to intptr_t of "based" lvalues.
4091 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00004092 // FIXME: The only reason we need to pass the type in here is to get
4093 // the sign right on this one case. It would be nice if APValue
4094 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00004095 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004096 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00004097}
John McCallf2370c92010-01-06 05:24:50 +00004098
4099/// Pseudo-evaluate the given integer expression, estimating the
4100/// range of values it might take.
4101///
4102/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00004103static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004104 E = E->IgnoreParens();
4105
4106 // Try a full evaluation first.
4107 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004108 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00004109 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004110
4111 // I think we only want to look through implicit casts here; if the
4112 // user has an explicit widening cast, we should treat the value as
4113 // being of the new, wider type.
4114 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00004115 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00004116 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4117
John McCall1844a6e2010-11-10 23:38:19 +00004118 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00004119
John McCall2de56d12010-08-25 11:45:40 +00004120 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00004121
John McCallf2370c92010-01-06 05:24:50 +00004122 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00004123 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00004124 return OutputTypeRange;
4125
4126 IntRange SubRange
4127 = GetExprRange(C, CE->getSubExpr(),
4128 std::min(MaxWidth, OutputTypeRange.Width));
4129
4130 // Bail out if the subexpr's range is as wide as the cast type.
4131 if (SubRange.Width >= OutputTypeRange.Width)
4132 return OutputTypeRange;
4133
4134 // Otherwise, we take the smaller width, and we're non-negative if
4135 // either the output type or the subexpr is.
4136 return IntRange(SubRange.Width,
4137 SubRange.NonNegative || OutputTypeRange.NonNegative);
4138 }
4139
4140 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4141 // If we can fold the condition, just take that operand.
4142 bool CondResult;
4143 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4144 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4145 : CO->getFalseExpr(),
4146 MaxWidth);
4147
4148 // Otherwise, conservatively merge.
4149 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4150 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4151 return IntRange::join(L, R);
4152 }
4153
4154 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4155 switch (BO->getOpcode()) {
4156
4157 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00004158 case BO_LAnd:
4159 case BO_LOr:
4160 case BO_LT:
4161 case BO_GT:
4162 case BO_LE:
4163 case BO_GE:
4164 case BO_EQ:
4165 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00004166 return IntRange::forBoolType();
4167
John McCall862ff872011-07-13 06:35:24 +00004168 // The type of the assignments is the type of the LHS, so the RHS
4169 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00004170 case BO_MulAssign:
4171 case BO_DivAssign:
4172 case BO_RemAssign:
4173 case BO_AddAssign:
4174 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00004175 case BO_XorAssign:
4176 case BO_OrAssign:
4177 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00004178 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00004179
John McCall862ff872011-07-13 06:35:24 +00004180 // Simple assignments just pass through the RHS, which will have
4181 // been coerced to the LHS type.
4182 case BO_Assign:
4183 // TODO: bitfields?
4184 return GetExprRange(C, BO->getRHS(), MaxWidth);
4185
John McCallf2370c92010-01-06 05:24:50 +00004186 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004187 case BO_PtrMemD:
4188 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00004189 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004190
John McCall60fad452010-01-06 22:07:33 +00004191 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00004192 case BO_And:
4193 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00004194 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4195 GetExprRange(C, BO->getRHS(), MaxWidth));
4196
John McCallf2370c92010-01-06 05:24:50 +00004197 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00004198 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00004199 // ...except that we want to treat '1 << (blah)' as logically
4200 // positive. It's an important idiom.
4201 if (IntegerLiteral *I
4202 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4203 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00004204 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00004205 return IntRange(R.Width, /*NonNegative*/ true);
4206 }
4207 }
4208 // fallthrough
4209
John McCall2de56d12010-08-25 11:45:40 +00004210 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00004211 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004212
John McCall60fad452010-01-06 22:07:33 +00004213 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00004214 case BO_Shr:
4215 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00004216 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4217
4218 // If the shift amount is a positive constant, drop the width by
4219 // that much.
4220 llvm::APSInt shift;
4221 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4222 shift.isNonNegative()) {
4223 unsigned zext = shift.getZExtValue();
4224 if (zext >= L.Width)
4225 L.Width = (L.NonNegative ? 0 : 1);
4226 else
4227 L.Width -= zext;
4228 }
4229
4230 return L;
4231 }
4232
4233 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00004234 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00004235 return GetExprRange(C, BO->getRHS(), MaxWidth);
4236
John McCall60fad452010-01-06 22:07:33 +00004237 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00004238 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00004239 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00004240 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00004241 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00004242
John McCall00fe7612011-07-14 22:39:48 +00004243 // The width of a division result is mostly determined by the size
4244 // of the LHS.
4245 case BO_Div: {
4246 // Don't 'pre-truncate' the operands.
4247 unsigned opWidth = C.getIntWidth(E->getType());
4248 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4249
4250 // If the divisor is constant, use that.
4251 llvm::APSInt divisor;
4252 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4253 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4254 if (log2 >= L.Width)
4255 L.Width = (L.NonNegative ? 0 : 1);
4256 else
4257 L.Width = std::min(L.Width - log2, MaxWidth);
4258 return L;
4259 }
4260
4261 // Otherwise, just use the LHS's width.
4262 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4263 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4264 }
4265
4266 // The result of a remainder can't be larger than the result of
4267 // either side.
4268 case BO_Rem: {
4269 // Don't 'pre-truncate' the operands.
4270 unsigned opWidth = C.getIntWidth(E->getType());
4271 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4272 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4273
4274 IntRange meet = IntRange::meet(L, R);
4275 meet.Width = std::min(meet.Width, MaxWidth);
4276 return meet;
4277 }
4278
4279 // The default behavior is okay for these.
4280 case BO_Mul:
4281 case BO_Add:
4282 case BO_Xor:
4283 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00004284 break;
4285 }
4286
John McCall00fe7612011-07-14 22:39:48 +00004287 // The default case is to treat the operation as if it were closed
4288 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004289 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4290 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4291 return IntRange::join(L, R);
4292 }
4293
4294 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4295 switch (UO->getOpcode()) {
4296 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004297 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004298 return IntRange::forBoolType();
4299
4300 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004301 case UO_Deref:
4302 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00004303 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004304
4305 default:
4306 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4307 }
4308 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004309
4310 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00004311 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004312 }
John McCallf2370c92010-01-06 05:24:50 +00004313
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004314 if (FieldDecl *BitField = E->getBitField())
4315 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004316 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004317
John McCall1844a6e2010-11-10 23:38:19 +00004318 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004319}
John McCall51313c32010-01-04 23:31:57 +00004320
Ted Kremenek0692a192012-01-31 05:37:37 +00004321static IntRange GetExprRange(ASTContext &C, Expr *E) {
John McCall323ed742010-05-06 08:58:33 +00004322 return GetExprRange(C, E, C.getIntWidth(E->getType()));
4323}
4324
John McCall51313c32010-01-04 23:31:57 +00004325/// Checks whether the given value, which currently has the given
4326/// source semantics, has the same value when coerced through the
4327/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004328static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4329 const llvm::fltSemantics &Src,
4330 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004331 llvm::APFloat truncated = value;
4332
4333 bool ignored;
4334 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4335 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4336
4337 return truncated.bitwiseIsEqual(value);
4338}
4339
4340/// Checks whether the given value, which currently has the given
4341/// source semantics, has the same value when coerced through the
4342/// target semantics.
4343///
4344/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004345static bool IsSameFloatAfterCast(const APValue &value,
4346 const llvm::fltSemantics &Src,
4347 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004348 if (value.isFloat())
4349 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4350
4351 if (value.isVector()) {
4352 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4353 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4354 return false;
4355 return true;
4356 }
4357
4358 assert(value.isComplexFloat());
4359 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4360 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4361}
4362
Ted Kremenek0692a192012-01-31 05:37:37 +00004363static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004364
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004365static bool IsZero(Sema &S, Expr *E) {
4366 // Suppress cases where we are comparing against an enum constant.
4367 if (const DeclRefExpr *DR =
4368 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4369 if (isa<EnumConstantDecl>(DR->getDecl()))
4370 return false;
4371
4372 // Suppress cases where the '0' value is expanded from a macro.
4373 if (E->getLocStart().isMacroID())
4374 return false;
4375
John McCall323ed742010-05-06 08:58:33 +00004376 llvm::APSInt Value;
4377 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4378}
4379
John McCall372e1032010-10-06 00:25:24 +00004380static bool HasEnumType(Expr *E) {
4381 // Strip off implicit integral promotions.
4382 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004383 if (ICE->getCastKind() != CK_IntegralCast &&
4384 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004385 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004386 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004387 }
4388
4389 return E->getType()->isEnumeralType();
4390}
4391
Ted Kremenek0692a192012-01-31 05:37:37 +00004392static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004393 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004394 if (E->isValueDependent())
4395 return;
4396
John McCall2de56d12010-08-25 11:45:40 +00004397 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004398 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004399 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004400 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004401 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004402 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004403 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004404 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004405 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004406 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004407 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004408 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004409 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004410 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004411 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004412 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4413 }
4414}
4415
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004416static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004417 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004418 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004419 bool RhsConstant) {
Richard Trieu526e6272012-11-14 22:50:24 +00004420 // 0 values are handled later by CheckTrivialUnsignedComparison().
4421 if (Value == 0)
4422 return;
4423
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004424 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004425 QualType OtherT = Other->getType();
4426 QualType ConstantT = Constant->getType();
Richard Trieu526e6272012-11-14 22:50:24 +00004427 QualType CommonT = E->getLHS()->getType();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004428 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004429 return;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004430 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004431 && "comparison with non-integer type");
Richard Trieu526e6272012-11-14 22:50:24 +00004432
4433 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu526e6272012-11-14 22:50:24 +00004434 bool CommonSigned = CommonT->isSignedIntegerType();
4435
4436 bool EqualityOnly = false;
4437
4438 // TODO: Investigate using GetExprRange() to get tighter bounds on
4439 // on the bit ranges.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004440 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu526e6272012-11-14 22:50:24 +00004441 unsigned OtherWidth = OtherRange.Width;
4442
4443 if (CommonSigned) {
4444 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedmand87de7b2012-11-30 23:09:29 +00004445 if (!OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004446 // Check that the constant is representable in type OtherT.
4447 if (ConstantSigned) {
4448 if (OtherWidth >= Value.getMinSignedBits())
4449 return;
4450 } else { // !ConstantSigned
4451 if (OtherWidth >= Value.getActiveBits() + 1)
4452 return;
4453 }
4454 } else { // !OtherSigned
4455 // Check that the constant is representable in type OtherT.
4456 // Negative values are out of range.
4457 if (ConstantSigned) {
4458 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4459 return;
4460 } else { // !ConstantSigned
4461 if (OtherWidth >= Value.getActiveBits())
4462 return;
4463 }
4464 }
4465 } else { // !CommonSigned
Eli Friedmand87de7b2012-11-30 23:09:29 +00004466 if (OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004467 if (OtherWidth >= Value.getActiveBits())
4468 return;
Eli Friedmand87de7b2012-11-30 23:09:29 +00004469 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu526e6272012-11-14 22:50:24 +00004470 // Check to see if the constant is representable in OtherT.
4471 if (OtherWidth > Value.getActiveBits())
4472 return;
4473 // Check to see if the constant is equivalent to a negative value
4474 // cast to CommonT.
4475 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu5d1cf4f2012-11-15 03:43:50 +00004476 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu526e6272012-11-14 22:50:24 +00004477 return;
4478 // The constant value rests between values that OtherT can represent after
4479 // conversion. Relational comparison still works, but equality
4480 // comparisons will be tautological.
4481 EqualityOnly = true;
4482 } else { // OtherSigned && ConstantSigned
4483 assert(0 && "Two signed types converted to unsigned types.");
4484 }
4485 }
4486
4487 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4488
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004489 bool IsTrue = true;
Richard Trieu526e6272012-11-14 22:50:24 +00004490 if (op == BO_EQ || op == BO_NE) {
4491 IsTrue = op == BO_NE;
4492 } else if (EqualityOnly) {
4493 return;
4494 } else if (RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004495 if (op == BO_GT || op == BO_GE)
Richard Trieu526e6272012-11-14 22:50:24 +00004496 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004497 else // op == BO_LT || op == BO_LE
Richard Trieu526e6272012-11-14 22:50:24 +00004498 IsTrue = PositiveConstant;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004499 } else {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004500 if (op == BO_LT || op == BO_LE)
Richard Trieu526e6272012-11-14 22:50:24 +00004501 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004502 else // op == BO_GT || op == BO_GE
Richard Trieu526e6272012-11-14 22:50:24 +00004503 IsTrue = PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004504 }
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004505
4506 // If this is a comparison to an enum constant, include that
4507 // constant in the diagnostic.
4508 const EnumConstantDecl *ED = 0;
4509 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
4510 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
4511
4512 SmallString<64> PrettySourceValue;
4513 llvm::raw_svector_ostream OS(PrettySourceValue);
4514 if (ED)
Ted Kremenek9de50942013-03-15 22:02:46 +00004515 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004516 else
4517 OS << Value;
4518
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004519 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004520 << OS.str() << OtherT << IsTrue
Richard Trieu526e6272012-11-14 22:50:24 +00004521 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004522}
4523
John McCall323ed742010-05-06 08:58:33 +00004524/// Analyze the operands of the given comparison. Implements the
4525/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004526static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004527 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4528 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004529}
John McCall51313c32010-01-04 23:31:57 +00004530
John McCallba26e582010-01-04 23:21:16 +00004531/// \brief Implements -Wsign-compare.
4532///
Richard Trieudd225092011-09-15 21:56:47 +00004533/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004534static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004535 // The type the comparison is being performed in.
4536 QualType T = E->getLHS()->getType();
4537 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4538 && "comparison with mismatched types");
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00004539 if (E->isValueDependent())
4540 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004541
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004542 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4543 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004544
4545 bool IsComparisonConstant = false;
4546
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004547 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004548 // of 'true' or 'false'.
4549 if (T->isIntegralType(S.Context)) {
4550 llvm::APSInt RHSValue;
4551 bool IsRHSIntegralLiteral =
4552 RHS->isIntegerConstantExpr(RHSValue, S.Context);
4553 llvm::APSInt LHSValue;
4554 bool IsLHSIntegralLiteral =
4555 LHS->isIntegerConstantExpr(LHSValue, S.Context);
4556 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4557 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4558 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4559 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4560 else
4561 IsComparisonConstant =
4562 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004563 } else if (!T->hasUnsignedIntegerRepresentation())
4564 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004565
John McCall323ed742010-05-06 08:58:33 +00004566 // We don't do anything special if this isn't an unsigned integral
4567 // comparison: we're only interested in integral comparisons, and
4568 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004569 //
4570 // We also don't care about value-dependent expressions or expressions
4571 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004572 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00004573 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004574
John McCall323ed742010-05-06 08:58:33 +00004575 // Check to see if one of the (unmodified) operands is of different
4576 // signedness.
4577 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004578 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4579 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004580 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004581 signedOperand = LHS;
4582 unsignedOperand = RHS;
4583 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4584 signedOperand = RHS;
4585 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004586 } else {
John McCall323ed742010-05-06 08:58:33 +00004587 CheckTrivialUnsignedComparison(S, E);
4588 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004589 }
4590
John McCall323ed742010-05-06 08:58:33 +00004591 // Otherwise, calculate the effective range of the signed operand.
4592 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004593
John McCall323ed742010-05-06 08:58:33 +00004594 // Go ahead and analyze implicit conversions in the operands. Note
4595 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004596 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4597 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004598
John McCall323ed742010-05-06 08:58:33 +00004599 // If the signed range is non-negative, -Wsign-compare won't fire,
4600 // but we should still check for comparisons which are always true
4601 // or false.
4602 if (signedRange.NonNegative)
4603 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004604
4605 // For (in)equality comparisons, if the unsigned operand is a
4606 // constant which cannot collide with a overflowed signed operand,
4607 // then reinterpreting the signed operand as unsigned will not
4608 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00004609 if (E->isEqualityOp()) {
4610 unsigned comparisonWidth = S.Context.getIntWidth(T);
4611 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00004612
John McCall323ed742010-05-06 08:58:33 +00004613 // We should never be unable to prove that the unsigned operand is
4614 // non-negative.
4615 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
4616
4617 if (unsignedRange.Width < comparisonWidth)
4618 return;
4619 }
4620
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00004621 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4622 S.PDiag(diag::warn_mixed_sign_comparison)
4623 << LHS->getType() << RHS->getType()
4624 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00004625}
4626
John McCall15d7d122010-11-11 03:21:53 +00004627/// Analyzes an attempt to assign the given value to a bitfield.
4628///
4629/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00004630static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4631 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00004632 assert(Bitfield->isBitField());
4633 if (Bitfield->isInvalidDecl())
4634 return false;
4635
John McCall91b60142010-11-11 05:33:51 +00004636 // White-list bool bitfields.
4637 if (Bitfield->getType()->isBooleanType())
4638 return false;
4639
Douglas Gregor46ff3032011-02-04 13:09:01 +00004640 // Ignore value- or type-dependent expressions.
4641 if (Bitfield->getBitWidth()->isValueDependent() ||
4642 Bitfield->getBitWidth()->isTypeDependent() ||
4643 Init->isValueDependent() ||
4644 Init->isTypeDependent())
4645 return false;
4646
John McCall15d7d122010-11-11 03:21:53 +00004647 Expr *OriginalInit = Init->IgnoreParenImpCasts();
4648
Richard Smith80d4b552011-12-28 19:48:30 +00004649 llvm::APSInt Value;
4650 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00004651 return false;
4652
John McCall15d7d122010-11-11 03:21:53 +00004653 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004654 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00004655
4656 if (OriginalWidth <= FieldWidth)
4657 return false;
4658
Eli Friedman3a643af2012-01-26 23:11:39 +00004659 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004660 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00004661 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00004662
Eli Friedman3a643af2012-01-26 23:11:39 +00004663 // Check whether the stored value is equal to the original value.
4664 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00004665 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00004666 return false;
4667
Eli Friedman3a643af2012-01-26 23:11:39 +00004668 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00004669 // therefore don't strictly fit into a signed bitfield of width 1.
4670 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00004671 return false;
4672
John McCall15d7d122010-11-11 03:21:53 +00004673 std::string PrettyValue = Value.toString(10);
4674 std::string PrettyTrunc = TruncatedValue.toString(10);
4675
4676 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4677 << PrettyValue << PrettyTrunc << OriginalInit->getType()
4678 << Init->getSourceRange();
4679
4680 return true;
4681}
4682
John McCallbeb22aa2010-11-09 23:24:47 +00004683/// Analyze the given simple or compound assignment for warning-worthy
4684/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00004685static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00004686 // Just recurse on the LHS.
4687 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4688
4689 // We want to recurse on the RHS as normal unless we're assigning to
4690 // a bitfield.
4691 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00004692 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall15d7d122010-11-11 03:21:53 +00004693 E->getOperatorLoc())) {
4694 // Recurse, ignoring any implicit conversions on the RHS.
4695 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
4696 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00004697 }
4698 }
4699
4700 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4701}
4702
John McCall51313c32010-01-04 23:31:57 +00004703/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004704static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004705 SourceLocation CContext, unsigned diag,
4706 bool pruneControlFlow = false) {
4707 if (pruneControlFlow) {
4708 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4709 S.PDiag(diag)
4710 << SourceType << T << E->getSourceRange()
4711 << SourceRange(CContext));
4712 return;
4713 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004714 S.Diag(E->getExprLoc(), diag)
4715 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
4716}
4717
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004718/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004719static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004720 SourceLocation CContext, unsigned diag,
4721 bool pruneControlFlow = false) {
4722 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004723}
4724
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004725/// Diagnose an implicit cast from a literal expression. Does not warn when the
4726/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004727void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
4728 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004729 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004730 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004731 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00004732 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
4733 T->hasUnsignedIntegerRepresentation());
4734 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00004735 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004736 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00004737 return;
4738
David Blaikiebe0ee872012-05-15 16:56:36 +00004739 SmallString<16> PrettySourceValue;
4740 Value.toString(PrettySourceValue);
David Blaikiede7e7b82012-05-15 17:18:27 +00004741 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00004742 if (T->isSpecificBuiltinType(BuiltinType::Bool))
4743 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
4744 else
David Blaikiede7e7b82012-05-15 17:18:27 +00004745 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00004746
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004747 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00004748 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
4749 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00004750}
4751
John McCall091f23f2010-11-09 22:22:12 +00004752std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
4753 if (!Range.Width) return "0";
4754
4755 llvm::APSInt ValueInRange = Value;
4756 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00004757 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00004758 return ValueInRange.toString(10);
4759}
4760
Hans Wennborg88617a22012-08-28 15:44:30 +00004761static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
4762 if (!isa<ImplicitCastExpr>(Ex))
4763 return false;
4764
4765 Expr *InnerE = Ex->IgnoreParenImpCasts();
4766 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
4767 const Type *Source =
4768 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4769 if (Target->isDependentType())
4770 return false;
4771
4772 const BuiltinType *FloatCandidateBT =
4773 dyn_cast<BuiltinType>(ToBool ? Source : Target);
4774 const Type *BoolCandidateType = ToBool ? Target : Source;
4775
4776 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
4777 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
4778}
4779
4780void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
4781 SourceLocation CC) {
4782 unsigned NumArgs = TheCall->getNumArgs();
4783 for (unsigned i = 0; i < NumArgs; ++i) {
4784 Expr *CurrA = TheCall->getArg(i);
4785 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
4786 continue;
4787
4788 bool IsSwapped = ((i > 0) &&
4789 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
4790 IsSwapped |= ((i < (NumArgs - 1)) &&
4791 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
4792 if (IsSwapped) {
4793 // Warn on this floating-point to bool conversion.
4794 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
4795 CurrA->getType(), CC,
4796 diag::warn_impcast_floating_point_to_bool);
4797 }
4798 }
4799}
4800
John McCall323ed742010-05-06 08:58:33 +00004801void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00004802 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00004803 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00004804
John McCall323ed742010-05-06 08:58:33 +00004805 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
4806 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
4807 if (Source == Target) return;
4808 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00004809
Chandler Carruth108f7562011-07-26 05:40:03 +00004810 // If the conversion context location is invalid don't complain. We also
4811 // don't want to emit a warning if the issue occurs from the expansion of
4812 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
4813 // delay this check as long as possible. Once we detect we are in that
4814 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00004815 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00004816 return;
4817
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004818 // Diagnose implicit casts to bool.
4819 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
4820 if (isa<StringLiteral>(E))
4821 // Warn on string literal to bool. Checks for string literals in logical
4822 // expressions, for instances, assert(0 && "error here"), is prevented
4823 // by a check in AnalyzeImplicitConversions().
4824 return DiagnoseImpCast(S, E, T, CC,
4825 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00004826 if (Source->isFunctionType()) {
4827 // Warn on function to bool. Checks free functions and static member
4828 // functions. Weakly imported functions are excluded from the check,
4829 // since it's common to test their value to check whether the linker
4830 // found a definition for them.
4831 ValueDecl *D = 0;
4832 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
4833 D = R->getDecl();
4834 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
4835 D = M->getMemberDecl();
4836 }
4837
4838 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00004839 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
4840 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
4841 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00004842 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
4843 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
4844 QualType ReturnType;
4845 UnresolvedSet<4> NonTemplateOverloads;
4846 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
4847 if (!ReturnType.isNull()
4848 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
4849 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
4850 << FixItHint::CreateInsertion(
4851 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00004852 return;
4853 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00004854 }
4855 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004856 }
John McCall51313c32010-01-04 23:31:57 +00004857
4858 // Strip vector types.
4859 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004860 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004861 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004862 return;
John McCallb4eb64d2010-10-08 02:01:28 +00004863 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004864 }
Chris Lattnerb792b302011-06-14 04:51:15 +00004865
4866 // If the vector cast is cast between two vectors of the same size, it is
4867 // a bitcast, not a conversion.
4868 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4869 return;
John McCall51313c32010-01-04 23:31:57 +00004870
4871 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4872 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4873 }
4874
4875 // Strip complex types.
4876 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004877 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004878 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004879 return;
4880
John McCallb4eb64d2010-10-08 02:01:28 +00004881 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004882 }
John McCall51313c32010-01-04 23:31:57 +00004883
4884 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4885 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4886 }
4887
4888 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4889 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4890
4891 // If the source is floating point...
4892 if (SourceBT && SourceBT->isFloatingPoint()) {
4893 // ...and the target is floating point...
4894 if (TargetBT && TargetBT->isFloatingPoint()) {
4895 // ...then warn if we're dropping FP rank.
4896
4897 // Builtin FP kinds are ordered by increasing FP rank.
4898 if (SourceBT->getKind() > TargetBT->getKind()) {
4899 // Don't warn about float constants that are precisely
4900 // representable in the target type.
4901 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004902 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00004903 // Value might be a float, a float vector, or a float complex.
4904 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00004905 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4906 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00004907 return;
4908 }
4909
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004910 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004911 return;
4912
John McCallb4eb64d2010-10-08 02:01:28 +00004913 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00004914 }
4915 return;
4916 }
4917
Ted Kremenekef9ff882011-03-10 20:03:42 +00004918 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00004919 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004920 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004921 return;
4922
Chandler Carrutha5b93322011-02-17 11:05:49 +00004923 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00004924 // We also want to warn on, e.g., "int i = -1.234"
4925 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4926 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4927 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
4928
Chandler Carruthf65076e2011-04-10 08:36:24 +00004929 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4930 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00004931 } else {
4932 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4933 }
4934 }
John McCall51313c32010-01-04 23:31:57 +00004935
Hans Wennborg88617a22012-08-28 15:44:30 +00004936 // If the target is bool, warn if expr is a function or method call.
4937 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
4938 isa<CallExpr>(E)) {
4939 // Check last argument of function call to see if it is an
4940 // implicit cast from a type matching the type the result
4941 // is being cast to.
4942 CallExpr *CEx = cast<CallExpr>(E);
4943 unsigned NumArgs = CEx->getNumArgs();
4944 if (NumArgs > 0) {
4945 Expr *LastA = CEx->getArg(NumArgs - 1);
4946 Expr *InnerE = LastA->IgnoreParenImpCasts();
4947 const Type *InnerType =
4948 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4949 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
4950 // Warn on this floating-point to bool conversion
4951 DiagnoseImpCast(S, E, T, CC,
4952 diag::warn_impcast_floating_point_to_bool);
4953 }
4954 }
4955 }
John McCall51313c32010-01-04 23:31:57 +00004956 return;
4957 }
4958
Richard Trieu1838ca52011-05-29 19:59:02 +00004959 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00004960 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiee81b43b2012-11-08 00:41:20 +00004961 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikie896c7dd2013-02-16 00:56:22 +00004962 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieb1360492012-03-16 20:30:12 +00004963 SourceLocation Loc = E->getSourceRange().getBegin();
4964 if (Loc.isMacroID())
4965 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00004966 if (!Loc.isMacroID() || CC.isMacroID())
4967 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
4968 << T << clang::SourceRange(CC)
4969 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
Richard Trieu1838ca52011-05-29 19:59:02 +00004970 }
4971
David Blaikieb26331b2012-06-19 21:19:06 +00004972 if (!Source->isIntegerType() || !Target->isIntegerType())
4973 return;
4974
David Blaikiebe0ee872012-05-15 16:56:36 +00004975 // TODO: remove this early return once the false positives for constant->bool
4976 // in templates, macros, etc, are reduced or removed.
4977 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
4978 return;
4979
John McCall323ed742010-05-06 08:58:33 +00004980 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00004981 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00004982
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00004983 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer25ffbef2013-03-28 19:07:11 +00004984 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00004985 // TODO: this should happen for bitfield stores, too.
4986 llvm::APSInt Value(32);
4987 if (E->isIntegerConstantExpr(Value, S.Context)) {
4988 if (S.SourceMgr.isInSystemMacro(CC))
4989 return;
4990
John McCall091f23f2010-11-09 22:22:12 +00004991 std::string PrettySourceValue = Value.toString(10);
4992 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00004993
Ted Kremenek5e745da2011-10-22 02:37:33 +00004994 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4995 S.PDiag(diag::warn_impcast_integer_precision_constant)
4996 << PrettySourceValue << PrettyTargetValue
4997 << E->getType() << T << E->getSourceRange()
4998 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00004999 return;
5000 }
5001
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005002 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5003 if (S.SourceMgr.isInSystemMacro(CC))
5004 return;
5005
David Blaikie37050842012-04-12 22:40:54 +00005006 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00005007 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5008 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00005009 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00005010 }
5011
5012 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5013 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5014 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005015
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005016 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005017 return;
5018
John McCall323ed742010-05-06 08:58:33 +00005019 unsigned DiagID = diag::warn_impcast_integer_sign;
5020
5021 // Traditionally, gcc has warned about this under -Wsign-compare.
5022 // We also want to warn about it in -Wconversion.
5023 // So if -Wconversion is off, use a completely identical diagnostic
5024 // in the sign-compare group.
5025 // The conditional-checking code will
5026 if (ICContext) {
5027 DiagID = diag::warn_impcast_integer_sign_conditional;
5028 *ICContext = true;
5029 }
5030
John McCallb4eb64d2010-10-08 02:01:28 +00005031 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00005032 }
5033
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005034 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005035 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5036 // type, to give us better diagnostics.
5037 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00005038 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005039 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5040 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5041 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5042 SourceType = S.Context.getTypeDeclType(Enum);
5043 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5044 }
5045 }
5046
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005047 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5048 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall83972f12013-03-09 00:54:27 +00005049 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5050 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00005051 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005052 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005053 return;
5054
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005055 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005056 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005057 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005058
John McCall51313c32010-01-04 23:31:57 +00005059 return;
5060}
5061
David Blaikie9fb1ac52012-05-15 21:57:38 +00005062void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5063 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00005064
5065void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00005066 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00005067 E = E->IgnoreParenImpCasts();
5068
5069 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00005070 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00005071
John McCallb4eb64d2010-10-08 02:01:28 +00005072 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005073 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005074 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00005075 return;
5076}
5077
David Blaikie9fb1ac52012-05-15 21:57:38 +00005078void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5079 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00005080 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00005081
5082 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00005083 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5084 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005085
5086 // If -Wconversion would have warned about either of the candidates
5087 // for a signedness conversion to the context type...
5088 if (!Suspicious) return;
5089
5090 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005091 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5092 CC))
John McCall323ed742010-05-06 08:58:33 +00005093 return;
5094
John McCall323ed742010-05-06 08:58:33 +00005095 // ...then check whether it would have warned about either of the
5096 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00005097 if (E->getType() == T) return;
5098
5099 Suspicious = false;
5100 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5101 E->getType(), CC, &Suspicious);
5102 if (!Suspicious)
5103 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00005104 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005105}
5106
5107/// AnalyzeImplicitConversions - Find and report any interesting
5108/// implicit conversions in the given expression. There are a couple
5109/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005110void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005111 QualType T = OrigE->getType();
5112 Expr *E = OrigE->IgnoreParenImpCasts();
5113
Douglas Gregorf8b6e152011-10-10 17:38:18 +00005114 if (E->isTypeDependent() || E->isValueDependent())
5115 return;
5116
John McCall323ed742010-05-06 08:58:33 +00005117 // For conditional operators, we analyze the arguments as if they
5118 // were being fed directly into the output.
5119 if (isa<ConditionalOperator>(E)) {
5120 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00005121 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00005122 return;
5123 }
5124
Hans Wennborg88617a22012-08-28 15:44:30 +00005125 // Check implicit argument conversions for function calls.
5126 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5127 CheckImplicitArgumentConversions(S, Call, CC);
5128
John McCall323ed742010-05-06 08:58:33 +00005129 // Go ahead and check any implicit conversions we might have skipped.
5130 // The non-canonical typecheck is just an optimization;
5131 // CheckImplicitConversion will filter out dead implicit conversions.
5132 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005133 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00005134
5135 // Now continue drilling into this expression.
5136
5137 // Skip past explicit casts.
5138 if (isa<ExplicitCastExpr>(E)) {
5139 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00005140 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005141 }
5142
John McCallbeb22aa2010-11-09 23:24:47 +00005143 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5144 // Do a somewhat different check with comparison operators.
5145 if (BO->isComparisonOp())
5146 return AnalyzeComparison(S, BO);
5147
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005148 // And with simple assignments.
5149 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00005150 return AnalyzeAssignment(S, BO);
5151 }
John McCall323ed742010-05-06 08:58:33 +00005152
5153 // These break the otherwise-useful invariant below. Fortunately,
5154 // we don't really need to recurse into them, because any internal
5155 // expressions should have been analyzed already when they were
5156 // built into statements.
5157 if (isa<StmtExpr>(E)) return;
5158
5159 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005160 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00005161
5162 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00005163 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005164 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5165 bool IsLogicalOperator = BO && BO->isLogicalOp();
5166 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00005167 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00005168 if (!ChildExpr)
5169 continue;
5170
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005171 if (IsLogicalOperator &&
5172 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5173 // Ignore checking string literals that are in logical operators.
5174 continue;
5175 AnalyzeImplicitConversions(S, ChildExpr, CC);
5176 }
John McCall323ed742010-05-06 08:58:33 +00005177}
5178
5179} // end anonymous namespace
5180
5181/// Diagnoses "dangerous" implicit conversions within the given
5182/// expression (which is a full expression). Implements -Wconversion
5183/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005184///
5185/// \param CC the "context" location of the implicit conversion, i.e.
5186/// the most location of the syntactic entity requiring the implicit
5187/// conversion
5188void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005189 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00005190 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00005191 return;
5192
5193 // Don't diagnose for value- or type-dependent expressions.
5194 if (E->isTypeDependent() || E->isValueDependent())
5195 return;
5196
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005197 // Check for array bounds violations in cases where the check isn't triggered
5198 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5199 // ArraySubscriptExpr is on the RHS of a variable initialization.
5200 CheckArrayAccess(E);
5201
John McCallb4eb64d2010-10-08 02:01:28 +00005202 // This is not the right CC for (e.g.) a variable initialization.
5203 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005204}
5205
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005206/// Diagnose when expression is an integer constant expression and its evaluation
5207/// results in integer overflow
5208void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanian1fd8d462013-03-15 20:47:07 +00005209 if (isa<BinaryOperator>(E->IgnoreParens())) {
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005210 llvm::SmallVector<PartialDiagnosticAt, 4> Diags;
5211 E->EvaluateForOverflow(Context, &Diags);
5212 }
5213}
5214
Richard Smith6c3af3d2013-01-17 01:17:56 +00005215namespace {
5216/// \brief Visitor for expressions which looks for unsequenced operations on the
5217/// same object.
5218class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
5219 /// \brief A tree of sequenced regions within an expression. Two regions are
5220 /// unsequenced if one is an ancestor or a descendent of the other. When we
5221 /// finish processing an expression with sequencing, such as a comma
5222 /// expression, we fold its tree nodes into its parent, since they are
5223 /// unsequenced with respect to nodes we will visit later.
5224 class SequenceTree {
5225 struct Value {
5226 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5227 unsigned Parent : 31;
5228 bool Merged : 1;
5229 };
5230 llvm::SmallVector<Value, 8> Values;
5231
5232 public:
5233 /// \brief A region within an expression which may be sequenced with respect
5234 /// to some other region.
5235 class Seq {
5236 explicit Seq(unsigned N) : Index(N) {}
5237 unsigned Index;
5238 friend class SequenceTree;
5239 public:
5240 Seq() : Index(0) {}
5241 };
5242
5243 SequenceTree() { Values.push_back(Value(0)); }
5244 Seq root() const { return Seq(0); }
5245
5246 /// \brief Create a new sequence of operations, which is an unsequenced
5247 /// subset of \p Parent. This sequence of operations is sequenced with
5248 /// respect to other children of \p Parent.
5249 Seq allocate(Seq Parent) {
5250 Values.push_back(Value(Parent.Index));
5251 return Seq(Values.size() - 1);
5252 }
5253
5254 /// \brief Merge a sequence of operations into its parent.
5255 void merge(Seq S) {
5256 Values[S.Index].Merged = true;
5257 }
5258
5259 /// \brief Determine whether two operations are unsequenced. This operation
5260 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5261 /// should have been merged into its parent as appropriate.
5262 bool isUnsequenced(Seq Cur, Seq Old) {
5263 unsigned C = representative(Cur.Index);
5264 unsigned Target = representative(Old.Index);
5265 while (C >= Target) {
5266 if (C == Target)
5267 return true;
5268 C = Values[C].Parent;
5269 }
5270 return false;
5271 }
5272
5273 private:
5274 /// \brief Pick a representative for a sequence.
5275 unsigned representative(unsigned K) {
5276 if (Values[K].Merged)
5277 // Perform path compression as we go.
5278 return Values[K].Parent = representative(Values[K].Parent);
5279 return K;
5280 }
5281 };
5282
5283 /// An object for which we can track unsequenced uses.
5284 typedef NamedDecl *Object;
5285
5286 /// Different flavors of object usage which we track. We only track the
5287 /// least-sequenced usage of each kind.
5288 enum UsageKind {
5289 /// A read of an object. Multiple unsequenced reads are OK.
5290 UK_Use,
5291 /// A modification of an object which is sequenced before the value
5292 /// computation of the expression, such as ++n.
5293 UK_ModAsValue,
5294 /// A modification of an object which is not sequenced before the value
5295 /// computation of the expression, such as n++.
5296 UK_ModAsSideEffect,
5297
5298 UK_Count = UK_ModAsSideEffect + 1
5299 };
5300
5301 struct Usage {
5302 Usage() : Use(0), Seq() {}
5303 Expr *Use;
5304 SequenceTree::Seq Seq;
5305 };
5306
5307 struct UsageInfo {
5308 UsageInfo() : Diagnosed(false) {}
5309 Usage Uses[UK_Count];
5310 /// Have we issued a diagnostic for this variable already?
5311 bool Diagnosed;
5312 };
5313 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5314
5315 Sema &SemaRef;
5316 /// Sequenced regions within the expression.
5317 SequenceTree Tree;
5318 /// Declaration modifications and references which we have seen.
5319 UsageInfoMap UsageMap;
5320 /// The region we are currently within.
5321 SequenceTree::Seq Region;
5322 /// Filled in with declarations which were modified as a side-effect
5323 /// (that is, post-increment operations).
5324 llvm::SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smith1a2dcd52013-01-17 23:18:09 +00005325 /// Expressions to check later. We defer checking these to reduce
5326 /// stack usage.
5327 llvm::SmallVectorImpl<Expr*> &WorkList;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005328
5329 /// RAII object wrapping the visitation of a sequenced subexpression of an
5330 /// expression. At the end of this process, the side-effects of the evaluation
5331 /// become sequenced with respect to the value computation of the result, so
5332 /// we downgrade any UK_ModAsSideEffect within the evaluation to
5333 /// UK_ModAsValue.
5334 struct SequencedSubexpression {
5335 SequencedSubexpression(SequenceChecker &Self)
5336 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5337 Self.ModAsSideEffect = &ModAsSideEffect;
5338 }
5339 ~SequencedSubexpression() {
5340 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5341 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5342 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5343 Self.addUsage(U, ModAsSideEffect[I].first,
5344 ModAsSideEffect[I].second.Use, UK_ModAsValue);
5345 }
5346 Self.ModAsSideEffect = OldModAsSideEffect;
5347 }
5348
5349 SequenceChecker &Self;
5350 llvm::SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5351 llvm::SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
5352 };
5353
5354 /// \brief Find the object which is produced by the specified expression,
5355 /// if any.
5356 Object getObject(Expr *E, bool Mod) const {
5357 E = E->IgnoreParenCasts();
5358 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5359 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5360 return getObject(UO->getSubExpr(), Mod);
5361 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5362 if (BO->getOpcode() == BO_Comma)
5363 return getObject(BO->getRHS(), Mod);
5364 if (Mod && BO->isAssignmentOp())
5365 return getObject(BO->getLHS(), Mod);
5366 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5367 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5368 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5369 return ME->getMemberDecl();
5370 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5371 // FIXME: If this is a reference, map through to its value.
5372 return DRE->getDecl();
5373 return 0;
5374 }
5375
5376 /// \brief Note that an object was modified or used by an expression.
5377 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5378 Usage &U = UI.Uses[UK];
5379 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5380 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5381 ModAsSideEffect->push_back(std::make_pair(O, U));
5382 U.Use = Ref;
5383 U.Seq = Region;
5384 }
5385 }
5386 /// \brief Check whether a modification or use conflicts with a prior usage.
5387 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5388 bool IsModMod) {
5389 if (UI.Diagnosed)
5390 return;
5391
5392 const Usage &U = UI.Uses[OtherKind];
5393 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5394 return;
5395
5396 Expr *Mod = U.Use;
5397 Expr *ModOrUse = Ref;
5398 if (OtherKind == UK_Use)
5399 std::swap(Mod, ModOrUse);
5400
5401 SemaRef.Diag(Mod->getExprLoc(),
5402 IsModMod ? diag::warn_unsequenced_mod_mod
5403 : diag::warn_unsequenced_mod_use)
5404 << O << SourceRange(ModOrUse->getExprLoc());
5405 UI.Diagnosed = true;
5406 }
5407
5408 void notePreUse(Object O, Expr *Use) {
5409 UsageInfo &U = UsageMap[O];
5410 // Uses conflict with other modifications.
5411 checkUsage(O, U, Use, UK_ModAsValue, false);
5412 }
5413 void notePostUse(Object O, Expr *Use) {
5414 UsageInfo &U = UsageMap[O];
5415 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5416 addUsage(U, O, Use, UK_Use);
5417 }
5418
5419 void notePreMod(Object O, Expr *Mod) {
5420 UsageInfo &U = UsageMap[O];
5421 // Modifications conflict with other modifications and with uses.
5422 checkUsage(O, U, Mod, UK_ModAsValue, true);
5423 checkUsage(O, U, Mod, UK_Use, false);
5424 }
5425 void notePostMod(Object O, Expr *Use, UsageKind UK) {
5426 UsageInfo &U = UsageMap[O];
5427 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5428 addUsage(U, O, Use, UK);
5429 }
5430
5431public:
Richard Smith1a2dcd52013-01-17 23:18:09 +00005432 SequenceChecker(Sema &S, Expr *E,
5433 llvm::SmallVectorImpl<Expr*> &WorkList)
Richard Smithe5096c82013-01-17 01:40:50 +00005434 : EvaluatedExprVisitor<SequenceChecker>(S.Context), SemaRef(S),
Richard Smith1a2dcd52013-01-17 23:18:09 +00005435 Region(Tree.root()), ModAsSideEffect(0), WorkList(WorkList) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005436 Visit(E);
5437 }
5438
5439 void VisitStmt(Stmt *S) {
5440 // Skip all statements which aren't expressions for now.
5441 }
5442
5443 void VisitExpr(Expr *E) {
5444 // By default, just recurse to evaluated subexpressions.
Richard Smithe5096c82013-01-17 01:40:50 +00005445 EvaluatedExprVisitor<SequenceChecker>::VisitStmt(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005446 }
5447
5448 void VisitCastExpr(CastExpr *E) {
5449 Object O = Object();
5450 if (E->getCastKind() == CK_LValueToRValue)
5451 O = getObject(E->getSubExpr(), false);
5452
5453 if (O)
5454 notePreUse(O, E);
5455 VisitExpr(E);
5456 if (O)
5457 notePostUse(O, E);
5458 }
5459
5460 void VisitBinComma(BinaryOperator *BO) {
5461 // C++11 [expr.comma]p1:
5462 // Every value computation and side effect associated with the left
5463 // expression is sequenced before every value computation and side
5464 // effect associated with the right expression.
5465 SequenceTree::Seq LHS = Tree.allocate(Region);
5466 SequenceTree::Seq RHS = Tree.allocate(Region);
5467 SequenceTree::Seq OldRegion = Region;
5468
5469 {
5470 SequencedSubexpression SeqLHS(*this);
5471 Region = LHS;
5472 Visit(BO->getLHS());
5473 }
5474
5475 Region = RHS;
5476 Visit(BO->getRHS());
5477
5478 Region = OldRegion;
5479
5480 // Forget that LHS and RHS are sequenced. They are both unsequenced
5481 // with respect to other stuff.
5482 Tree.merge(LHS);
5483 Tree.merge(RHS);
5484 }
5485
5486 void VisitBinAssign(BinaryOperator *BO) {
5487 // The modification is sequenced after the value computation of the LHS
5488 // and RHS, so check it before inspecting the operands and update the
5489 // map afterwards.
5490 Object O = getObject(BO->getLHS(), true);
5491 if (!O)
5492 return VisitExpr(BO);
5493
5494 notePreMod(O, BO);
5495
5496 // C++11 [expr.ass]p7:
5497 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
5498 // only once.
5499 //
5500 // Therefore, for a compound assignment operator, O is considered used
5501 // everywhere except within the evaluation of E1 itself.
5502 if (isa<CompoundAssignOperator>(BO))
5503 notePreUse(O, BO);
5504
5505 Visit(BO->getLHS());
5506
5507 if (isa<CompoundAssignOperator>(BO))
5508 notePostUse(O, BO);
5509
5510 Visit(BO->getRHS());
5511
5512 notePostMod(O, BO, UK_ModAsValue);
5513 }
5514 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
5515 VisitBinAssign(CAO);
5516 }
5517
5518 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5519 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5520 void VisitUnaryPreIncDec(UnaryOperator *UO) {
5521 Object O = getObject(UO->getSubExpr(), true);
5522 if (!O)
5523 return VisitExpr(UO);
5524
5525 notePreMod(O, UO);
5526 Visit(UO->getSubExpr());
5527 notePostMod(O, UO, UK_ModAsValue);
5528 }
5529
5530 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5531 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5532 void VisitUnaryPostIncDec(UnaryOperator *UO) {
5533 Object O = getObject(UO->getSubExpr(), true);
5534 if (!O)
5535 return VisitExpr(UO);
5536
5537 notePreMod(O, UO);
5538 Visit(UO->getSubExpr());
5539 notePostMod(O, UO, UK_ModAsSideEffect);
5540 }
5541
5542 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
5543 void VisitBinLOr(BinaryOperator *BO) {
5544 // The side-effects of the LHS of an '&&' are sequenced before the
5545 // value computation of the RHS, and hence before the value computation
5546 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
5547 // as if they were unconditionally sequenced.
5548 {
5549 SequencedSubexpression Sequenced(*this);
5550 Visit(BO->getLHS());
5551 }
5552
5553 bool Result;
5554 if (!BO->getLHS()->isValueDependent() &&
Richard Smith995e4a72013-01-17 22:06:26 +00005555 BO->getLHS()->EvaluateAsBooleanCondition(Result, SemaRef.Context)) {
5556 if (!Result)
5557 Visit(BO->getRHS());
5558 } else {
5559 // Check for unsequenced operations in the RHS, treating it as an
5560 // entirely separate evaluation.
5561 //
5562 // FIXME: If there are operations in the RHS which are unsequenced
5563 // with respect to operations outside the RHS, and those operations
5564 // are unconditionally evaluated, diagnose them.
Richard Smith1a2dcd52013-01-17 23:18:09 +00005565 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00005566 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005567 }
5568 void VisitBinLAnd(BinaryOperator *BO) {
5569 {
5570 SequencedSubexpression Sequenced(*this);
5571 Visit(BO->getLHS());
5572 }
5573
5574 bool Result;
5575 if (!BO->getLHS()->isValueDependent() &&
Richard Smith995e4a72013-01-17 22:06:26 +00005576 BO->getLHS()->EvaluateAsBooleanCondition(Result, SemaRef.Context)) {
5577 if (Result)
5578 Visit(BO->getRHS());
5579 } else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005580 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00005581 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005582 }
5583
5584 // Only visit the condition, unless we can be sure which subexpression will
5585 // be chosen.
5586 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
5587 SequencedSubexpression Sequenced(*this);
5588 Visit(CO->getCond());
5589
5590 bool Result;
5591 if (!CO->getCond()->isValueDependent() &&
5592 CO->getCond()->EvaluateAsBooleanCondition(Result, SemaRef.Context))
5593 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00005594 else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005595 WorkList.push_back(CO->getTrueExpr());
5596 WorkList.push_back(CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00005597 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005598 }
5599
5600 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
5601 if (!CCE->isListInitialization())
5602 return VisitExpr(CCE);
5603
5604 // In C++11, list initializations are sequenced.
5605 llvm::SmallVector<SequenceTree::Seq, 32> Elts;
5606 SequenceTree::Seq Parent = Region;
5607 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
5608 E = CCE->arg_end();
5609 I != E; ++I) {
5610 Region = Tree.allocate(Parent);
5611 Elts.push_back(Region);
5612 Visit(*I);
5613 }
5614
5615 // Forget that the initializers are sequenced.
5616 Region = Parent;
5617 for (unsigned I = 0; I < Elts.size(); ++I)
5618 Tree.merge(Elts[I]);
5619 }
5620
5621 void VisitInitListExpr(InitListExpr *ILE) {
5622 if (!SemaRef.getLangOpts().CPlusPlus11)
5623 return VisitExpr(ILE);
5624
5625 // In C++11, list initializations are sequenced.
5626 llvm::SmallVector<SequenceTree::Seq, 32> Elts;
5627 SequenceTree::Seq Parent = Region;
5628 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
5629 Expr *E = ILE->getInit(I);
5630 if (!E) continue;
5631 Region = Tree.allocate(Parent);
5632 Elts.push_back(Region);
5633 Visit(E);
5634 }
5635
5636 // Forget that the initializers are sequenced.
5637 Region = Parent;
5638 for (unsigned I = 0; I < Elts.size(); ++I)
5639 Tree.merge(Elts[I]);
5640 }
5641};
5642}
5643
5644void Sema::CheckUnsequencedOperations(Expr *E) {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005645 llvm::SmallVector<Expr*, 8> WorkList;
5646 WorkList.push_back(E);
5647 while (!WorkList.empty()) {
5648 Expr *Item = WorkList.back();
5649 WorkList.pop_back();
5650 SequenceChecker(*this, Item, WorkList);
5651 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005652}
5653
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005654void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
5655 bool IsConstexpr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005656 CheckImplicitConversions(E, CheckLoc);
5657 CheckUnsequencedOperations(E);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005658 if (!IsConstexpr && !E->isValueDependent())
5659 CheckForIntOverflow(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005660}
5661
John McCall15d7d122010-11-11 03:21:53 +00005662void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
5663 FieldDecl *BitField,
5664 Expr *Init) {
5665 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
5666}
5667
Mike Stumpf8c49212010-01-21 03:59:47 +00005668/// CheckParmsForFunctionDef - Check that the parameters of the given
5669/// function are appropriate for the definition of a function. This
5670/// takes care of any checks that cannot be performed on the
5671/// declaration itself, e.g., that the types of each of the function
5672/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00005673bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
5674 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005675 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00005676 for (; P != PEnd; ++P) {
5677 ParmVarDecl *Param = *P;
5678
Mike Stumpf8c49212010-01-21 03:59:47 +00005679 // C99 6.7.5.3p4: the parameters in a parameter type list in a
5680 // function declarator that is part of a function definition of
5681 // that function shall not have incomplete type.
5682 //
5683 // This is also C++ [dcl.fct]p6.
5684 if (!Param->isInvalidDecl() &&
5685 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00005686 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005687 Param->setInvalidDecl();
5688 HasInvalidParm = true;
5689 }
5690
5691 // C99 6.9.1p5: If the declarator includes a parameter type list, the
5692 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00005693 if (CheckParameterNames &&
5694 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00005695 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005696 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00005697 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00005698
5699 // C99 6.7.5.3p12:
5700 // If the function declarator is not part of a definition of that
5701 // function, parameters may have incomplete type and may use the [*]
5702 // notation in their sequences of declarator specifiers to specify
5703 // variable length array types.
5704 QualType PType = Param->getOriginalType();
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00005705 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigd17e3402010-02-01 05:02:49 +00005706 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitfc093362013-03-01 21:41:22 +00005707 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00005708 // information is added for it.
5709 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00005710 break;
Sam Weinigd17e3402010-02-01 05:02:49 +00005711 }
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00005712 PType= AT->getElementType();
Sam Weinigd17e3402010-02-01 05:02:49 +00005713 }
Mike Stumpf8c49212010-01-21 03:59:47 +00005714 }
5715
5716 return HasInvalidParm;
5717}
John McCallb7f4ffe2010-08-12 21:44:57 +00005718
5719/// CheckCastAlign - Implements -Wcast-align, which warns when a
5720/// pointer cast increases the alignment requirements.
5721void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
5722 // This is actually a lot of work to potentially be doing on every
5723 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005724 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
5725 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00005726 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00005727 return;
5728
5729 // Ignore dependent types.
5730 if (T->isDependentType() || Op->getType()->isDependentType())
5731 return;
5732
5733 // Require that the destination be a pointer type.
5734 const PointerType *DestPtr = T->getAs<PointerType>();
5735 if (!DestPtr) return;
5736
5737 // If the destination has alignment 1, we're done.
5738 QualType DestPointee = DestPtr->getPointeeType();
5739 if (DestPointee->isIncompleteType()) return;
5740 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
5741 if (DestAlign.isOne()) return;
5742
5743 // Require that the source be a pointer type.
5744 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
5745 if (!SrcPtr) return;
5746 QualType SrcPointee = SrcPtr->getPointeeType();
5747
5748 // Whitelist casts from cv void*. We already implicitly
5749 // whitelisted casts to cv void*, since they have alignment 1.
5750 // Also whitelist casts involving incomplete types, which implicitly
5751 // includes 'void'.
5752 if (SrcPointee->isIncompleteType()) return;
5753
5754 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
5755 if (SrcAlign >= DestAlign) return;
5756
5757 Diag(TRange.getBegin(), diag::warn_cast_align)
5758 << Op->getType() << T
5759 << static_cast<unsigned>(SrcAlign.getQuantity())
5760 << static_cast<unsigned>(DestAlign.getQuantity())
5761 << TRange << Op->getSourceRange();
5762}
5763
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005764static const Type* getElementType(const Expr *BaseExpr) {
5765 const Type* EltType = BaseExpr->getType().getTypePtr();
5766 if (EltType->isAnyPointerType())
5767 return EltType->getPointeeType().getTypePtr();
5768 else if (EltType->isArrayType())
5769 return EltType->getBaseElementTypeUnsafe();
5770 return EltType;
5771}
5772
Chandler Carruthc2684342011-08-05 09:10:50 +00005773/// \brief Check whether this array fits the idiom of a size-one tail padded
5774/// array member of a struct.
5775///
5776/// We avoid emitting out-of-bounds access warnings for such arrays as they are
5777/// commonly used to emulate flexible arrays in C89 code.
5778static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
5779 const NamedDecl *ND) {
5780 if (Size != 1 || !ND) return false;
5781
5782 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
5783 if (!FD) return false;
5784
5785 // Don't consider sizes resulting from macro expansions or template argument
5786 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00005787
5788 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005789 while (TInfo) {
5790 TypeLoc TL = TInfo->getTypeLoc();
5791 // Look through typedefs.
David Blaikie39e6ab42013-02-18 22:06:02 +00005792 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
5793 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005794 TInfo = TDL->getTypeSourceInfo();
5795 continue;
5796 }
David Blaikie39e6ab42013-02-18 22:06:02 +00005797 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
5798 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier5e253012013-02-06 00:58:34 +00005799 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
5800 return false;
5801 }
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005802 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00005803 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005804
5805 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00005806 if (!RD) return false;
5807 if (RD->isUnion()) return false;
5808 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
5809 if (!CRD->isStandardLayout()) return false;
5810 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005811
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00005812 // See if this is the last field decl in the record.
5813 const Decl *D = FD;
5814 while ((D = D->getNextDeclInContext()))
5815 if (isa<FieldDecl>(D))
5816 return false;
5817 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00005818}
5819
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005820void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005821 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00005822 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00005823 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005824 if (IndexExpr->isValueDependent())
5825 return;
5826
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00005827 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005828 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00005829 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005830 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00005831 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00005832 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00005833
Chandler Carruth34064582011-02-17 20:55:08 +00005834 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005835 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00005836 return;
Richard Smith25b009a2011-12-16 19:31:14 +00005837 if (IndexNegated)
5838 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00005839
Chandler Carruthba447122011-08-05 08:07:29 +00005840 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00005841 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5842 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00005843 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00005844 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00005845
Ted Kremenek9e060ca2011-02-23 23:06:04 +00005846 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00005847 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00005848 if (!size.isStrictlyPositive())
5849 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005850
5851 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00005852 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005853 // Make sure we're comparing apples to apples when comparing index to size
5854 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
5855 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00005856 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00005857 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005858 if (ptrarith_typesize != array_typesize) {
5859 // There's a cast to a different size type involved
5860 uint64_t ratio = array_typesize / ptrarith_typesize;
5861 // TODO: Be smarter about handling cases where array_typesize is not a
5862 // multiple of ptrarith_typesize
5863 if (ptrarith_typesize * ratio == array_typesize)
5864 size *= llvm::APInt(size.getBitWidth(), ratio);
5865 }
5866 }
5867
Chandler Carruth34064582011-02-17 20:55:08 +00005868 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005869 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005870 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005871 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005872
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005873 // For array subscripting the index must be less than size, but for pointer
5874 // arithmetic also allow the index (offset) to be equal to size since
5875 // computing the next address after the end of the array is legal and
5876 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00005877 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00005878 return;
5879
5880 // Also don't warn for arrays of size 1 which are members of some
5881 // structure. These are often used to approximate flexible arrays in C89
5882 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005883 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00005884 return;
Chandler Carruth34064582011-02-17 20:55:08 +00005885
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005886 // Suppress the warning if the subscript expression (as identified by the
5887 // ']' location) and the index expression are both from macro expansions
5888 // within a system header.
5889 if (ASE) {
5890 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
5891 ASE->getRBracketLoc());
5892 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
5893 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
5894 IndexExpr->getLocStart());
5895 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
5896 return;
5897 }
5898 }
5899
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005900 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005901 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005902 DiagID = diag::warn_array_index_exceeds_bounds;
5903
5904 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
5905 PDiag(DiagID) << index.toString(10, true)
5906 << size.toString(10, true)
5907 << (unsigned)size.getLimitedValue(~0U)
5908 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00005909 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005910 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005911 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005912 DiagID = diag::warn_ptr_arith_precedes_bounds;
5913 if (index.isNegative()) index = -index;
5914 }
5915
5916 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
5917 PDiag(DiagID) << index.toString(10, true)
5918 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00005919 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00005920
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00005921 if (!ND) {
5922 // Try harder to find a NamedDecl to point at in the note.
5923 while (const ArraySubscriptExpr *ASE =
5924 dyn_cast<ArraySubscriptExpr>(BaseExpr))
5925 BaseExpr = ASE->getBase()->IgnoreParenCasts();
5926 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5927 ND = dyn_cast<NamedDecl>(DRE->getDecl());
5928 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
5929 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
5930 }
5931
Chandler Carruth35001ca2011-02-17 21:10:52 +00005932 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005933 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
5934 PDiag(diag::note_array_index_out_of_bounds)
5935 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00005936}
5937
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005938void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005939 int AllowOnePastEnd = 0;
5940 while (expr) {
5941 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005942 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005943 case Stmt::ArraySubscriptExprClass: {
5944 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005945 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005946 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005947 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005948 }
5949 case Stmt::UnaryOperatorClass: {
5950 // Only unwrap the * and & unary operators
5951 const UnaryOperator *UO = cast<UnaryOperator>(expr);
5952 expr = UO->getSubExpr();
5953 switch (UO->getOpcode()) {
5954 case UO_AddrOf:
5955 AllowOnePastEnd++;
5956 break;
5957 case UO_Deref:
5958 AllowOnePastEnd--;
5959 break;
5960 default:
5961 return;
5962 }
5963 break;
5964 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005965 case Stmt::ConditionalOperatorClass: {
5966 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
5967 if (const Expr *lhs = cond->getLHS())
5968 CheckArrayAccess(lhs);
5969 if (const Expr *rhs = cond->getRHS())
5970 CheckArrayAccess(rhs);
5971 return;
5972 }
5973 default:
5974 return;
5975 }
Peter Collingbournef111d932011-04-15 00:35:48 +00005976 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005977}
John McCallf85e1932011-06-15 23:02:42 +00005978
5979//===--- CHECK: Objective-C retain cycles ----------------------------------//
5980
5981namespace {
5982 struct RetainCycleOwner {
5983 RetainCycleOwner() : Variable(0), Indirect(false) {}
5984 VarDecl *Variable;
5985 SourceRange Range;
5986 SourceLocation Loc;
5987 bool Indirect;
5988
5989 void setLocsFrom(Expr *e) {
5990 Loc = e->getExprLoc();
5991 Range = e->getSourceRange();
5992 }
5993 };
5994}
5995
5996/// Consider whether capturing the given variable can possibly lead to
5997/// a retain cycle.
5998static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00005999 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00006000 // lifetime. In MRR, it's captured strongly if the variable is
6001 // __block and has an appropriate type.
6002 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6003 return false;
6004
6005 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00006006 if (ref)
6007 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00006008 return true;
6009}
6010
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006011static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00006012 while (true) {
6013 e = e->IgnoreParens();
6014 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6015 switch (cast->getCastKind()) {
6016 case CK_BitCast:
6017 case CK_LValueBitCast:
6018 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00006019 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00006020 e = cast->getSubExpr();
6021 continue;
6022
John McCallf85e1932011-06-15 23:02:42 +00006023 default:
6024 return false;
6025 }
6026 }
6027
6028 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6029 ObjCIvarDecl *ivar = ref->getDecl();
6030 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6031 return false;
6032
6033 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006034 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006035 return false;
6036
6037 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6038 owner.Indirect = true;
6039 return true;
6040 }
6041
6042 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6043 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6044 if (!var) return false;
6045 return considerVariable(var, ref, owner);
6046 }
6047
John McCallf85e1932011-06-15 23:02:42 +00006048 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6049 if (member->isArrow()) return false;
6050
6051 // Don't count this as an indirect ownership.
6052 e = member->getBase();
6053 continue;
6054 }
6055
John McCall4b9c2d22011-11-06 09:01:30 +00006056 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6057 // Only pay attention to pseudo-objects on property references.
6058 ObjCPropertyRefExpr *pre
6059 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6060 ->IgnoreParens());
6061 if (!pre) return false;
6062 if (pre->isImplicitProperty()) return false;
6063 ObjCPropertyDecl *property = pre->getExplicitProperty();
6064 if (!property->isRetaining() &&
6065 !(property->getPropertyIvarDecl() &&
6066 property->getPropertyIvarDecl()->getType()
6067 .getObjCLifetime() == Qualifiers::OCL_Strong))
6068 return false;
6069
6070 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006071 if (pre->isSuperReceiver()) {
6072 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6073 if (!owner.Variable)
6074 return false;
6075 owner.Loc = pre->getLocation();
6076 owner.Range = pre->getSourceRange();
6077 return true;
6078 }
John McCall4b9c2d22011-11-06 09:01:30 +00006079 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6080 ->getSourceExpr());
6081 continue;
6082 }
6083
John McCallf85e1932011-06-15 23:02:42 +00006084 // Array ivars?
6085
6086 return false;
6087 }
6088}
6089
6090namespace {
6091 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6092 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6093 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6094 Variable(variable), Capturer(0) {}
6095
6096 VarDecl *Variable;
6097 Expr *Capturer;
6098
6099 void VisitDeclRefExpr(DeclRefExpr *ref) {
6100 if (ref->getDecl() == Variable && !Capturer)
6101 Capturer = ref;
6102 }
6103
John McCallf85e1932011-06-15 23:02:42 +00006104 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6105 if (Capturer) return;
6106 Visit(ref->getBase());
6107 if (Capturer && ref->isFreeIvar())
6108 Capturer = ref;
6109 }
6110
6111 void VisitBlockExpr(BlockExpr *block) {
6112 // Look inside nested blocks
6113 if (block->getBlockDecl()->capturesVariable(Variable))
6114 Visit(block->getBlockDecl()->getBody());
6115 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00006116
6117 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6118 if (Capturer) return;
6119 if (OVE->getSourceExpr())
6120 Visit(OVE->getSourceExpr());
6121 }
John McCallf85e1932011-06-15 23:02:42 +00006122 };
6123}
6124
6125/// Check whether the given argument is a block which captures a
6126/// variable.
6127static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6128 assert(owner.Variable && owner.Loc.isValid());
6129
6130 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00006131
6132 // Look through [^{...} copy] and Block_copy(^{...}).
6133 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6134 Selector Cmd = ME->getSelector();
6135 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6136 e = ME->getInstanceReceiver();
6137 if (!e)
6138 return 0;
6139 e = e->IgnoreParenCasts();
6140 }
6141 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6142 if (CE->getNumArgs() == 1) {
6143 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00006144 if (Fn) {
6145 const IdentifierInfo *FnI = Fn->getIdentifier();
6146 if (FnI && FnI->isStr("_Block_copy")) {
6147 e = CE->getArg(0)->IgnoreParenCasts();
6148 }
6149 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00006150 }
6151 }
6152
John McCallf85e1932011-06-15 23:02:42 +00006153 BlockExpr *block = dyn_cast<BlockExpr>(e);
6154 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6155 return 0;
6156
6157 FindCaptureVisitor visitor(S.Context, owner.Variable);
6158 visitor.Visit(block->getBlockDecl()->getBody());
6159 return visitor.Capturer;
6160}
6161
6162static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6163 RetainCycleOwner &owner) {
6164 assert(capturer);
6165 assert(owner.Variable && owner.Loc.isValid());
6166
6167 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6168 << owner.Variable << capturer->getSourceRange();
6169 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6170 << owner.Indirect << owner.Range;
6171}
6172
6173/// Check for a keyword selector that starts with the word 'add' or
6174/// 'set'.
6175static bool isSetterLikeSelector(Selector sel) {
6176 if (sel.isUnarySelector()) return false;
6177
Chris Lattner5f9e2722011-07-23 10:55:15 +00006178 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00006179 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006180 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00006181 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006182 else if (str.startswith("add")) {
6183 // Specially whitelist 'addOperationWithBlock:'.
6184 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6185 return false;
6186 str = str.substr(3);
6187 }
John McCallf85e1932011-06-15 23:02:42 +00006188 else
6189 return false;
6190
6191 if (str.empty()) return true;
Jordan Rose3f6f51e2013-02-08 22:30:41 +00006192 return !isLowercase(str.front());
John McCallf85e1932011-06-15 23:02:42 +00006193}
6194
6195/// Check a message send to see if it's likely to cause a retain cycle.
6196void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6197 // Only check instance methods whose selector looks like a setter.
6198 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6199 return;
6200
6201 // Try to find a variable that the receiver is strongly owned by.
6202 RetainCycleOwner owner;
6203 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006204 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006205 return;
6206 } else {
6207 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6208 owner.Variable = getCurMethodDecl()->getSelfDecl();
6209 owner.Loc = msg->getSuperLoc();
6210 owner.Range = msg->getSuperLoc();
6211 }
6212
6213 // Check whether the receiver is captured by any of the arguments.
6214 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6215 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6216 return diagnoseRetainCycle(*this, capturer, owner);
6217}
6218
6219/// Check a property assign to see if it's likely to cause a retain cycle.
6220void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6221 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006222 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00006223 return;
6224
6225 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6226 diagnoseRetainCycle(*this, capturer, owner);
6227}
6228
Jordan Rosee10f4d32012-09-15 02:48:31 +00006229void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6230 RetainCycleOwner Owner;
6231 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6232 return;
6233
6234 // Because we don't have an expression for the variable, we have to set the
6235 // location explicitly here.
6236 Owner.Loc = Var->getLocation();
6237 Owner.Range = Var->getSourceRange();
6238
6239 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6240 diagnoseRetainCycle(*this, Capturer, Owner);
6241}
6242
Ted Kremenek9d084012012-12-21 08:04:28 +00006243static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6244 Expr *RHS, bool isProperty) {
6245 // Check if RHS is an Objective-C object literal, which also can get
6246 // immediately zapped in a weak reference. Note that we explicitly
6247 // allow ObjCStringLiterals, since those are designed to never really die.
6248 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006249
Ted Kremenekd3292c82012-12-21 22:46:35 +00006250 // This enum needs to match with the 'select' in
6251 // warn_objc_arc_literal_assign (off-by-1).
6252 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6253 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6254 return false;
Ted Kremenekf530ff72012-12-21 21:59:39 +00006255
6256 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenekd3292c82012-12-21 22:46:35 +00006257 << (unsigned) Kind
Ted Kremenek9d084012012-12-21 08:04:28 +00006258 << (isProperty ? 0 : 1)
6259 << RHS->getSourceRange();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006260
6261 return true;
Ted Kremenek9d084012012-12-21 08:04:28 +00006262}
6263
Ted Kremenekb29b30f2012-12-21 19:45:30 +00006264static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6265 Qualifiers::ObjCLifetime LT,
6266 Expr *RHS, bool isProperty) {
6267 // Strip off any implicit cast added to get to the one ARC-specific.
6268 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6269 if (cast->getCastKind() == CK_ARCConsumeObject) {
6270 S.Diag(Loc, diag::warn_arc_retained_assign)
6271 << (LT == Qualifiers::OCL_ExplicitNone)
6272 << (isProperty ? 0 : 1)
6273 << RHS->getSourceRange();
6274 return true;
6275 }
6276 RHS = cast->getSubExpr();
6277 }
6278
6279 if (LT == Qualifiers::OCL_Weak &&
6280 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6281 return true;
6282
6283 return false;
6284}
6285
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006286bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6287 QualType LHS, Expr *RHS) {
6288 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6289
6290 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6291 return false;
6292
6293 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6294 return true;
6295
6296 return false;
6297}
6298
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006299void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6300 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006301 QualType LHSType;
6302 // PropertyRef on LHS type need be directly obtained from
6303 // its declaration as it has a PsuedoType.
6304 ObjCPropertyRefExpr *PRE
6305 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6306 if (PRE && !PRE->isImplicitProperty()) {
6307 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6308 if (PD)
6309 LHSType = PD->getType();
6310 }
6311
6312 if (LHSType.isNull())
6313 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00006314
6315 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6316
6317 if (LT == Qualifiers::OCL_Weak) {
6318 DiagnosticsEngine::Level Level =
6319 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6320 if (Level != DiagnosticsEngine::Ignored)
6321 getCurFunction()->markSafeWeakUse(LHS);
6322 }
6323
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006324 if (checkUnsafeAssigns(Loc, LHSType, RHS))
6325 return;
Jordan Rose7a270482012-09-28 22:21:35 +00006326
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006327 // FIXME. Check for other life times.
6328 if (LT != Qualifiers::OCL_None)
6329 return;
6330
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006331 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006332 if (PRE->isImplicitProperty())
6333 return;
6334 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6335 if (!PD)
6336 return;
6337
Bill Wendlingad017fa2012-12-20 19:22:21 +00006338 unsigned Attributes = PD->getPropertyAttributes();
6339 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006340 // when 'assign' attribute was not explicitly specified
6341 // by user, ignore it and rely on property type itself
6342 // for lifetime info.
6343 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6344 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6345 LHSType->isObjCRetainableType())
6346 return;
6347
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006348 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00006349 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006350 Diag(Loc, diag::warn_arc_retained_property_assign)
6351 << RHS->getSourceRange();
6352 return;
6353 }
6354 RHS = cast->getSubExpr();
6355 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006356 }
Bill Wendlingad017fa2012-12-20 19:22:21 +00006357 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006358 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6359 return;
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00006360 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006361 }
6362}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00006363
6364//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6365
6366namespace {
6367bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6368 SourceLocation StmtLoc,
6369 const NullStmt *Body) {
6370 // Do not warn if the body is a macro that expands to nothing, e.g:
6371 //
6372 // #define CALL(x)
6373 // if (condition)
6374 // CALL(0);
6375 //
6376 if (Body->hasLeadingEmptyMacro())
6377 return false;
6378
6379 // Get line numbers of statement and body.
6380 bool StmtLineInvalid;
6381 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6382 &StmtLineInvalid);
6383 if (StmtLineInvalid)
6384 return false;
6385
6386 bool BodyLineInvalid;
6387 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
6388 &BodyLineInvalid);
6389 if (BodyLineInvalid)
6390 return false;
6391
6392 // Warn if null statement and body are on the same line.
6393 if (StmtLine != BodyLine)
6394 return false;
6395
6396 return true;
6397}
6398} // Unnamed namespace
6399
6400void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
6401 const Stmt *Body,
6402 unsigned DiagID) {
6403 // Since this is a syntactic check, don't emit diagnostic for template
6404 // instantiations, this just adds noise.
6405 if (CurrentInstantiationScope)
6406 return;
6407
6408 // The body should be a null statement.
6409 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6410 if (!NBody)
6411 return;
6412
6413 // Do the usual checks.
6414 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6415 return;
6416
6417 Diag(NBody->getSemiLoc(), DiagID);
6418 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6419}
6420
6421void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
6422 const Stmt *PossibleBody) {
6423 assert(!CurrentInstantiationScope); // Ensured by caller
6424
6425 SourceLocation StmtLoc;
6426 const Stmt *Body;
6427 unsigned DiagID;
6428 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
6429 StmtLoc = FS->getRParenLoc();
6430 Body = FS->getBody();
6431 DiagID = diag::warn_empty_for_body;
6432 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
6433 StmtLoc = WS->getCond()->getSourceRange().getEnd();
6434 Body = WS->getBody();
6435 DiagID = diag::warn_empty_while_body;
6436 } else
6437 return; // Neither `for' nor `while'.
6438
6439 // The body should be a null statement.
6440 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6441 if (!NBody)
6442 return;
6443
6444 // Skip expensive checks if diagnostic is disabled.
6445 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
6446 DiagnosticsEngine::Ignored)
6447 return;
6448
6449 // Do the usual checks.
6450 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6451 return;
6452
6453 // `for(...);' and `while(...);' are popular idioms, so in order to keep
6454 // noise level low, emit diagnostics only if for/while is followed by a
6455 // CompoundStmt, e.g.:
6456 // for (int i = 0; i < n; i++);
6457 // {
6458 // a(i);
6459 // }
6460 // or if for/while is followed by a statement with more indentation
6461 // than for/while itself:
6462 // for (int i = 0; i < n; i++);
6463 // a(i);
6464 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
6465 if (!ProbableTypo) {
6466 bool BodyColInvalid;
6467 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
6468 PossibleBody->getLocStart(),
6469 &BodyColInvalid);
6470 if (BodyColInvalid)
6471 return;
6472
6473 bool StmtColInvalid;
6474 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
6475 S->getLocStart(),
6476 &StmtColInvalid);
6477 if (StmtColInvalid)
6478 return;
6479
6480 if (BodyCol > StmtCol)
6481 ProbableTypo = true;
6482 }
6483
6484 if (ProbableTypo) {
6485 Diag(NBody->getSemiLoc(), DiagID);
6486 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6487 }
6488}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006489
6490//===--- Layout compatibility ----------------------------------------------//
6491
6492namespace {
6493
6494bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
6495
6496/// \brief Check if two enumeration types are layout-compatible.
6497bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
6498 // C++11 [dcl.enum] p8:
6499 // Two enumeration types are layout-compatible if they have the same
6500 // underlying type.
6501 return ED1->isComplete() && ED2->isComplete() &&
6502 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
6503}
6504
6505/// \brief Check if two fields are layout-compatible.
6506bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
6507 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
6508 return false;
6509
6510 if (Field1->isBitField() != Field2->isBitField())
6511 return false;
6512
6513 if (Field1->isBitField()) {
6514 // Make sure that the bit-fields are the same length.
6515 unsigned Bits1 = Field1->getBitWidthValue(C);
6516 unsigned Bits2 = Field2->getBitWidthValue(C);
6517
6518 if (Bits1 != Bits2)
6519 return false;
6520 }
6521
6522 return true;
6523}
6524
6525/// \brief Check if two standard-layout structs are layout-compatible.
6526/// (C++11 [class.mem] p17)
6527bool isLayoutCompatibleStruct(ASTContext &C,
6528 RecordDecl *RD1,
6529 RecordDecl *RD2) {
6530 // If both records are C++ classes, check that base classes match.
6531 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
6532 // If one of records is a CXXRecordDecl we are in C++ mode,
6533 // thus the other one is a CXXRecordDecl, too.
6534 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
6535 // Check number of base classes.
6536 if (D1CXX->getNumBases() != D2CXX->getNumBases())
6537 return false;
6538
6539 // Check the base classes.
6540 for (CXXRecordDecl::base_class_const_iterator
6541 Base1 = D1CXX->bases_begin(),
6542 BaseEnd1 = D1CXX->bases_end(),
6543 Base2 = D2CXX->bases_begin();
6544 Base1 != BaseEnd1;
6545 ++Base1, ++Base2) {
6546 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
6547 return false;
6548 }
6549 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
6550 // If only RD2 is a C++ class, it should have zero base classes.
6551 if (D2CXX->getNumBases() > 0)
6552 return false;
6553 }
6554
6555 // Check the fields.
6556 RecordDecl::field_iterator Field2 = RD2->field_begin(),
6557 Field2End = RD2->field_end(),
6558 Field1 = RD1->field_begin(),
6559 Field1End = RD1->field_end();
6560 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
6561 if (!isLayoutCompatible(C, *Field1, *Field2))
6562 return false;
6563 }
6564 if (Field1 != Field1End || Field2 != Field2End)
6565 return false;
6566
6567 return true;
6568}
6569
6570/// \brief Check if two standard-layout unions are layout-compatible.
6571/// (C++11 [class.mem] p18)
6572bool isLayoutCompatibleUnion(ASTContext &C,
6573 RecordDecl *RD1,
6574 RecordDecl *RD2) {
6575 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
6576 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
6577 Field2End = RD2->field_end();
6578 Field2 != Field2End; ++Field2) {
6579 UnmatchedFields.insert(*Field2);
6580 }
6581
6582 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
6583 Field1End = RD1->field_end();
6584 Field1 != Field1End; ++Field1) {
6585 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
6586 I = UnmatchedFields.begin(),
6587 E = UnmatchedFields.end();
6588
6589 for ( ; I != E; ++I) {
6590 if (isLayoutCompatible(C, *Field1, *I)) {
6591 bool Result = UnmatchedFields.erase(*I);
6592 (void) Result;
6593 assert(Result);
6594 break;
6595 }
6596 }
6597 if (I == E)
6598 return false;
6599 }
6600
6601 return UnmatchedFields.empty();
6602}
6603
6604bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
6605 if (RD1->isUnion() != RD2->isUnion())
6606 return false;
6607
6608 if (RD1->isUnion())
6609 return isLayoutCompatibleUnion(C, RD1, RD2);
6610 else
6611 return isLayoutCompatibleStruct(C, RD1, RD2);
6612}
6613
6614/// \brief Check if two types are layout-compatible in C++11 sense.
6615bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
6616 if (T1.isNull() || T2.isNull())
6617 return false;
6618
6619 // C++11 [basic.types] p11:
6620 // If two types T1 and T2 are the same type, then T1 and T2 are
6621 // layout-compatible types.
6622 if (C.hasSameType(T1, T2))
6623 return true;
6624
6625 T1 = T1.getCanonicalType().getUnqualifiedType();
6626 T2 = T2.getCanonicalType().getUnqualifiedType();
6627
6628 const Type::TypeClass TC1 = T1->getTypeClass();
6629 const Type::TypeClass TC2 = T2->getTypeClass();
6630
6631 if (TC1 != TC2)
6632 return false;
6633
6634 if (TC1 == Type::Enum) {
6635 return isLayoutCompatible(C,
6636 cast<EnumType>(T1)->getDecl(),
6637 cast<EnumType>(T2)->getDecl());
6638 } else if (TC1 == Type::Record) {
6639 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
6640 return false;
6641
6642 return isLayoutCompatible(C,
6643 cast<RecordType>(T1)->getDecl(),
6644 cast<RecordType>(T2)->getDecl());
6645 }
6646
6647 return false;
6648}
6649}
6650
6651//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
6652
6653namespace {
6654/// \brief Given a type tag expression find the type tag itself.
6655///
6656/// \param TypeExpr Type tag expression, as it appears in user's code.
6657///
6658/// \param VD Declaration of an identifier that appears in a type tag.
6659///
6660/// \param MagicValue Type tag magic value.
6661bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
6662 const ValueDecl **VD, uint64_t *MagicValue) {
6663 while(true) {
6664 if (!TypeExpr)
6665 return false;
6666
6667 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
6668
6669 switch (TypeExpr->getStmtClass()) {
6670 case Stmt::UnaryOperatorClass: {
6671 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
6672 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
6673 TypeExpr = UO->getSubExpr();
6674 continue;
6675 }
6676 return false;
6677 }
6678
6679 case Stmt::DeclRefExprClass: {
6680 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
6681 *VD = DRE->getDecl();
6682 return true;
6683 }
6684
6685 case Stmt::IntegerLiteralClass: {
6686 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
6687 llvm::APInt MagicValueAPInt = IL->getValue();
6688 if (MagicValueAPInt.getActiveBits() <= 64) {
6689 *MagicValue = MagicValueAPInt.getZExtValue();
6690 return true;
6691 } else
6692 return false;
6693 }
6694
6695 case Stmt::BinaryConditionalOperatorClass:
6696 case Stmt::ConditionalOperatorClass: {
6697 const AbstractConditionalOperator *ACO =
6698 cast<AbstractConditionalOperator>(TypeExpr);
6699 bool Result;
6700 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
6701 if (Result)
6702 TypeExpr = ACO->getTrueExpr();
6703 else
6704 TypeExpr = ACO->getFalseExpr();
6705 continue;
6706 }
6707 return false;
6708 }
6709
6710 case Stmt::BinaryOperatorClass: {
6711 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
6712 if (BO->getOpcode() == BO_Comma) {
6713 TypeExpr = BO->getRHS();
6714 continue;
6715 }
6716 return false;
6717 }
6718
6719 default:
6720 return false;
6721 }
6722 }
6723}
6724
6725/// \brief Retrieve the C type corresponding to type tag TypeExpr.
6726///
6727/// \param TypeExpr Expression that specifies a type tag.
6728///
6729/// \param MagicValues Registered magic values.
6730///
6731/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
6732/// kind.
6733///
6734/// \param TypeInfo Information about the corresponding C type.
6735///
6736/// \returns true if the corresponding C type was found.
6737bool GetMatchingCType(
6738 const IdentifierInfo *ArgumentKind,
6739 const Expr *TypeExpr, const ASTContext &Ctx,
6740 const llvm::DenseMap<Sema::TypeTagMagicValue,
6741 Sema::TypeTagData> *MagicValues,
6742 bool &FoundWrongKind,
6743 Sema::TypeTagData &TypeInfo) {
6744 FoundWrongKind = false;
6745
6746 // Variable declaration that has type_tag_for_datatype attribute.
6747 const ValueDecl *VD = NULL;
6748
6749 uint64_t MagicValue;
6750
6751 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
6752 return false;
6753
6754 if (VD) {
6755 for (specific_attr_iterator<TypeTagForDatatypeAttr>
6756 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
6757 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
6758 I != E; ++I) {
6759 if (I->getArgumentKind() != ArgumentKind) {
6760 FoundWrongKind = true;
6761 return false;
6762 }
6763 TypeInfo.Type = I->getMatchingCType();
6764 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
6765 TypeInfo.MustBeNull = I->getMustBeNull();
6766 return true;
6767 }
6768 return false;
6769 }
6770
6771 if (!MagicValues)
6772 return false;
6773
6774 llvm::DenseMap<Sema::TypeTagMagicValue,
6775 Sema::TypeTagData>::const_iterator I =
6776 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
6777 if (I == MagicValues->end())
6778 return false;
6779
6780 TypeInfo = I->second;
6781 return true;
6782}
6783} // unnamed namespace
6784
6785void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
6786 uint64_t MagicValue, QualType Type,
6787 bool LayoutCompatible,
6788 bool MustBeNull) {
6789 if (!TypeTagForDatatypeMagicValues)
6790 TypeTagForDatatypeMagicValues.reset(
6791 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
6792
6793 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
6794 (*TypeTagForDatatypeMagicValues)[Magic] =
6795 TypeTagData(Type, LayoutCompatible, MustBeNull);
6796}
6797
6798namespace {
6799bool IsSameCharType(QualType T1, QualType T2) {
6800 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
6801 if (!BT1)
6802 return false;
6803
6804 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
6805 if (!BT2)
6806 return false;
6807
6808 BuiltinType::Kind T1Kind = BT1->getKind();
6809 BuiltinType::Kind T2Kind = BT2->getKind();
6810
6811 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
6812 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
6813 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
6814 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
6815}
6816} // unnamed namespace
6817
6818void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
6819 const Expr * const *ExprArgs) {
6820 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
6821 bool IsPointerAttr = Attr->getIsPointer();
6822
6823 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
6824 bool FoundWrongKind;
6825 TypeTagData TypeInfo;
6826 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
6827 TypeTagForDatatypeMagicValues.get(),
6828 FoundWrongKind, TypeInfo)) {
6829 if (FoundWrongKind)
6830 Diag(TypeTagExpr->getExprLoc(),
6831 diag::warn_type_tag_for_datatype_wrong_kind)
6832 << TypeTagExpr->getSourceRange();
6833 return;
6834 }
6835
6836 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
6837 if (IsPointerAttr) {
6838 // Skip implicit cast of pointer to `void *' (as a function argument).
6839 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5a249802012-11-03 16:07:49 +00006840 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkob57ce4e2012-11-03 22:10:18 +00006841 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006842 ArgumentExpr = ICE->getSubExpr();
6843 }
6844 QualType ArgumentType = ArgumentExpr->getType();
6845
6846 // Passing a `void*' pointer shouldn't trigger a warning.
6847 if (IsPointerAttr && ArgumentType->isVoidPointerType())
6848 return;
6849
6850 if (TypeInfo.MustBeNull) {
6851 // Type tag with matching void type requires a null pointer.
6852 if (!ArgumentExpr->isNullPointerConstant(Context,
6853 Expr::NPC_ValueDependentIsNotNull)) {
6854 Diag(ArgumentExpr->getExprLoc(),
6855 diag::warn_type_safety_null_pointer_required)
6856 << ArgumentKind->getName()
6857 << ArgumentExpr->getSourceRange()
6858 << TypeTagExpr->getSourceRange();
6859 }
6860 return;
6861 }
6862
6863 QualType RequiredType = TypeInfo.Type;
6864 if (IsPointerAttr)
6865 RequiredType = Context.getPointerType(RequiredType);
6866
6867 bool mismatch = false;
6868 if (!TypeInfo.LayoutCompatible) {
6869 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
6870
6871 // C++11 [basic.fundamental] p1:
6872 // Plain char, signed char, and unsigned char are three distinct types.
6873 //
6874 // But we treat plain `char' as equivalent to `signed char' or `unsigned
6875 // char' depending on the current char signedness mode.
6876 if (mismatch)
6877 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
6878 RequiredType->getPointeeType())) ||
6879 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
6880 mismatch = false;
6881 } else
6882 if (IsPointerAttr)
6883 mismatch = !isLayoutCompatible(Context,
6884 ArgumentType->getPointeeType(),
6885 RequiredType->getPointeeType());
6886 else
6887 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
6888
6889 if (mismatch)
6890 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
6891 << ArgumentType << ArgumentKind->getName()
6892 << TypeInfo.LayoutCompatible << RequiredType
6893 << ArgumentExpr->getSourceRange()
6894 << TypeTagExpr->getSourceRange();
6895}