blob: 3e6b39a09b3b9948921414538cf7c314f635893c [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-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 Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000035#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000036#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "llvm/ADT/SmallString.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000038#include "llvm/Support/ConvertUTF.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/Support/raw_ostream.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000040#include <limits>
Chris Lattnerb87b1b32007-08-10 20:18:51 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000043
Chris Lattnera26fb342009-02-18 17:49:48 +000044SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
Chris Lattnere925d612010-11-17 07:37:15 +000046 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +000047 PP.getLangOpts(), PP.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000048}
49
John McCallbebede42011-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 Lerouge4a5b4442012-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 Lerouge5a6b6982011-09-09 22:41:49 +000082 return true;
83 }
Julien Lerouge4a5b4442012-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 Lerouge5a6b6982011-09-09 22:41:49 +000095 return false;
96}
97
Richard Smith6cbd65d2013-07-11 02:27:57 +000098/// Check that the argument to __builtin_addressof is a glvalue, and set the
99/// result type to the corresponding pointer type.
100static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101 if (checkArgCount(S, TheCall, 1))
102 return true;
103
104 ExprResult Arg(S.Owned(TheCall->getArg(0)));
105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
107 return true;
108
109 TheCall->setArg(0, Arg.take());
110 TheCall->setType(ResultType);
111 return false;
112}
113
John McCalldadc5752010-08-24 06:29:42 +0000114ExprResult
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000115Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCalldadc5752010-08-24 06:29:42 +0000116 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000117
Chris Lattner3be167f2010-10-01 23:23:24 +0000118 // Find out if any arguments are required to be integer constant expressions.
119 unsigned ICEArguments = 0;
120 ASTContext::GetBuiltinTypeError Error;
121 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
122 if (Error != ASTContext::GE_None)
123 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
124
125 // If any arguments are required to be ICE's, check and diagnose.
126 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
127 // Skip arguments not required to be ICE's.
128 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
129
130 llvm::APSInt Result;
131 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
132 return true;
133 ICEArguments &= ~(1 << ArgNo);
134 }
135
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000136 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000137 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000138 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000139 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000140 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000141 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000142 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000143 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000144 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000145 if (SemaBuiltinVAStart(TheCall))
146 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000147 break;
Chris Lattner2da14fb2007-12-20 00:26:33 +0000148 case Builtin::BI__builtin_isgreater:
149 case Builtin::BI__builtin_isgreaterequal:
150 case Builtin::BI__builtin_isless:
151 case Builtin::BI__builtin_islessequal:
152 case Builtin::BI__builtin_islessgreater:
153 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000154 if (SemaBuiltinUnorderedCompare(TheCall))
155 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000156 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000157 case Builtin::BI__builtin_fpclassify:
158 if (SemaBuiltinFPClassification(TheCall, 6))
159 return ExprError();
160 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000161 case Builtin::BI__builtin_isfinite:
162 case Builtin::BI__builtin_isinf:
163 case Builtin::BI__builtin_isinf_sign:
164 case Builtin::BI__builtin_isnan:
165 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000166 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000167 return ExprError();
168 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000169 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000170 return SemaBuiltinShuffleVector(TheCall);
171 // TheCall will be freed by the smart pointer here, but that's fine, since
172 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000173 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000174 if (SemaBuiltinPrefetch(TheCall))
175 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000176 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000177 case Builtin::BI__builtin_object_size:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000178 if (SemaBuiltinObjectSize(TheCall))
179 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000180 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000181 case Builtin::BI__builtin_longjmp:
182 if (SemaBuiltinLongjmp(TheCall))
183 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000184 break;
John McCallbebede42011-02-26 05:39:39 +0000185
186 case Builtin::BI__builtin_classify_type:
187 if (checkArgCount(*this, TheCall, 1)) return true;
188 TheCall->setType(Context.IntTy);
189 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000190 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000191 if (checkArgCount(*this, TheCall, 1)) return true;
192 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000193 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000194 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000195 case Builtin::BI__sync_fetch_and_add_1:
196 case Builtin::BI__sync_fetch_and_add_2:
197 case Builtin::BI__sync_fetch_and_add_4:
198 case Builtin::BI__sync_fetch_and_add_8:
199 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000200 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000201 case Builtin::BI__sync_fetch_and_sub_1:
202 case Builtin::BI__sync_fetch_and_sub_2:
203 case Builtin::BI__sync_fetch_and_sub_4:
204 case Builtin::BI__sync_fetch_and_sub_8:
205 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000206 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000207 case Builtin::BI__sync_fetch_and_or_1:
208 case Builtin::BI__sync_fetch_and_or_2:
209 case Builtin::BI__sync_fetch_and_or_4:
210 case Builtin::BI__sync_fetch_and_or_8:
211 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000212 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000213 case Builtin::BI__sync_fetch_and_and_1:
214 case Builtin::BI__sync_fetch_and_and_2:
215 case Builtin::BI__sync_fetch_and_and_4:
216 case Builtin::BI__sync_fetch_and_and_8:
217 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000218 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000219 case Builtin::BI__sync_fetch_and_xor_1:
220 case Builtin::BI__sync_fetch_and_xor_2:
221 case Builtin::BI__sync_fetch_and_xor_4:
222 case Builtin::BI__sync_fetch_and_xor_8:
223 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000224 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000225 case Builtin::BI__sync_add_and_fetch_1:
226 case Builtin::BI__sync_add_and_fetch_2:
227 case Builtin::BI__sync_add_and_fetch_4:
228 case Builtin::BI__sync_add_and_fetch_8:
229 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000230 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000231 case Builtin::BI__sync_sub_and_fetch_1:
232 case Builtin::BI__sync_sub_and_fetch_2:
233 case Builtin::BI__sync_sub_and_fetch_4:
234 case Builtin::BI__sync_sub_and_fetch_8:
235 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000236 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000237 case Builtin::BI__sync_and_and_fetch_1:
238 case Builtin::BI__sync_and_and_fetch_2:
239 case Builtin::BI__sync_and_and_fetch_4:
240 case Builtin::BI__sync_and_and_fetch_8:
241 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000242 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000243 case Builtin::BI__sync_or_and_fetch_1:
244 case Builtin::BI__sync_or_and_fetch_2:
245 case Builtin::BI__sync_or_and_fetch_4:
246 case Builtin::BI__sync_or_and_fetch_8:
247 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000248 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000249 case Builtin::BI__sync_xor_and_fetch_1:
250 case Builtin::BI__sync_xor_and_fetch_2:
251 case Builtin::BI__sync_xor_and_fetch_4:
252 case Builtin::BI__sync_xor_and_fetch_8:
253 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000254 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000255 case Builtin::BI__sync_val_compare_and_swap_1:
256 case Builtin::BI__sync_val_compare_and_swap_2:
257 case Builtin::BI__sync_val_compare_and_swap_4:
258 case Builtin::BI__sync_val_compare_and_swap_8:
259 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000260 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000261 case Builtin::BI__sync_bool_compare_and_swap_1:
262 case Builtin::BI__sync_bool_compare_and_swap_2:
263 case Builtin::BI__sync_bool_compare_and_swap_4:
264 case Builtin::BI__sync_bool_compare_and_swap_8:
265 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000266 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000267 case Builtin::BI__sync_lock_test_and_set_1:
268 case Builtin::BI__sync_lock_test_and_set_2:
269 case Builtin::BI__sync_lock_test_and_set_4:
270 case Builtin::BI__sync_lock_test_and_set_8:
271 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000272 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000273 case Builtin::BI__sync_lock_release_1:
274 case Builtin::BI__sync_lock_release_2:
275 case Builtin::BI__sync_lock_release_4:
276 case Builtin::BI__sync_lock_release_8:
277 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000278 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000279 case Builtin::BI__sync_swap_1:
280 case Builtin::BI__sync_swap_2:
281 case Builtin::BI__sync_swap_4:
282 case Builtin::BI__sync_swap_8:
283 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000284 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000285#define BUILTIN(ID, TYPE, ATTRS)
286#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
287 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000288 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000289#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000290 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000291 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000292 return ExprError();
293 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000294 case Builtin::BI__builtin_addressof:
295 if (SemaBuiltinAddressof(*this, TheCall))
296 return ExprError();
297 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000298 }
299
300 // Since the target specific builtins for each arch overlap, only check those
301 // of the arch we are compiling for.
302 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000303 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000304 case llvm::Triple::arm:
305 case llvm::Triple::thumb:
306 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
307 return ExprError();
308 break;
Tim Northover2fe823a2013-08-01 09:23:19 +0000309 case llvm::Triple::aarch64:
310 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
311 return ExprError();
312 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000313 case llvm::Triple::mips:
314 case llvm::Triple::mipsel:
315 case llvm::Triple::mips64:
316 case llvm::Triple::mips64el:
317 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
318 return ExprError();
319 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000320 default:
321 break;
322 }
323 }
324
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000325 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000326}
327
Nate Begeman91e1fea2010-06-14 05:21:25 +0000328// Get the valid immediate range for the specified NEON type code.
329static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000330 NeonTypeFlags Type(t);
331 int IsQuad = Type.isQuad();
332 switch (Type.getEltType()) {
333 case NeonTypeFlags::Int8:
334 case NeonTypeFlags::Poly8:
335 return shift ? 7 : (8 << IsQuad) - 1;
336 case NeonTypeFlags::Int16:
337 case NeonTypeFlags::Poly16:
338 return shift ? 15 : (4 << IsQuad) - 1;
339 case NeonTypeFlags::Int32:
340 return shift ? 31 : (2 << IsQuad) - 1;
341 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000342 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000343 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000344 case NeonTypeFlags::Poly128:
345 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000346 case NeonTypeFlags::Float16:
347 assert(!shift && "cannot shift float types!");
348 return (4 << IsQuad) - 1;
349 case NeonTypeFlags::Float32:
350 assert(!shift && "cannot shift float types!");
351 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000352 case NeonTypeFlags::Float64:
353 assert(!shift && "cannot shift float types!");
354 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000355 }
David Blaikie8a40f702012-01-17 06:56:22 +0000356 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000357}
358
Bob Wilsone4d77232011-11-08 05:04:11 +0000359/// getNeonEltType - Return the QualType corresponding to the elements of
360/// the vector type specified by the NeonTypeFlags. This is used to check
361/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000362static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
363 bool IsAArch64) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000364 switch (Flags.getEltType()) {
365 case NeonTypeFlags::Int8:
366 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
367 case NeonTypeFlags::Int16:
368 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
369 case NeonTypeFlags::Int32:
370 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
371 case NeonTypeFlags::Int64:
372 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
373 case NeonTypeFlags::Poly8:
Kevin Qincaac85e2013-11-14 03:29:16 +0000374 return IsAArch64 ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000375 case NeonTypeFlags::Poly16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000376 return IsAArch64 ? Context.UnsignedShortTy : Context.ShortTy;
377 case NeonTypeFlags::Poly64:
378 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000379 case NeonTypeFlags::Poly128:
380 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000381 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000382 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000383 case NeonTypeFlags::Float32:
384 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000385 case NeonTypeFlags::Float64:
386 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000387 }
David Blaikie8a40f702012-01-17 06:56:22 +0000388 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000389}
390
Tim Northover2fe823a2013-08-01 09:23:19 +0000391bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
392 CallExpr *TheCall) {
393
394 llvm::APSInt Result;
395
396 uint64_t mask = 0;
397 unsigned TV = 0;
398 int PtrArgNum = -1;
399 bool HasConstPtr = false;
400 switch (BuiltinID) {
401#define GET_NEON_AARCH64_OVERLOAD_CHECK
402#include "clang/Basic/arm_neon.inc"
403#undef GET_NEON_AARCH64_OVERLOAD_CHECK
404 }
405
406 // For NEON intrinsics which are overloaded on vector element type, validate
407 // the immediate which specifies which variant to emit.
408 unsigned ImmArg = TheCall->getNumArgs() - 1;
409 if (mask) {
410 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
411 return true;
412
413 TV = Result.getLimitedValue(64);
414 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
415 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
416 << TheCall->getArg(ImmArg)->getSourceRange();
417 }
418
419 if (PtrArgNum >= 0) {
420 // Check that pointer arguments have the specified type.
421 Expr *Arg = TheCall->getArg(PtrArgNum);
422 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
423 Arg = ICE->getSubExpr();
424 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
425 QualType RHSTy = RHS.get()->getType();
Kevin Qincaac85e2013-11-14 03:29:16 +0000426 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context, true);
Tim Northover2fe823a2013-08-01 09:23:19 +0000427 if (HasConstPtr)
428 EltTy = EltTy.withConst();
429 QualType LHSTy = Context.getPointerType(EltTy);
430 AssignConvertType ConvTy;
431 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
432 if (RHS.isInvalid())
433 return true;
434 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
435 RHS.get(), AA_Assigning))
436 return true;
437 }
438
439 // For NEON intrinsics which take an immediate value as part of the
440 // instruction, range check them here.
441 unsigned i = 0, l = 0, u = 0;
442 switch (BuiltinID) {
443 default:
444 return false;
445#define GET_NEON_AARCH64_IMMEDIATE_CHECK
446#include "clang/Basic/arm_neon.inc"
447#undef GET_NEON_AARCH64_IMMEDIATE_CHECK
448 }
449 ;
450
451 // We can't check the value of a dependent argument.
452 if (TheCall->getArg(i)->isTypeDependent() ||
453 TheCall->getArg(i)->isValueDependent())
454 return false;
455
456 // Check that the immediate argument is actually a constant.
457 if (SemaBuiltinConstantArg(TheCall, i, Result))
458 return true;
459
460 // Range check against the upper/lower values for this isntruction.
461 unsigned Val = Result.getZExtValue();
462 if (Val < l || Val > (u + l))
463 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
464 << l << u + l << TheCall->getArg(i)->getSourceRange();
465
466 return false;
467}
468
Tim Northover6aacd492013-07-16 09:47:53 +0000469bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall) {
470 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
471 BuiltinID == ARM::BI__builtin_arm_strex) &&
472 "unexpected ARM builtin");
473 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex;
474
475 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
476
477 // Ensure that we have the proper number of arguments.
478 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
479 return true;
480
481 // Inspect the pointer argument of the atomic builtin. This should always be
482 // a pointer type, whose element is an integral scalar or pointer type.
483 // Because it is a pointer type, we don't have to worry about any implicit
484 // casts here.
485 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
486 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
487 if (PointerArgRes.isInvalid())
488 return true;
489 PointerArg = PointerArgRes.take();
490
491 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
492 if (!pointerType) {
493 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
494 << PointerArg->getType() << PointerArg->getSourceRange();
495 return true;
496 }
497
498 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
499 // task is to insert the appropriate casts into the AST. First work out just
500 // what the appropriate type is.
501 QualType ValType = pointerType->getPointeeType();
502 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
503 if (IsLdrex)
504 AddrType.addConst();
505
506 // Issue a warning if the cast is dodgy.
507 CastKind CastNeeded = CK_NoOp;
508 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
509 CastNeeded = CK_BitCast;
510 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
511 << PointerArg->getType()
512 << Context.getPointerType(AddrType)
513 << AA_Passing << PointerArg->getSourceRange();
514 }
515
516 // Finally, do the cast and replace the argument with the corrected version.
517 AddrType = Context.getPointerType(AddrType);
518 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
519 if (PointerArgRes.isInvalid())
520 return true;
521 PointerArg = PointerArgRes.take();
522
523 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
524
525 // In general, we allow ints, floats and pointers to be loaded and stored.
526 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
527 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
528 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
529 << PointerArg->getType() << PointerArg->getSourceRange();
530 return true;
531 }
532
533 // But ARM doesn't have instructions to deal with 128-bit versions.
534 if (Context.getTypeSize(ValType) > 64) {
535 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
536 << PointerArg->getType() << PointerArg->getSourceRange();
537 return true;
538 }
539
540 switch (ValType.getObjCLifetime()) {
541 case Qualifiers::OCL_None:
542 case Qualifiers::OCL_ExplicitNone:
543 // okay
544 break;
545
546 case Qualifiers::OCL_Weak:
547 case Qualifiers::OCL_Strong:
548 case Qualifiers::OCL_Autoreleasing:
549 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
550 << ValType << PointerArg->getSourceRange();
551 return true;
552 }
553
554
555 if (IsLdrex) {
556 TheCall->setType(ValType);
557 return false;
558 }
559
560 // Initialize the argument to be stored.
561 ExprResult ValArg = TheCall->getArg(0);
562 InitializedEntity Entity = InitializedEntity::InitializeParameter(
563 Context, ValType, /*consume*/ false);
564 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
565 if (ValArg.isInvalid())
566 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000567 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000568
569 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
570 // but the custom checker bypasses all default analysis.
571 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000572 return false;
573}
574
Nate Begeman4904e322010-06-08 02:47:44 +0000575bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000576 llvm::APSInt Result;
577
Tim Northover6aacd492013-07-16 09:47:53 +0000578 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
579 BuiltinID == ARM::BI__builtin_arm_strex) {
580 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall);
581 }
582
Richard Smith7d6d47b2012-08-14 01:28:02 +0000583 uint64_t mask = 0;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000584 unsigned TV = 0;
Bob Wilson89d14242011-11-16 21:32:23 +0000585 int PtrArgNum = -1;
Bob Wilsone4d77232011-11-08 05:04:11 +0000586 bool HasConstPtr = false;
Nate Begeman55483092010-06-09 01:10:23 +0000587 switch (BuiltinID) {
Nate Begeman35f4c1c2010-06-17 04:17:01 +0000588#define GET_NEON_OVERLOAD_CHECK
589#include "clang/Basic/arm_neon.inc"
590#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman55483092010-06-09 01:10:23 +0000591 }
592
Nate Begemand773fe62010-06-13 04:47:52 +0000593 // For NEON intrinsics which are overloaded on vector element type, validate
594 // the immediate which specifies which variant to emit.
Bob Wilsone4d77232011-11-08 05:04:11 +0000595 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begemand773fe62010-06-13 04:47:52 +0000596 if (mask) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000597 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begemand773fe62010-06-13 04:47:52 +0000598 return true;
599
Bob Wilson98bc98c2011-11-08 01:16:11 +0000600 TV = Result.getLimitedValue(64);
Richard Smith7d6d47b2012-08-14 01:28:02 +0000601 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
Nate Begemand773fe62010-06-13 04:47:52 +0000602 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilsone4d77232011-11-08 05:04:11 +0000603 << TheCall->getArg(ImmArg)->getSourceRange();
604 }
605
Bob Wilson89d14242011-11-16 21:32:23 +0000606 if (PtrArgNum >= 0) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000607 // Check that pointer arguments have the specified type.
Bob Wilson89d14242011-11-16 21:32:23 +0000608 Expr *Arg = TheCall->getArg(PtrArgNum);
609 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
610 Arg = ICE->getSubExpr();
611 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
612 QualType RHSTy = RHS.get()->getType();
Kevin Qincaac85e2013-11-14 03:29:16 +0000613 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context, false);
Bob Wilson89d14242011-11-16 21:32:23 +0000614 if (HasConstPtr)
615 EltTy = EltTy.withConst();
616 QualType LHSTy = Context.getPointerType(EltTy);
617 AssignConvertType ConvTy;
618 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
619 if (RHS.isInvalid())
620 return true;
621 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
622 RHS.get(), AA_Assigning))
623 return true;
Nate Begemand773fe62010-06-13 04:47:52 +0000624 }
Nico Weber0e6daef2013-12-26 23:38:39 +0000625
Nate Begemand773fe62010-06-13 04:47:52 +0000626 // For NEON intrinsics which take an immediate value as part of the
627 // instruction, range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000628 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000629 switch (BuiltinID) {
630 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000631 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
632 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000633 case ARM::BI__builtin_arm_vcvtr_f:
634 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000635 case ARM::BI__builtin_arm_dmb:
636 case ARM::BI__builtin_arm_dsb: l = 0; u = 15; break;
Nate Begeman35f4c1c2010-06-17 04:17:01 +0000637#define GET_NEON_IMMEDIATE_CHECK
638#include "clang/Basic/arm_neon.inc"
639#undef GET_NEON_IMMEDIATE_CHECK
Nate Begemand773fe62010-06-13 04:47:52 +0000640 };
641
Douglas Gregor98c3cfc2012-06-29 01:05:22 +0000642 // We can't check the value of a dependent argument.
643 if (TheCall->getArg(i)->isTypeDependent() ||
644 TheCall->getArg(i)->isValueDependent())
645 return false;
646
Nate Begeman91e1fea2010-06-14 05:21:25 +0000647 // Check that the immediate argument is actually a constant.
Nate Begemand773fe62010-06-13 04:47:52 +0000648 if (SemaBuiltinConstantArg(TheCall, i, Result))
649 return true;
650
Nate Begeman91e1fea2010-06-14 05:21:25 +0000651 // Range check against the upper/lower values for this isntruction.
Nate Begemand773fe62010-06-13 04:47:52 +0000652 unsigned Val = Result.getZExtValue();
Nate Begeman91e1fea2010-06-14 05:21:25 +0000653 if (Val < l || Val > (u + l))
Nate Begemand773fe62010-06-13 04:47:52 +0000654 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramere8394df2010-08-11 14:47:12 +0000655 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begemand773fe62010-06-13 04:47:52 +0000656
Nate Begemanf568b072010-08-03 21:32:34 +0000657 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman4904e322010-06-08 02:47:44 +0000658 return false;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000659}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000660
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000661bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
662 unsigned i = 0, l = 0, u = 0;
663 switch (BuiltinID) {
664 default: return false;
665 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
666 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000667 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
668 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
669 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
670 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
671 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000672 };
673
674 // We can't check the value of a dependent argument.
675 if (TheCall->getArg(i)->isTypeDependent() ||
676 TheCall->getArg(i)->isValueDependent())
677 return false;
678
679 // Check that the immediate argument is actually a constant.
680 llvm::APSInt Result;
681 if (SemaBuiltinConstantArg(TheCall, i, Result))
682 return true;
683
684 // Range check against the upper/lower values for this instruction.
685 unsigned Val = Result.getZExtValue();
686 if (Val < l || Val > u)
687 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
688 << l << u << TheCall->getArg(i)->getSourceRange();
689
690 return false;
691}
692
Richard Smith55ce3522012-06-25 20:30:08 +0000693/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
694/// parameter with the FormatAttr's correct format_idx and firstDataArg.
695/// Returns true when the format fits the function and the FormatStringInfo has
696/// been populated.
697bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
698 FormatStringInfo *FSI) {
699 FSI->HasVAListArg = Format->getFirstArg() == 0;
700 FSI->FormatIdx = Format->getFormatIdx() - 1;
701 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000702
Richard Smith55ce3522012-06-25 20:30:08 +0000703 // The way the format attribute works in GCC, the implicit this argument
704 // of member functions is counted. However, it doesn't appear in our own
705 // lists, so decrement format_idx in that case.
706 if (IsCXXMember) {
707 if(FSI->FormatIdx == 0)
708 return false;
709 --FSI->FormatIdx;
710 if (FSI->FirstDataArg != 0)
711 --FSI->FirstDataArg;
712 }
713 return true;
714}
Mike Stump11289f42009-09-09 15:08:12 +0000715
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000716/// Checks if a the given expression evaluates to null.
717///
718/// \brief Returns true if the value evaluates to null.
719static bool CheckNonNullExpr(Sema &S,
720 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000721 // As a special case, transparent unions initialized with zero are
722 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000723 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000724 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
725 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000726 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000727 if (const InitListExpr *ILE =
728 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000729 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000730 }
731
732 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000733 return (!Expr->isValueDependent() &&
734 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
735 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000736}
737
738static void CheckNonNullArgument(Sema &S,
739 const Expr *ArgExpr,
740 SourceLocation CallSiteLoc) {
741 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000742 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
743}
744
Ted Kremenek2bc73332014-01-17 06:24:43 +0000745static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +0000746 const NamedDecl *FDecl,
Ted Kremenek2bc73332014-01-17 06:24:43 +0000747 const Expr * const *ExprArgs,
748 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000749 // Check the attributes attached to the method/function itself.
Ted Kremeneka146db32014-01-17 06:24:47 +0000750 for (specific_attr_iterator<NonNullAttr>
751 I = FDecl->specific_attr_begin<NonNullAttr>(),
752 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I) {
Ted Kremenek2bc73332014-01-17 06:24:43 +0000753
Ted Kremeneka146db32014-01-17 06:24:47 +0000754 const NonNullAttr *NonNull = *I;
755 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
756 e = NonNull->args_end();
757 i != e; ++i) {
758 CheckNonNullArgument(S, ExprArgs[*i], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +0000759 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000760 }
Ted Kremenek9aedc152014-01-17 06:24:56 +0000761
762 // Check the attributes on the parameters.
763 ArrayRef<ParmVarDecl*> parms;
764 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
765 parms = FD->parameters();
766 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
767 parms = MD->parameters();
768
769 unsigned argIndex = 0;
770 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
771 I != E; ++I, ++argIndex) {
772 const ParmVarDecl *PVD = *I;
773 if (PVD->hasAttr<NonNullAttr>())
774 CheckNonNullArgument(S, ExprArgs[argIndex], CallSiteLoc);
775 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000776}
777
Richard Smith55ce3522012-06-25 20:30:08 +0000778/// Handles the checks for format strings, non-POD arguments to vararg
779/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000780void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
781 unsigned NumParams, bool IsMemberFunction,
782 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +0000783 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +0000784 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +0000785 if (CurContext->isDependentContext())
786 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000787
Ted Kremenekb8176da2010-09-09 04:33:05 +0000788 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +0000789 llvm::SmallBitVector CheckedVarArgs;
790 if (FDecl) {
Richard Trieu41bc0992013-06-22 00:20:41 +0000791 for (specific_attr_iterator<FormatAttr>
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000792 I = FDecl->specific_attr_begin<FormatAttr>(),
793 E = FDecl->specific_attr_end<FormatAttr>();
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000794 I != E; ++I) {
795 // Only create vector if there are format attributes.
796 CheckedVarArgs.resize(Args.size());
797
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000798 CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc, Range,
799 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000800 }
Richard Smithd7293d72013-08-05 18:49:43 +0000801 }
Richard Smith55ce3522012-06-25 20:30:08 +0000802
803 // Refuse POD arguments that weren't caught by the format string
804 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +0000805 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000806 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000807 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +0000808 if (const Expr *Arg = Args[ArgIdx]) {
809 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
810 checkVariadicArgument(Arg, CallType);
811 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000812 }
Richard Smithd7293d72013-08-05 18:49:43 +0000813 }
Mike Stump11289f42009-09-09 15:08:12 +0000814
Richard Trieu41bc0992013-06-22 00:20:41 +0000815 if (FDecl) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000816 CheckNonNullArguments(*this, FDecl, Args.data(), Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000817
Richard Trieu41bc0992013-06-22 00:20:41 +0000818 // Type safety checking.
819 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
820 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
821 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>();
822 i != e; ++i) {
823 CheckArgumentWithTypeTag(*i, Args.data());
824 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000825 }
Richard Smith55ce3522012-06-25 20:30:08 +0000826}
827
828/// CheckConstructorCall - Check a constructor call for correctness and safety
829/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000830void Sema::CheckConstructorCall(FunctionDecl *FDecl,
831 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +0000832 const FunctionProtoType *Proto,
833 SourceLocation Loc) {
834 VariadicCallType CallType =
835 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +0000836 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +0000837 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
838}
839
840/// CheckFunctionCall - Check a direct function call for various correctness
841/// and safety properties not strictly enforced by the C type system.
842bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
843 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000844 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
845 isa<CXXMethodDecl>(FDecl);
846 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
847 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +0000848 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
849 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000850 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +0000851 Expr** Args = TheCall->getArgs();
852 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +0000853 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000854 // If this is a call to a member operator, hide the first argument
855 // from checkCall.
856 // FIXME: Our choice of AST representation here is less than ideal.
857 ++Args;
858 --NumArgs;
859 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000860 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +0000861 IsMemberFunction, TheCall->getRParenLoc(),
862 TheCall->getCallee()->getSourceRange(), CallType);
863
864 IdentifierInfo *FnInfo = FDecl->getIdentifier();
865 // None of the checks below are needed for functions that don't have
866 // simple names (e.g., C++ conversion functions).
867 if (!FnInfo)
868 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000869
Anna Zaks22122702012-01-17 00:37:07 +0000870 unsigned CMId = FDecl->getMemoryFunctionKind();
871 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +0000872 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +0000873
Anna Zaks201d4892012-01-13 21:52:01 +0000874 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +0000875 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +0000876 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +0000877 else if (CMId == Builtin::BIstrncat)
878 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +0000879 else
Anna Zaks22122702012-01-17 00:37:07 +0000880 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +0000881
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000882 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000883}
884
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000885bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000886 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +0000887 VariadicCallType CallType =
888 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000889
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000890 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +0000891 /*IsMemberFunction=*/false,
892 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000893
894 return false;
895}
896
Richard Trieu664c4c62013-06-20 21:03:13 +0000897bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
898 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000899 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
900 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000901 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000902
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000903 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +0000904 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000905 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000906
Richard Trieu664c4c62013-06-20 21:03:13 +0000907 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +0000908 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +0000909 CallType = VariadicDoesNotApply;
910 } else if (Ty->isBlockPointerType()) {
911 CallType = VariadicBlock;
912 } else { // Ty->isFunctionPointerType()
913 CallType = VariadicFunction;
914 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000915 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000916
Alp Toker9cacbab2014-01-20 20:26:09 +0000917 checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
918 TheCall->getNumArgs()),
919 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +0000920 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +0000921
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000922 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000923}
924
Richard Trieu41bc0992013-06-22 00:20:41 +0000925/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
926/// such as function pointers returned from functions.
927bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
928 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
929 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000930 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +0000931
Alp Toker9cacbab2014-01-20 20:26:09 +0000932 checkCall(/*FDecl=*/0, llvm::makeArrayRef<const Expr *>(
933 TheCall->getArgs(), TheCall->getNumArgs()),
934 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +0000935 TheCall->getCallee()->getSourceRange(), CallType);
936
937 return false;
938}
939
Richard Smithfeea8832012-04-12 05:08:17 +0000940ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
941 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000942 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
943 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000944
Richard Smithfeea8832012-04-12 05:08:17 +0000945 // All these operations take one of the following forms:
946 enum {
947 // C __c11_atomic_init(A *, C)
948 Init,
949 // C __c11_atomic_load(A *, int)
950 Load,
951 // void __atomic_load(A *, CP, int)
952 Copy,
953 // C __c11_atomic_add(A *, M, int)
954 Arithmetic,
955 // C __atomic_exchange_n(A *, CP, int)
956 Xchg,
957 // void __atomic_exchange(A *, C *, CP, int)
958 GNUXchg,
959 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
960 C11CmpXchg,
961 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
962 GNUCmpXchg
963 } Form = Init;
964 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
965 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
966 // where:
967 // C is an appropriate type,
968 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
969 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
970 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
971 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000972
Richard Smithfeea8832012-04-12 05:08:17 +0000973 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
974 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
975 && "need to update code for modified C11 atomics");
976 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
977 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
978 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
979 Op == AtomicExpr::AO__atomic_store_n ||
980 Op == AtomicExpr::AO__atomic_exchange_n ||
981 Op == AtomicExpr::AO__atomic_compare_exchange_n;
982 bool IsAddSub = false;
983
984 switch (Op) {
985 case AtomicExpr::AO__c11_atomic_init:
986 Form = Init;
987 break;
988
989 case AtomicExpr::AO__c11_atomic_load:
990 case AtomicExpr::AO__atomic_load_n:
991 Form = Load;
992 break;
993
994 case AtomicExpr::AO__c11_atomic_store:
995 case AtomicExpr::AO__atomic_load:
996 case AtomicExpr::AO__atomic_store:
997 case AtomicExpr::AO__atomic_store_n:
998 Form = Copy;
999 break;
1000
1001 case AtomicExpr::AO__c11_atomic_fetch_add:
1002 case AtomicExpr::AO__c11_atomic_fetch_sub:
1003 case AtomicExpr::AO__atomic_fetch_add:
1004 case AtomicExpr::AO__atomic_fetch_sub:
1005 case AtomicExpr::AO__atomic_add_fetch:
1006 case AtomicExpr::AO__atomic_sub_fetch:
1007 IsAddSub = true;
1008 // Fall through.
1009 case AtomicExpr::AO__c11_atomic_fetch_and:
1010 case AtomicExpr::AO__c11_atomic_fetch_or:
1011 case AtomicExpr::AO__c11_atomic_fetch_xor:
1012 case AtomicExpr::AO__atomic_fetch_and:
1013 case AtomicExpr::AO__atomic_fetch_or:
1014 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001015 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001016 case AtomicExpr::AO__atomic_and_fetch:
1017 case AtomicExpr::AO__atomic_or_fetch:
1018 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001019 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001020 Form = Arithmetic;
1021 break;
1022
1023 case AtomicExpr::AO__c11_atomic_exchange:
1024 case AtomicExpr::AO__atomic_exchange_n:
1025 Form = Xchg;
1026 break;
1027
1028 case AtomicExpr::AO__atomic_exchange:
1029 Form = GNUXchg;
1030 break;
1031
1032 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1033 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1034 Form = C11CmpXchg;
1035 break;
1036
1037 case AtomicExpr::AO__atomic_compare_exchange:
1038 case AtomicExpr::AO__atomic_compare_exchange_n:
1039 Form = GNUCmpXchg;
1040 break;
1041 }
1042
1043 // Check we have the right number of arguments.
1044 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001045 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001046 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001047 << TheCall->getCallee()->getSourceRange();
1048 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001049 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1050 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001051 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001052 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001053 << TheCall->getCallee()->getSourceRange();
1054 return ExprError();
1055 }
1056
Richard Smithfeea8832012-04-12 05:08:17 +00001057 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001058 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001059 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1060 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1061 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001062 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001063 << Ptr->getType() << Ptr->getSourceRange();
1064 return ExprError();
1065 }
1066
Richard Smithfeea8832012-04-12 05:08:17 +00001067 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1068 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1069 QualType ValType = AtomTy; // 'C'
1070 if (IsC11) {
1071 if (!AtomTy->isAtomicType()) {
1072 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1073 << Ptr->getType() << Ptr->getSourceRange();
1074 return ExprError();
1075 }
Richard Smithe00921a2012-09-15 06:09:58 +00001076 if (AtomTy.isConstQualified()) {
1077 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1078 << Ptr->getType() << Ptr->getSourceRange();
1079 return ExprError();
1080 }
Richard Smithfeea8832012-04-12 05:08:17 +00001081 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001082 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001083
Richard Smithfeea8832012-04-12 05:08:17 +00001084 // For an arithmetic operation, the implied arithmetic must be well-formed.
1085 if (Form == Arithmetic) {
1086 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1087 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1088 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1089 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1090 return ExprError();
1091 }
1092 if (!IsAddSub && !ValType->isIntegerType()) {
1093 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1094 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1095 return ExprError();
1096 }
1097 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1098 // For __atomic_*_n operations, the value type must be a scalar integral or
1099 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001100 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001101 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1102 return ExprError();
1103 }
1104
Eli Friedmanaa769812013-09-11 03:49:34 +00001105 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1106 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001107 // For GNU atomics, require a trivially-copyable type. This is not part of
1108 // the GNU atomics specification, but we enforce it for sanity.
1109 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001110 << Ptr->getType() << Ptr->getSourceRange();
1111 return ExprError();
1112 }
1113
Richard Smithfeea8832012-04-12 05:08:17 +00001114 // FIXME: For any builtin other than a load, the ValType must not be
1115 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001116
1117 switch (ValType.getObjCLifetime()) {
1118 case Qualifiers::OCL_None:
1119 case Qualifiers::OCL_ExplicitNone:
1120 // okay
1121 break;
1122
1123 case Qualifiers::OCL_Weak:
1124 case Qualifiers::OCL_Strong:
1125 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001126 // FIXME: Can this happen? By this point, ValType should be known
1127 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001128 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1129 << ValType << Ptr->getSourceRange();
1130 return ExprError();
1131 }
1132
1133 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001134 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001135 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001136 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001137 ResultType = Context.BoolTy;
1138
Richard Smithfeea8832012-04-12 05:08:17 +00001139 // The type of a parameter passed 'by value'. In the GNU atomics, such
1140 // arguments are actually passed as pointers.
1141 QualType ByValType = ValType; // 'CP'
1142 if (!IsC11 && !IsN)
1143 ByValType = Ptr->getType();
1144
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001145 // The first argument --- the pointer --- has a fixed type; we
1146 // deduce the types of the rest of the arguments accordingly. Walk
1147 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001148 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001149 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001150 if (i < NumVals[Form] + 1) {
1151 switch (i) {
1152 case 1:
1153 // The second argument is the non-atomic operand. For arithmetic, this
1154 // is always passed by value, and for a compare_exchange it is always
1155 // passed by address. For the rest, GNU uses by-address and C11 uses
1156 // by-value.
1157 assert(Form != Load);
1158 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1159 Ty = ValType;
1160 else if (Form == Copy || Form == Xchg)
1161 Ty = ByValType;
1162 else if (Form == Arithmetic)
1163 Ty = Context.getPointerDiffType();
1164 else
1165 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1166 break;
1167 case 2:
1168 // The third argument to compare_exchange / GNU exchange is a
1169 // (pointer to a) desired value.
1170 Ty = ByValType;
1171 break;
1172 case 3:
1173 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1174 Ty = Context.BoolTy;
1175 break;
1176 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001177 } else {
1178 // The order(s) are always converted to int.
1179 Ty = Context.IntTy;
1180 }
Richard Smithfeea8832012-04-12 05:08:17 +00001181
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001182 InitializedEntity Entity =
1183 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001184 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001185 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1186 if (Arg.isInvalid())
1187 return true;
1188 TheCall->setArg(i, Arg.get());
1189 }
1190
Richard Smithfeea8832012-04-12 05:08:17 +00001191 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001192 SmallVector<Expr*, 5> SubExprs;
1193 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001194 switch (Form) {
1195 case Init:
1196 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001197 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001198 break;
1199 case Load:
1200 SubExprs.push_back(TheCall->getArg(1)); // Order
1201 break;
1202 case Copy:
1203 case Arithmetic:
1204 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001205 SubExprs.push_back(TheCall->getArg(2)); // Order
1206 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001207 break;
1208 case GNUXchg:
1209 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1210 SubExprs.push_back(TheCall->getArg(3)); // Order
1211 SubExprs.push_back(TheCall->getArg(1)); // Val1
1212 SubExprs.push_back(TheCall->getArg(2)); // Val2
1213 break;
1214 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001215 SubExprs.push_back(TheCall->getArg(3)); // Order
1216 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001217 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001218 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001219 break;
1220 case GNUCmpXchg:
1221 SubExprs.push_back(TheCall->getArg(4)); // Order
1222 SubExprs.push_back(TheCall->getArg(1)); // Val1
1223 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1224 SubExprs.push_back(TheCall->getArg(2)); // Val2
1225 SubExprs.push_back(TheCall->getArg(3)); // Weak
1226 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001227 }
Fariborz Jahanian615de762013-05-28 17:37:39 +00001228
1229 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1230 SubExprs, ResultType, Op,
1231 TheCall->getRParenLoc());
1232
1233 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1234 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1235 Context.AtomicUsesUnsupportedLibcall(AE))
1236 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1237 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001238
Fariborz Jahanian615de762013-05-28 17:37:39 +00001239 return Owned(AE);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001240}
1241
1242
John McCall29ad95b2011-08-27 01:09:30 +00001243/// checkBuiltinArgument - Given a call to a builtin function, perform
1244/// normal type-checking on the given argument, updating the call in
1245/// place. This is useful when a builtin function requires custom
1246/// type-checking for some of its arguments but not necessarily all of
1247/// them.
1248///
1249/// Returns true on error.
1250static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1251 FunctionDecl *Fn = E->getDirectCallee();
1252 assert(Fn && "builtin call without direct callee!");
1253
1254 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1255 InitializedEntity Entity =
1256 InitializedEntity::InitializeParameter(S.Context, Param);
1257
1258 ExprResult Arg = E->getArg(0);
1259 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1260 if (Arg.isInvalid())
1261 return true;
1262
1263 E->setArg(ArgIndex, Arg.take());
1264 return false;
1265}
1266
Chris Lattnerdc046542009-05-08 06:58:22 +00001267/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1268/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1269/// type of its first argument. The main ActOnCallExpr routines have already
1270/// promoted the types of arguments because all of these calls are prototyped as
1271/// void(...).
1272///
1273/// This function goes through and does final semantic checking for these
1274/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001275ExprResult
1276Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001277 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001278 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1279 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1280
1281 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001282 if (TheCall->getNumArgs() < 1) {
1283 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1284 << 0 << 1 << TheCall->getNumArgs()
1285 << TheCall->getCallee()->getSourceRange();
1286 return ExprError();
1287 }
Mike Stump11289f42009-09-09 15:08:12 +00001288
Chris Lattnerdc046542009-05-08 06:58:22 +00001289 // Inspect the first argument of the atomic builtin. This should always be
1290 // a pointer type, whose element is an integral scalar or pointer type.
1291 // Because it is a pointer type, we don't have to worry about any implicit
1292 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001293 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001294 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001295 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1296 if (FirstArgResult.isInvalid())
1297 return ExprError();
1298 FirstArg = FirstArgResult.take();
1299 TheCall->setArg(0, FirstArg);
1300
John McCall31168b02011-06-15 23:02:42 +00001301 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1302 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001303 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1304 << FirstArg->getType() << FirstArg->getSourceRange();
1305 return ExprError();
1306 }
Mike Stump11289f42009-09-09 15:08:12 +00001307
John McCall31168b02011-06-15 23:02:42 +00001308 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001309 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001310 !ValType->isBlockPointerType()) {
1311 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1312 << FirstArg->getType() << FirstArg->getSourceRange();
1313 return ExprError();
1314 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001315
John McCall31168b02011-06-15 23:02:42 +00001316 switch (ValType.getObjCLifetime()) {
1317 case Qualifiers::OCL_None:
1318 case Qualifiers::OCL_ExplicitNone:
1319 // okay
1320 break;
1321
1322 case Qualifiers::OCL_Weak:
1323 case Qualifiers::OCL_Strong:
1324 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001325 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001326 << ValType << FirstArg->getSourceRange();
1327 return ExprError();
1328 }
1329
John McCallb50451a2011-10-05 07:41:44 +00001330 // Strip any qualifiers off ValType.
1331 ValType = ValType.getUnqualifiedType();
1332
Chandler Carruth3973af72010-07-18 20:54:12 +00001333 // The majority of builtins return a value, but a few have special return
1334 // types, so allow them to override appropriately below.
1335 QualType ResultType = ValType;
1336
Chris Lattnerdc046542009-05-08 06:58:22 +00001337 // We need to figure out which concrete builtin this maps onto. For example,
1338 // __sync_fetch_and_add with a 2 byte object turns into
1339 // __sync_fetch_and_add_2.
1340#define BUILTIN_ROW(x) \
1341 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1342 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001343
Chris Lattnerdc046542009-05-08 06:58:22 +00001344 static const unsigned BuiltinIndices[][5] = {
1345 BUILTIN_ROW(__sync_fetch_and_add),
1346 BUILTIN_ROW(__sync_fetch_and_sub),
1347 BUILTIN_ROW(__sync_fetch_and_or),
1348 BUILTIN_ROW(__sync_fetch_and_and),
1349 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +00001350
Chris Lattnerdc046542009-05-08 06:58:22 +00001351 BUILTIN_ROW(__sync_add_and_fetch),
1352 BUILTIN_ROW(__sync_sub_and_fetch),
1353 BUILTIN_ROW(__sync_and_and_fetch),
1354 BUILTIN_ROW(__sync_or_and_fetch),
1355 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001356
Chris Lattnerdc046542009-05-08 06:58:22 +00001357 BUILTIN_ROW(__sync_val_compare_and_swap),
1358 BUILTIN_ROW(__sync_bool_compare_and_swap),
1359 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001360 BUILTIN_ROW(__sync_lock_release),
1361 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001362 };
Mike Stump11289f42009-09-09 15:08:12 +00001363#undef BUILTIN_ROW
1364
Chris Lattnerdc046542009-05-08 06:58:22 +00001365 // Determine the index of the size.
1366 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001367 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001368 case 1: SizeIndex = 0; break;
1369 case 2: SizeIndex = 1; break;
1370 case 4: SizeIndex = 2; break;
1371 case 8: SizeIndex = 3; break;
1372 case 16: SizeIndex = 4; break;
1373 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001374 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1375 << FirstArg->getType() << FirstArg->getSourceRange();
1376 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001377 }
Mike Stump11289f42009-09-09 15:08:12 +00001378
Chris Lattnerdc046542009-05-08 06:58:22 +00001379 // Each of these builtins has one pointer argument, followed by some number of
1380 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1381 // that we ignore. Find out which row of BuiltinIndices to read from as well
1382 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001383 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001384 unsigned BuiltinIndex, NumFixed = 1;
1385 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001386 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001387 case Builtin::BI__sync_fetch_and_add:
1388 case Builtin::BI__sync_fetch_and_add_1:
1389 case Builtin::BI__sync_fetch_and_add_2:
1390 case Builtin::BI__sync_fetch_and_add_4:
1391 case Builtin::BI__sync_fetch_and_add_8:
1392 case Builtin::BI__sync_fetch_and_add_16:
1393 BuiltinIndex = 0;
1394 break;
1395
1396 case Builtin::BI__sync_fetch_and_sub:
1397 case Builtin::BI__sync_fetch_and_sub_1:
1398 case Builtin::BI__sync_fetch_and_sub_2:
1399 case Builtin::BI__sync_fetch_and_sub_4:
1400 case Builtin::BI__sync_fetch_and_sub_8:
1401 case Builtin::BI__sync_fetch_and_sub_16:
1402 BuiltinIndex = 1;
1403 break;
1404
1405 case Builtin::BI__sync_fetch_and_or:
1406 case Builtin::BI__sync_fetch_and_or_1:
1407 case Builtin::BI__sync_fetch_and_or_2:
1408 case Builtin::BI__sync_fetch_and_or_4:
1409 case Builtin::BI__sync_fetch_and_or_8:
1410 case Builtin::BI__sync_fetch_and_or_16:
1411 BuiltinIndex = 2;
1412 break;
1413
1414 case Builtin::BI__sync_fetch_and_and:
1415 case Builtin::BI__sync_fetch_and_and_1:
1416 case Builtin::BI__sync_fetch_and_and_2:
1417 case Builtin::BI__sync_fetch_and_and_4:
1418 case Builtin::BI__sync_fetch_and_and_8:
1419 case Builtin::BI__sync_fetch_and_and_16:
1420 BuiltinIndex = 3;
1421 break;
Mike Stump11289f42009-09-09 15:08:12 +00001422
Douglas Gregor73722482011-11-28 16:30:08 +00001423 case Builtin::BI__sync_fetch_and_xor:
1424 case Builtin::BI__sync_fetch_and_xor_1:
1425 case Builtin::BI__sync_fetch_and_xor_2:
1426 case Builtin::BI__sync_fetch_and_xor_4:
1427 case Builtin::BI__sync_fetch_and_xor_8:
1428 case Builtin::BI__sync_fetch_and_xor_16:
1429 BuiltinIndex = 4;
1430 break;
1431
1432 case Builtin::BI__sync_add_and_fetch:
1433 case Builtin::BI__sync_add_and_fetch_1:
1434 case Builtin::BI__sync_add_and_fetch_2:
1435 case Builtin::BI__sync_add_and_fetch_4:
1436 case Builtin::BI__sync_add_and_fetch_8:
1437 case Builtin::BI__sync_add_and_fetch_16:
1438 BuiltinIndex = 5;
1439 break;
1440
1441 case Builtin::BI__sync_sub_and_fetch:
1442 case Builtin::BI__sync_sub_and_fetch_1:
1443 case Builtin::BI__sync_sub_and_fetch_2:
1444 case Builtin::BI__sync_sub_and_fetch_4:
1445 case Builtin::BI__sync_sub_and_fetch_8:
1446 case Builtin::BI__sync_sub_and_fetch_16:
1447 BuiltinIndex = 6;
1448 break;
1449
1450 case Builtin::BI__sync_and_and_fetch:
1451 case Builtin::BI__sync_and_and_fetch_1:
1452 case Builtin::BI__sync_and_and_fetch_2:
1453 case Builtin::BI__sync_and_and_fetch_4:
1454 case Builtin::BI__sync_and_and_fetch_8:
1455 case Builtin::BI__sync_and_and_fetch_16:
1456 BuiltinIndex = 7;
1457 break;
1458
1459 case Builtin::BI__sync_or_and_fetch:
1460 case Builtin::BI__sync_or_and_fetch_1:
1461 case Builtin::BI__sync_or_and_fetch_2:
1462 case Builtin::BI__sync_or_and_fetch_4:
1463 case Builtin::BI__sync_or_and_fetch_8:
1464 case Builtin::BI__sync_or_and_fetch_16:
1465 BuiltinIndex = 8;
1466 break;
1467
1468 case Builtin::BI__sync_xor_and_fetch:
1469 case Builtin::BI__sync_xor_and_fetch_1:
1470 case Builtin::BI__sync_xor_and_fetch_2:
1471 case Builtin::BI__sync_xor_and_fetch_4:
1472 case Builtin::BI__sync_xor_and_fetch_8:
1473 case Builtin::BI__sync_xor_and_fetch_16:
1474 BuiltinIndex = 9;
1475 break;
Mike Stump11289f42009-09-09 15:08:12 +00001476
Chris Lattnerdc046542009-05-08 06:58:22 +00001477 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001478 case Builtin::BI__sync_val_compare_and_swap_1:
1479 case Builtin::BI__sync_val_compare_and_swap_2:
1480 case Builtin::BI__sync_val_compare_and_swap_4:
1481 case Builtin::BI__sync_val_compare_and_swap_8:
1482 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001483 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +00001484 NumFixed = 2;
1485 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001486
Chris Lattnerdc046542009-05-08 06:58:22 +00001487 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001488 case Builtin::BI__sync_bool_compare_and_swap_1:
1489 case Builtin::BI__sync_bool_compare_and_swap_2:
1490 case Builtin::BI__sync_bool_compare_and_swap_4:
1491 case Builtin::BI__sync_bool_compare_and_swap_8:
1492 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001493 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +00001494 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001495 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001496 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001497
1498 case Builtin::BI__sync_lock_test_and_set:
1499 case Builtin::BI__sync_lock_test_and_set_1:
1500 case Builtin::BI__sync_lock_test_and_set_2:
1501 case Builtin::BI__sync_lock_test_and_set_4:
1502 case Builtin::BI__sync_lock_test_and_set_8:
1503 case Builtin::BI__sync_lock_test_and_set_16:
1504 BuiltinIndex = 12;
1505 break;
1506
Chris Lattnerdc046542009-05-08 06:58:22 +00001507 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001508 case Builtin::BI__sync_lock_release_1:
1509 case Builtin::BI__sync_lock_release_2:
1510 case Builtin::BI__sync_lock_release_4:
1511 case Builtin::BI__sync_lock_release_8:
1512 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001513 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001514 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001515 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001516 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001517
1518 case Builtin::BI__sync_swap:
1519 case Builtin::BI__sync_swap_1:
1520 case Builtin::BI__sync_swap_2:
1521 case Builtin::BI__sync_swap_4:
1522 case Builtin::BI__sync_swap_8:
1523 case Builtin::BI__sync_swap_16:
1524 BuiltinIndex = 14;
1525 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001526 }
Mike Stump11289f42009-09-09 15:08:12 +00001527
Chris Lattnerdc046542009-05-08 06:58:22 +00001528 // Now that we know how many fixed arguments we expect, first check that we
1529 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001530 if (TheCall->getNumArgs() < 1+NumFixed) {
1531 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1532 << 0 << 1+NumFixed << TheCall->getNumArgs()
1533 << TheCall->getCallee()->getSourceRange();
1534 return ExprError();
1535 }
Mike Stump11289f42009-09-09 15:08:12 +00001536
Chris Lattner5b9241b2009-05-08 15:36:58 +00001537 // Get the decl for the concrete builtin from this, we can tell what the
1538 // concrete integer type we should convert to is.
1539 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1540 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001541 FunctionDecl *NewBuiltinDecl;
1542 if (NewBuiltinID == BuiltinID)
1543 NewBuiltinDecl = FDecl;
1544 else {
1545 // Perform builtin lookup to avoid redeclaring it.
1546 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1547 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1548 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1549 assert(Res.getFoundDecl());
1550 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1551 if (NewBuiltinDecl == 0)
1552 return ExprError();
1553 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001554
John McCallcf142162010-08-07 06:22:56 +00001555 // The first argument --- the pointer --- has a fixed type; we
1556 // deduce the types of the rest of the arguments accordingly. Walk
1557 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001558 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001559 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001560
Chris Lattnerdc046542009-05-08 06:58:22 +00001561 // GCC does an implicit conversion to the pointer or integer ValType. This
1562 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001563 // Initialize the argument.
1564 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1565 ValType, /*consume*/ false);
1566 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001567 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001568 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001569
Chris Lattnerdc046542009-05-08 06:58:22 +00001570 // Okay, we have something that *can* be converted to the right type. Check
1571 // to see if there is a potentially weird extension going on here. This can
1572 // happen when you do an atomic operation on something like an char* and
1573 // pass in 42. The 42 gets converted to char. This is even more strange
1574 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001575 // FIXME: Do this check.
John McCallb50451a2011-10-05 07:41:44 +00001576 TheCall->setArg(i+1, Arg.take());
Chris Lattnerdc046542009-05-08 06:58:22 +00001577 }
Mike Stump11289f42009-09-09 15:08:12 +00001578
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001579 ASTContext& Context = this->getASTContext();
1580
1581 // Create a new DeclRefExpr to refer to the new decl.
1582 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1583 Context,
1584 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001585 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001586 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001587 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001588 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001589 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001590 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001591
Chris Lattnerdc046542009-05-08 06:58:22 +00001592 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001593 // FIXME: This loses syntactic information.
1594 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1595 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1596 CK_BuiltinFnToFnPtr);
John Wiegley01296292011-04-08 18:41:53 +00001597 TheCall->setCallee(PromotedCall.take());
Mike Stump11289f42009-09-09 15:08:12 +00001598
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001599 // Change the result type of the call to match the original value type. This
1600 // is arbitrary, but the codegen for these builtins ins design to handle it
1601 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001602 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001603
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001604 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001605}
1606
Chris Lattner6436fb62009-02-18 06:01:06 +00001607/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001608/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001609/// Note: It might also make sense to do the UTF-16 conversion here (would
1610/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001611bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001612 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001613 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1614
Douglas Gregorfb65e592011-07-27 05:40:30 +00001615 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001616 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1617 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001618 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001619 }
Mike Stump11289f42009-09-09 15:08:12 +00001620
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001621 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001622 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001623 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001624 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001625 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001626 UTF16 *ToPtr = &ToBuf[0];
1627
1628 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1629 &ToPtr, ToPtr + NumBytes,
1630 strictConversion);
1631 // Check for conversion failure.
1632 if (Result != conversionOK)
1633 Diag(Arg->getLocStart(),
1634 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1635 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001636 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001637}
1638
Chris Lattnere202e6a2007-12-20 00:05:45 +00001639/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1640/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001641bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1642 Expr *Fn = TheCall->getCallee();
1643 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001644 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001645 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001646 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1647 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001648 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001649 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001650 return true;
1651 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001652
1653 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001654 return Diag(TheCall->getLocEnd(),
1655 diag::err_typecheck_call_too_few_args_at_least)
1656 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001657 }
1658
John McCall29ad95b2011-08-27 01:09:30 +00001659 // Type-check the first argument normally.
1660 if (checkBuiltinArgument(*this, TheCall, 0))
1661 return true;
1662
Chris Lattnere202e6a2007-12-20 00:05:45 +00001663 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001664 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001665 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001666 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001667 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001668 else if (FunctionDecl *FD = getCurFunctionDecl())
1669 isVariadic = FD->isVariadic();
1670 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001671 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001672
Chris Lattnere202e6a2007-12-20 00:05:45 +00001673 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001674 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1675 return true;
1676 }
Mike Stump11289f42009-09-09 15:08:12 +00001677
Chris Lattner43be2e62007-12-19 23:59:04 +00001678 // Verify that the second argument to the builtin is the last argument of the
1679 // current function or method.
1680 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001681 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001682
Nico Weber9eea7642013-05-24 23:31:57 +00001683 // These are valid if SecondArgIsLastNamedArgument is false after the next
1684 // block.
1685 QualType Type;
1686 SourceLocation ParamLoc;
1687
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001688 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1689 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001690 // FIXME: This isn't correct for methods (results in bogus warning).
1691 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001692 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001693 if (CurBlock)
1694 LastArg = *(CurBlock->TheDecl->param_end()-1);
1695 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001696 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001697 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001698 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001699 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00001700
1701 Type = PV->getType();
1702 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00001703 }
1704 }
Mike Stump11289f42009-09-09 15:08:12 +00001705
Chris Lattner43be2e62007-12-19 23:59:04 +00001706 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001707 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001708 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00001709 else if (Type->isReferenceType()) {
1710 Diag(Arg->getLocStart(),
1711 diag::warn_va_start_of_reference_type_is_undefined);
1712 Diag(ParamLoc, diag::note_parameter_type) << Type;
1713 }
1714
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00001715 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00001716 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001717}
Chris Lattner43be2e62007-12-19 23:59:04 +00001718
Chris Lattner2da14fb2007-12-20 00:26:33 +00001719/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1720/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001721bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1722 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001723 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001724 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001725 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001726 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001727 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001728 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001729 << SourceRange(TheCall->getArg(2)->getLocStart(),
1730 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001731
John Wiegley01296292011-04-08 18:41:53 +00001732 ExprResult OrigArg0 = TheCall->getArg(0);
1733 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001734
Chris Lattner2da14fb2007-12-20 00:26:33 +00001735 // Do standard promotions between the two arguments, returning their common
1736 // type.
Chris Lattner08464942007-12-28 05:29:59 +00001737 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00001738 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1739 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00001740
1741 // Make sure any conversions are pushed back into the call; this is
1742 // type safe since unordered compare builtins are declared as "_Bool
1743 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00001744 TheCall->setArg(0, OrigArg0.get());
1745 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00001746
John Wiegley01296292011-04-08 18:41:53 +00001747 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00001748 return false;
1749
Chris Lattner2da14fb2007-12-20 00:26:33 +00001750 // If the common type isn't a real floating type, then the arguments were
1751 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001752 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00001753 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001754 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00001755 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1756 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001757
Chris Lattner2da14fb2007-12-20 00:26:33 +00001758 return false;
1759}
1760
Benjamin Kramer634fc102010-02-15 22:42:31 +00001761/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1762/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001763/// to check everything. We expect the last argument to be a floating point
1764/// value.
1765bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1766 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001767 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001768 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001769 if (TheCall->getNumArgs() > NumArgs)
1770 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001771 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001772 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001773 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001774 (*(TheCall->arg_end()-1))->getLocEnd());
1775
Benjamin Kramer64aae502010-02-16 10:07:31 +00001776 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00001777
Eli Friedman7e4faac2009-08-31 20:06:00 +00001778 if (OrigArg->isTypeDependent())
1779 return false;
1780
Chris Lattner68784ef2010-05-06 05:50:07 +00001781 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00001782 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00001783 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001784 diag::err_typecheck_call_invalid_unary_fp)
1785 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001786
Chris Lattner68784ef2010-05-06 05:50:07 +00001787 // If this is an implicit conversion from float -> double, remove it.
1788 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1789 Expr *CastArg = Cast->getSubExpr();
1790 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1791 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1792 "promotion from float to double is the only expected cast here");
1793 Cast->setSubExpr(0);
Chris Lattner68784ef2010-05-06 05:50:07 +00001794 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00001795 }
1796 }
1797
Eli Friedman7e4faac2009-08-31 20:06:00 +00001798 return false;
1799}
1800
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001801/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1802// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00001803ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00001804 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001805 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00001806 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00001807 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1808 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001809
Nate Begemana0110022010-06-08 00:16:34 +00001810 // Determine which of the following types of shufflevector we're checking:
1811 // 1) unary, vector mask: (lhs, mask)
1812 // 2) binary, vector mask: (lhs, rhs, mask)
1813 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1814 QualType resType = TheCall->getArg(0)->getType();
1815 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00001816
Douglas Gregorc25f7662009-05-19 22:10:17 +00001817 if (!TheCall->getArg(0)->isTypeDependent() &&
1818 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00001819 QualType LHSType = TheCall->getArg(0)->getType();
1820 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00001821
Craig Topperbaca3892013-07-29 06:47:04 +00001822 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1823 return ExprError(Diag(TheCall->getLocStart(),
1824 diag::err_shufflevector_non_vector)
1825 << SourceRange(TheCall->getArg(0)->getLocStart(),
1826 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001827
Nate Begemana0110022010-06-08 00:16:34 +00001828 numElements = LHSType->getAs<VectorType>()->getNumElements();
1829 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00001830
Nate Begemana0110022010-06-08 00:16:34 +00001831 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1832 // with mask. If so, verify that RHS is an integer vector type with the
1833 // same number of elts as lhs.
1834 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00001835 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00001836 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00001837 return ExprError(Diag(TheCall->getLocStart(),
1838 diag::err_shufflevector_incompatible_vector)
1839 << SourceRange(TheCall->getArg(1)->getLocStart(),
1840 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001841 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00001842 return ExprError(Diag(TheCall->getLocStart(),
1843 diag::err_shufflevector_incompatible_vector)
1844 << SourceRange(TheCall->getArg(0)->getLocStart(),
1845 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00001846 } else if (numElements != numResElements) {
1847 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00001848 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001849 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001850 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001851 }
1852
1853 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001854 if (TheCall->getArg(i)->isTypeDependent() ||
1855 TheCall->getArg(i)->isValueDependent())
1856 continue;
1857
Nate Begemana0110022010-06-08 00:16:34 +00001858 llvm::APSInt Result(32);
1859 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1860 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001861 diag::err_shufflevector_nonconstant_argument)
1862 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001863
Craig Topper50ad5b72013-08-03 17:40:38 +00001864 // Allow -1 which will be translated to undef in the IR.
1865 if (Result.isSigned() && Result.isAllOnesValue())
1866 continue;
1867
Chris Lattner7ab824e2008-08-10 02:05:13 +00001868 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001869 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001870 diag::err_shufflevector_argument_too_large)
1871 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001872 }
1873
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001874 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001875
Chris Lattner7ab824e2008-08-10 02:05:13 +00001876 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001877 exprs.push_back(TheCall->getArg(i));
1878 TheCall->setArg(i, 0);
1879 }
1880
Benjamin Kramerc215e762012-08-24 11:54:20 +00001881 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek5a201952009-02-07 01:47:29 +00001882 TheCall->getCallee()->getLocStart(),
1883 TheCall->getRParenLoc()));
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001884}
Chris Lattner43be2e62007-12-19 23:59:04 +00001885
Hal Finkelc4d7c822013-09-18 03:29:45 +00001886/// SemaConvertVectorExpr - Handle __builtin_convertvector
1887ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1888 SourceLocation BuiltinLoc,
1889 SourceLocation RParenLoc) {
1890 ExprValueKind VK = VK_RValue;
1891 ExprObjectKind OK = OK_Ordinary;
1892 QualType DstTy = TInfo->getType();
1893 QualType SrcTy = E->getType();
1894
1895 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1896 return ExprError(Diag(BuiltinLoc,
1897 diag::err_convertvector_non_vector)
1898 << E->getSourceRange());
1899 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1900 return ExprError(Diag(BuiltinLoc,
1901 diag::err_convertvector_non_vector_type));
1902
1903 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1904 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1905 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1906 if (SrcElts != DstElts)
1907 return ExprError(Diag(BuiltinLoc,
1908 diag::err_convertvector_incompatible_vector)
1909 << E->getSourceRange());
1910 }
1911
1912 return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
1913 BuiltinLoc, RParenLoc));
1914
1915}
1916
Daniel Dunbarb7257262008-07-21 22:59:13 +00001917/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1918// This is declared to take (const void*, ...) and can take two
1919// optional constant int args.
1920bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00001921 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001922
Chris Lattner3b054132008-11-19 05:08:23 +00001923 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001924 return Diag(TheCall->getLocEnd(),
1925 diag::err_typecheck_call_too_many_args_at_most)
1926 << 0 /*function call*/ << 3 << NumArgs
1927 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001928
1929 // Argument 0 is checked for us and the remaining arguments must be
1930 // constant integers.
Chris Lattner3b054132008-11-19 05:08:23 +00001931 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbarb7257262008-07-21 22:59:13 +00001932 Expr *Arg = TheCall->getArg(i);
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001933
1934 // We can't check the value of a dependent argument.
1935 if (Arg->isTypeDependent() || Arg->isValueDependent())
1936 continue;
1937
Eli Friedman5efba262009-12-04 00:30:06 +00001938 llvm::APSInt Result;
Eric Christopher8d0c6212010-04-17 02:26:23 +00001939 if (SemaBuiltinConstantArg(TheCall, i, Result))
1940 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001941
Daniel Dunbarb7257262008-07-21 22:59:13 +00001942 // FIXME: gcc issues a warning and rewrites these to 0. These
1943 // seems especially odd for the third argument since the default
1944 // is 3.
Chris Lattner3b054132008-11-19 05:08:23 +00001945 if (i == 1) {
Eli Friedman5efba262009-12-04 00:30:06 +00001946 if (Result.getLimitedValue() > 1)
Chris Lattner3b054132008-11-19 05:08:23 +00001947 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001948 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001949 } else {
Eli Friedman5efba262009-12-04 00:30:06 +00001950 if (Result.getLimitedValue() > 3)
Chris Lattner3b054132008-11-19 05:08:23 +00001951 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001952 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001953 }
1954 }
1955
Chris Lattner3b054132008-11-19 05:08:23 +00001956 return false;
Daniel Dunbarb7257262008-07-21 22:59:13 +00001957}
1958
Eric Christopher8d0c6212010-04-17 02:26:23 +00001959/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1960/// TheCall is a constant expression.
1961bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1962 llvm::APSInt &Result) {
1963 Expr *Arg = TheCall->getArg(ArgNum);
1964 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1965 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1966
1967 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1968
1969 if (!Arg->isIntegerConstantExpr(Result, Context))
1970 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00001971 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00001972
Chris Lattnerd545ad12009-09-23 06:06:36 +00001973 return false;
1974}
1975
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001976/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1977/// int type). This simply type checks that type is one of the defined
1978/// constants (0-3).
Chris Lattner57540c52011-04-15 05:22:18 +00001979// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001980bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00001981 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001982
1983 // We can't check the value of a dependent argument.
1984 if (TheCall->getArg(1)->isTypeDependent() ||
1985 TheCall->getArg(1)->isValueDependent())
1986 return false;
1987
Eric Christopher8d0c6212010-04-17 02:26:23 +00001988 // Check constant-ness first.
1989 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1990 return true;
1991
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001992 Expr *Arg = TheCall->getArg(1);
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001993 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattner3b054132008-11-19 05:08:23 +00001994 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1995 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001996 }
1997
1998 return false;
1999}
2000
Eli Friedmanc97d0142009-05-03 06:04:26 +00002001/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002002/// This checks that val is a constant 1.
2003bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2004 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002005 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002006
Eric Christopher8d0c6212010-04-17 02:26:23 +00002007 // TODO: This is less than ideal. Overload this to take a value.
2008 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2009 return true;
2010
2011 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002012 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2013 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2014
2015 return false;
2016}
2017
Richard Smithd7293d72013-08-05 18:49:43 +00002018namespace {
2019enum StringLiteralCheckType {
2020 SLCT_NotALiteral,
2021 SLCT_UncheckedLiteral,
2022 SLCT_CheckedLiteral
2023};
2024}
2025
Richard Smith55ce3522012-06-25 20:30:08 +00002026// Determine if an expression is a string literal or constant string.
2027// If this function returns false on the arguments to a function expecting a
2028// format string, we will usually need to emit a warning.
2029// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002030static StringLiteralCheckType
2031checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2032 bool HasVAListArg, unsigned format_idx,
2033 unsigned firstDataArg, Sema::FormatStringType Type,
2034 Sema::VariadicCallType CallType, bool InFunctionCall,
2035 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002036 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002037 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002038 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002039
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002040 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002041
Richard Smithd7293d72013-08-05 18:49:43 +00002042 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002043 // Technically -Wformat-nonliteral does not warn about this case.
2044 // The behavior of printf and friends in this case is implementation
2045 // dependent. Ideally if the format string cannot be null then
2046 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002047 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002048
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002049 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002050 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002051 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002052 // The expression is a literal if both sub-expressions were, and it was
2053 // completely checked only if both sub-expressions were checked.
2054 const AbstractConditionalOperator *C =
2055 cast<AbstractConditionalOperator>(E);
2056 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002057 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002058 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002059 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002060 if (Left == SLCT_NotALiteral)
2061 return SLCT_NotALiteral;
2062 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002063 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002064 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002065 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002066 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002067 }
2068
2069 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002070 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2071 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002072 }
2073
John McCallc07a0c72011-02-17 10:25:35 +00002074 case Stmt::OpaqueValueExprClass:
2075 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2076 E = src;
2077 goto tryAgain;
2078 }
Richard Smith55ce3522012-06-25 20:30:08 +00002079 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002080
Ted Kremeneka8890832011-02-24 23:03:04 +00002081 case Stmt::PredefinedExprClass:
2082 // While __func__, etc., are technically not string literals, they
2083 // cannot contain format specifiers and thus are not a security
2084 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002085 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002086
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002087 case Stmt::DeclRefExprClass: {
2088 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002089
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002090 // As an exception, do not flag errors for variables binding to
2091 // const string literals.
2092 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2093 bool isConstant = false;
2094 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002095
Richard Smithd7293d72013-08-05 18:49:43 +00002096 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2097 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002098 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002099 isConstant = T.isConstant(S.Context) &&
2100 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002101 } else if (T->isObjCObjectPointerType()) {
2102 // In ObjC, there is usually no "const ObjectPointer" type,
2103 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002104 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002105 }
Mike Stump11289f42009-09-09 15:08:12 +00002106
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002107 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002108 if (const Expr *Init = VD->getAnyInitializer()) {
2109 // Look through initializers like const char c[] = { "foo" }
2110 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2111 if (InitList->isStringLiteralInit())
2112 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2113 }
Richard Smithd7293d72013-08-05 18:49:43 +00002114 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002115 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002116 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002117 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002118 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002119 }
Mike Stump11289f42009-09-09 15:08:12 +00002120
Anders Carlssonb012ca92009-06-28 19:55:58 +00002121 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2122 // special check to see if the format string is a function parameter
2123 // of the function calling the printf function. If the function
2124 // has an attribute indicating it is a printf-like function, then we
2125 // should suppress warnings concerning non-literals being used in a call
2126 // to a vprintf function. For example:
2127 //
2128 // void
2129 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2130 // va_list ap;
2131 // va_start(ap, fmt);
2132 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2133 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002134 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002135 if (HasVAListArg) {
2136 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2137 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2138 int PVIndex = PV->getFunctionScopeIndex() + 1;
2139 for (specific_attr_iterator<FormatAttr>
2140 i = ND->specific_attr_begin<FormatAttr>(),
2141 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
2142 FormatAttr *PVFormat = *i;
2143 // adjust for implicit parameter
2144 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2145 if (MD->isInstance())
2146 ++PVIndex;
2147 // We also check if the formats are compatible.
2148 // We can't pass a 'scanf' string to a 'printf' function.
2149 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002150 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002151 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002152 }
2153 }
2154 }
2155 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002156 }
Mike Stump11289f42009-09-09 15:08:12 +00002157
Richard Smith55ce3522012-06-25 20:30:08 +00002158 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002159 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002160
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002161 case Stmt::CallExprClass:
2162 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002163 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002164 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2165 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2166 unsigned ArgIndex = FA->getFormatIdx();
2167 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2168 if (MD->isInstance())
2169 --ArgIndex;
2170 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002171
Richard Smithd7293d72013-08-05 18:49:43 +00002172 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002173 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002174 Type, CallType, InFunctionCall,
2175 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002176 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2177 unsigned BuiltinID = FD->getBuiltinID();
2178 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2179 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2180 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002181 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002182 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002183 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002184 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002185 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002186 }
2187 }
Mike Stump11289f42009-09-09 15:08:12 +00002188
Richard Smith55ce3522012-06-25 20:30:08 +00002189 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002190 }
Fariborz Jahanian4ba4a5b2013-10-18 21:20:34 +00002191
2192 case Stmt::ObjCMessageExprClass: {
2193 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(E);
2194 if (const ObjCMethodDecl *MDecl = ME->getMethodDecl()) {
2195 if (const NamedDecl *ND = dyn_cast<NamedDecl>(MDecl)) {
2196 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2197 unsigned ArgIndex = FA->getFormatIdx();
2198 if (ArgIndex <= ME->getNumArgs()) {
2199 const Expr *Arg = ME->getArg(ArgIndex-1);
2200 return checkFormatStringExpr(S, Arg, Args,
2201 HasVAListArg, format_idx,
2202 firstDataArg, Type, CallType,
2203 InFunctionCall, CheckedVarArgs);
2204 }
2205 }
2206 }
2207 }
2208
2209 return SLCT_NotALiteral;
2210 }
2211
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002212 case Stmt::ObjCStringLiteralClass:
2213 case Stmt::StringLiteralClass: {
2214 const StringLiteral *StrE = NULL;
Mike Stump11289f42009-09-09 15:08:12 +00002215
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002216 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002217 StrE = ObjCFExpr->getString();
2218 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002219 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002220
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002221 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002222 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2223 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002224 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002225 }
Mike Stump11289f42009-09-09 15:08:12 +00002226
Richard Smith55ce3522012-06-25 20:30:08 +00002227 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002228 }
Mike Stump11289f42009-09-09 15:08:12 +00002229
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002230 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002231 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002232 }
2233}
2234
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002235Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002236 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002237 .Case("scanf", FST_Scanf)
2238 .Cases("printf", "printf0", FST_Printf)
2239 .Cases("NSString", "CFString", FST_NSString)
2240 .Case("strftime", FST_Strftime)
2241 .Case("strfmon", FST_Strfmon)
2242 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2243 .Default(FST_Unknown);
2244}
2245
Jordan Rose3e0ec582012-07-19 18:10:23 +00002246/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002247/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002248/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002249bool Sema::CheckFormatArguments(const FormatAttr *Format,
2250 ArrayRef<const Expr *> Args,
2251 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002252 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002253 SourceLocation Loc, SourceRange Range,
2254 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002255 FormatStringInfo FSI;
2256 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002257 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002258 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002259 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002260 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002261}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002262
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002263bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002264 bool HasVAListArg, unsigned format_idx,
2265 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002266 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002267 SourceLocation Loc, SourceRange Range,
2268 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002269 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002270 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002271 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002272 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002273 }
Mike Stump11289f42009-09-09 15:08:12 +00002274
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002275 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002276
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002277 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002278 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002279 // Dynamically generated format strings are difficult to
2280 // automatically vet at compile time. Requiring that format strings
2281 // are string literals: (1) permits the checking of format strings by
2282 // the compiler and thereby (2) can practically remove the source of
2283 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002284
Mike Stump11289f42009-09-09 15:08:12 +00002285 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002286 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002287 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002288 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002289 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002290 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2291 format_idx, firstDataArg, Type, CallType,
2292 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002293 if (CT != SLCT_NotALiteral)
2294 // Literal format string found, check done!
2295 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002296
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002297 // Strftime is particular as it always uses a single 'time' argument,
2298 // so it is safe to pass a non-literal string.
2299 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002300 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002301
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002302 // Do not emit diag when the string param is a macro expansion and the
2303 // format is either NSString or CFString. This is a hack to prevent
2304 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2305 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002306 if (Type == FST_NSString &&
2307 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002308 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002309
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002310 // If there are no arguments specified, warn with -Wformat-security, otherwise
2311 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002312 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002313 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002314 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002315 << OrigFormatExpr->getSourceRange();
2316 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002317 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002318 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002319 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002320 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002321}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002322
Ted Kremenekab278de2010-01-28 23:39:18 +00002323namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002324class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2325protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002326 Sema &S;
2327 const StringLiteral *FExpr;
2328 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002329 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002330 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002331 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002332 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002333 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002334 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002335 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002336 bool usesPositionalArgs;
2337 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002338 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002339 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002340 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002341public:
Ted Kremenek02087932010-07-16 02:11:22 +00002342 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002343 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002344 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002345 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002346 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002347 Sema::VariadicCallType callType,
2348 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002349 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002350 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2351 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002352 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002353 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002354 inFunctionCall(inFunctionCall), CallType(callType),
2355 CheckedVarArgs(CheckedVarArgs) {
2356 CoveredArgs.resize(numDataArgs);
2357 CoveredArgs.reset();
2358 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002359
Ted Kremenek019d2242010-01-29 01:50:07 +00002360 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002361
Ted Kremenek02087932010-07-16 02:11:22 +00002362 void HandleIncompleteSpecifier(const char *startSpecifier,
2363 unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002364
Jordan Rose92303592012-09-08 04:00:03 +00002365 void HandleInvalidLengthModifier(
2366 const analyze_format_string::FormatSpecifier &FS,
2367 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002368 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002369
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002370 void HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002371 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002372 const char *startSpecifier, unsigned specifierLen);
2373
2374 void HandleNonStandardConversionSpecifier(
2375 const analyze_format_string::ConversionSpecifier &CS,
2376 const char *startSpecifier, unsigned specifierLen);
2377
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002378 virtual void HandlePosition(const char *startPos, unsigned posLen);
2379
Ted Kremenekd1668192010-02-27 01:41:03 +00002380 virtual void HandleInvalidPosition(const char *startSpecifier,
2381 unsigned specifierLen,
Ted Kremenek02087932010-07-16 02:11:22 +00002382 analyze_format_string::PositionContext p);
Ted Kremenekd1668192010-02-27 01:41:03 +00002383
2384 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2385
Ted Kremenekab278de2010-01-28 23:39:18 +00002386 void HandleNullChar(const char *nullCharacter);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002387
Richard Trieu03cf7b72011-10-28 00:41:25 +00002388 template <typename Range>
2389 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2390 const Expr *ArgumentExpr,
2391 PartialDiagnostic PDiag,
2392 SourceLocation StringLoc,
2393 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002394 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002395
Ted Kremenek02087932010-07-16 02:11:22 +00002396protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002397 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2398 const char *startSpec,
2399 unsigned specifierLen,
2400 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002401
2402 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2403 const char *startSpec,
2404 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002405
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002406 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002407 CharSourceRange getSpecifierRange(const char *startSpecifier,
2408 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002409 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002410
Ted Kremenek5739de72010-01-29 01:06:55 +00002411 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002412
2413 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2414 const analyze_format_string::ConversionSpecifier &CS,
2415 const char *startSpecifier, unsigned specifierLen,
2416 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002417
2418 template <typename Range>
2419 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2420 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002421 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002422
2423 void CheckPositionalAndNonpositionalArgs(
2424 const analyze_format_string::FormatSpecifier *FS);
Ted Kremenekab278de2010-01-28 23:39:18 +00002425};
2426}
2427
Ted Kremenek02087932010-07-16 02:11:22 +00002428SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002429 return OrigFormatExpr->getSourceRange();
2430}
2431
Ted Kremenek02087932010-07-16 02:11:22 +00002432CharSourceRange CheckFormatHandler::
2433getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002434 SourceLocation Start = getLocationOfByte(startSpecifier);
2435 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2436
2437 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002438 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002439
2440 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002441}
2442
Ted Kremenek02087932010-07-16 02:11:22 +00002443SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002444 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002445}
2446
Ted Kremenek02087932010-07-16 02:11:22 +00002447void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2448 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002449 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2450 getLocationOfByte(startSpecifier),
2451 /*IsStringLocation*/true,
2452 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002453}
2454
Jordan Rose92303592012-09-08 04:00:03 +00002455void CheckFormatHandler::HandleInvalidLengthModifier(
2456 const analyze_format_string::FormatSpecifier &FS,
2457 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002458 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002459 using namespace analyze_format_string;
2460
2461 const LengthModifier &LM = FS.getLengthModifier();
2462 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2463
2464 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002465 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002466 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002467 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002468 getLocationOfByte(LM.getStart()),
2469 /*IsStringLocation*/true,
2470 getSpecifierRange(startSpecifier, specifierLen));
2471
2472 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2473 << FixedLM->toString()
2474 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2475
2476 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002477 FixItHint Hint;
2478 if (DiagID == diag::warn_format_nonsensical_length)
2479 Hint = FixItHint::CreateRemoval(LMRange);
2480
2481 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002482 getLocationOfByte(LM.getStart()),
2483 /*IsStringLocation*/true,
2484 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002485 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002486 }
2487}
2488
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002489void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002490 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002491 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002492 using namespace analyze_format_string;
2493
2494 const LengthModifier &LM = FS.getLengthModifier();
2495 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2496
2497 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002498 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002499 if (FixedLM) {
2500 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2501 << LM.toString() << 0,
2502 getLocationOfByte(LM.getStart()),
2503 /*IsStringLocation*/true,
2504 getSpecifierRange(startSpecifier, specifierLen));
2505
2506 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2507 << FixedLM->toString()
2508 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2509
2510 } else {
2511 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2512 << LM.toString() << 0,
2513 getLocationOfByte(LM.getStart()),
2514 /*IsStringLocation*/true,
2515 getSpecifierRange(startSpecifier, specifierLen));
2516 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002517}
2518
2519void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2520 const analyze_format_string::ConversionSpecifier &CS,
2521 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002522 using namespace analyze_format_string;
2523
2524 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002525 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002526 if (FixedCS) {
2527 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2528 << CS.toString() << /*conversion specifier*/1,
2529 getLocationOfByte(CS.getStart()),
2530 /*IsStringLocation*/true,
2531 getSpecifierRange(startSpecifier, specifierLen));
2532
2533 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2534 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2535 << FixedCS->toString()
2536 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2537 } else {
2538 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2539 << CS.toString() << /*conversion specifier*/1,
2540 getLocationOfByte(CS.getStart()),
2541 /*IsStringLocation*/true,
2542 getSpecifierRange(startSpecifier, specifierLen));
2543 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002544}
2545
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002546void CheckFormatHandler::HandlePosition(const char *startPos,
2547 unsigned posLen) {
2548 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2549 getLocationOfByte(startPos),
2550 /*IsStringLocation*/true,
2551 getSpecifierRange(startPos, posLen));
2552}
2553
Ted Kremenekd1668192010-02-27 01:41:03 +00002554void
Ted Kremenek02087932010-07-16 02:11:22 +00002555CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2556 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002557 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2558 << (unsigned) p,
2559 getLocationOfByte(startPos), /*IsStringLocation*/true,
2560 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002561}
2562
Ted Kremenek02087932010-07-16 02:11:22 +00002563void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002564 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002565 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2566 getLocationOfByte(startPos),
2567 /*IsStringLocation*/true,
2568 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002569}
2570
Ted Kremenek02087932010-07-16 02:11:22 +00002571void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002572 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002573 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002574 EmitFormatDiagnostic(
2575 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2576 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2577 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002578 }
Ted Kremenek02087932010-07-16 02:11:22 +00002579}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002580
Jordan Rose58bbe422012-07-19 18:10:08 +00002581// Note that this may return NULL if there was an error parsing or building
2582// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002583const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002584 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002585}
2586
2587void CheckFormatHandler::DoneProcessing() {
2588 // Does the number of data arguments exceed the number of
2589 // format conversions in the format string?
2590 if (!HasVAListArg) {
2591 // Find any arguments that weren't covered.
2592 CoveredArgs.flip();
2593 signed notCoveredArg = CoveredArgs.find_first();
2594 if (notCoveredArg >= 0) {
2595 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002596 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2597 SourceLocation Loc = E->getLocStart();
2598 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2599 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2600 Loc, /*IsStringLocation*/false,
2601 getFormatStringRange());
2602 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002603 }
Ted Kremenek02087932010-07-16 02:11:22 +00002604 }
2605 }
2606}
2607
Ted Kremenekce815422010-07-19 21:25:57 +00002608bool
2609CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2610 SourceLocation Loc,
2611 const char *startSpec,
2612 unsigned specifierLen,
2613 const char *csStart,
2614 unsigned csLen) {
2615
2616 bool keepGoing = true;
2617 if (argIndex < NumDataArgs) {
2618 // Consider the argument coverered, even though the specifier doesn't
2619 // make sense.
2620 CoveredArgs.set(argIndex);
2621 }
2622 else {
2623 // If argIndex exceeds the number of data arguments we
2624 // don't issue a warning because that is just a cascade of warnings (and
2625 // they may have intended '%%' anyway). We don't want to continue processing
2626 // the format string after this point, however, as we will like just get
2627 // gibberish when trying to match arguments.
2628 keepGoing = false;
2629 }
2630
Richard Trieu03cf7b72011-10-28 00:41:25 +00002631 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2632 << StringRef(csStart, csLen),
2633 Loc, /*IsStringLocation*/true,
2634 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00002635
2636 return keepGoing;
2637}
2638
Richard Trieu03cf7b72011-10-28 00:41:25 +00002639void
2640CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2641 const char *startSpec,
2642 unsigned specifierLen) {
2643 EmitFormatDiagnostic(
2644 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2645 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2646}
2647
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002648bool
2649CheckFormatHandler::CheckNumArgs(
2650 const analyze_format_string::FormatSpecifier &FS,
2651 const analyze_format_string::ConversionSpecifier &CS,
2652 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2653
2654 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002655 PartialDiagnostic PDiag = FS.usesPositionalArg()
2656 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2657 << (argIndex+1) << NumDataArgs)
2658 : S.PDiag(diag::warn_printf_insufficient_data_args);
2659 EmitFormatDiagnostic(
2660 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2661 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002662 return false;
2663 }
2664 return true;
2665}
2666
Richard Trieu03cf7b72011-10-28 00:41:25 +00002667template<typename Range>
2668void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2669 SourceLocation Loc,
2670 bool IsStringLocation,
2671 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002672 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002673 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002674 Loc, IsStringLocation, StringRange, FixIt);
2675}
2676
2677/// \brief If the format string is not within the funcion call, emit a note
2678/// so that the function call and string are in diagnostic messages.
2679///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002680/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00002681/// call and only one diagnostic message will be produced. Otherwise, an
2682/// extra note will be emitted pointing to location of the format string.
2683///
2684/// \param ArgumentExpr the expression that is passed as the format string
2685/// argument in the function call. Used for getting locations when two
2686/// diagnostics are emitted.
2687///
2688/// \param PDiag the callee should already have provided any strings for the
2689/// diagnostic message. This function only adds locations and fixits
2690/// to diagnostics.
2691///
2692/// \param Loc primary location for diagnostic. If two diagnostics are
2693/// required, one will be at Loc and a new SourceLocation will be created for
2694/// the other one.
2695///
2696/// \param IsStringLocation if true, Loc points to the format string should be
2697/// used for the note. Otherwise, Loc points to the argument list and will
2698/// be used with PDiag.
2699///
2700/// \param StringRange some or all of the string to highlight. This is
2701/// templated so it can accept either a CharSourceRange or a SourceRange.
2702///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002703/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002704template<typename Range>
2705void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2706 const Expr *ArgumentExpr,
2707 PartialDiagnostic PDiag,
2708 SourceLocation Loc,
2709 bool IsStringLocation,
2710 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002711 ArrayRef<FixItHint> FixIt) {
2712 if (InFunctionCall) {
2713 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2714 D << StringRange;
2715 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2716 I != E; ++I) {
2717 D << *I;
2718 }
2719 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002720 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2721 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00002722
2723 const Sema::SemaDiagnosticBuilder &Note =
2724 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2725 diag::note_format_string_defined);
2726
2727 Note << StringRange;
2728 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2729 I != E; ++I) {
2730 Note << *I;
2731 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00002732 }
2733}
2734
Ted Kremenek02087932010-07-16 02:11:22 +00002735//===--- CHECK: Printf format string checking ------------------------------===//
2736
2737namespace {
2738class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002739 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00002740public:
2741 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2742 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002743 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00002744 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002745 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002746 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002747 Sema::VariadicCallType CallType,
2748 llvm::SmallBitVector &CheckedVarArgs)
2749 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2750 numDataArgs, beg, hasVAListArg, Args,
2751 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2752 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00002753 {}
2754
Ted Kremenek02087932010-07-16 02:11:22 +00002755
2756 bool HandleInvalidPrintfConversionSpecifier(
2757 const analyze_printf::PrintfSpecifier &FS,
2758 const char *startSpecifier,
2759 unsigned specifierLen);
2760
2761 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2762 const char *startSpecifier,
2763 unsigned specifierLen);
Richard Smith55ce3522012-06-25 20:30:08 +00002764 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2765 const char *StartSpecifier,
2766 unsigned SpecifierLen,
2767 const Expr *E);
2768
Ted Kremenek02087932010-07-16 02:11:22 +00002769 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2770 const char *startSpecifier, unsigned specifierLen);
2771 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2772 const analyze_printf::OptionalAmount &Amt,
2773 unsigned type,
2774 const char *startSpecifier, unsigned specifierLen);
2775 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2776 const analyze_printf::OptionalFlag &flag,
2777 const char *startSpecifier, unsigned specifierLen);
2778 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2779 const analyze_printf::OptionalFlag &ignoredFlag,
2780 const analyze_printf::OptionalFlag &flag,
2781 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002782 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith55ce3522012-06-25 20:30:08 +00002783 const Expr *E, const CharSourceRange &CSR);
2784
Ted Kremenek02087932010-07-16 02:11:22 +00002785};
2786}
2787
2788bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2789 const analyze_printf::PrintfSpecifier &FS,
2790 const char *startSpecifier,
2791 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002792 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00002793 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00002794
Ted Kremenekce815422010-07-19 21:25:57 +00002795 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2796 getLocationOfByte(CS.getStart()),
2797 startSpecifier, specifierLen,
2798 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00002799}
2800
Ted Kremenek02087932010-07-16 02:11:22 +00002801bool CheckPrintfHandler::HandleAmount(
2802 const analyze_format_string::OptionalAmount &Amt,
2803 unsigned k, const char *startSpecifier,
2804 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002805
2806 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002807 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00002808 unsigned argIndex = Amt.getArgIndex();
2809 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002810 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2811 << k,
2812 getLocationOfByte(Amt.getStart()),
2813 /*IsStringLocation*/true,
2814 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002815 // Don't do any more checking. We will just emit
2816 // spurious errors.
2817 return false;
2818 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002819
Ted Kremenek5739de72010-01-29 01:06:55 +00002820 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00002821 // Although not in conformance with C99, we also allow the argument to be
2822 // an 'unsigned int' as that is a reasonably safe case. GCC also
2823 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00002824 CoveredArgs.set(argIndex);
2825 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00002826 if (!Arg)
2827 return false;
2828
Ted Kremenek5739de72010-01-29 01:06:55 +00002829 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002830
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002831 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2832 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002833
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002834 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002835 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002836 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00002837 << T << Arg->getSourceRange(),
2838 getLocationOfByte(Amt.getStart()),
2839 /*IsStringLocation*/true,
2840 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002841 // Don't do any more checking. We will just emit
2842 // spurious errors.
2843 return false;
2844 }
2845 }
2846 }
2847 return true;
2848}
Ted Kremenek5739de72010-01-29 01:06:55 +00002849
Tom Careb49ec692010-06-17 19:00:27 +00002850void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00002851 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002852 const analyze_printf::OptionalAmount &Amt,
2853 unsigned type,
2854 const char *startSpecifier,
2855 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002856 const analyze_printf::PrintfConversionSpecifier &CS =
2857 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00002858
Richard Trieu03cf7b72011-10-28 00:41:25 +00002859 FixItHint fixit =
2860 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2861 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2862 Amt.getConstantLength()))
2863 : FixItHint();
2864
2865 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2866 << type << CS.toString(),
2867 getLocationOfByte(Amt.getStart()),
2868 /*IsStringLocation*/true,
2869 getSpecifierRange(startSpecifier, specifierLen),
2870 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00002871}
2872
Ted Kremenek02087932010-07-16 02:11:22 +00002873void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002874 const analyze_printf::OptionalFlag &flag,
2875 const char *startSpecifier,
2876 unsigned specifierLen) {
2877 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002878 const analyze_printf::PrintfConversionSpecifier &CS =
2879 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00002880 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2881 << flag.toString() << CS.toString(),
2882 getLocationOfByte(flag.getPosition()),
2883 /*IsStringLocation*/true,
2884 getSpecifierRange(startSpecifier, specifierLen),
2885 FixItHint::CreateRemoval(
2886 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002887}
2888
2889void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00002890 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002891 const analyze_printf::OptionalFlag &ignoredFlag,
2892 const analyze_printf::OptionalFlag &flag,
2893 const char *startSpecifier,
2894 unsigned specifierLen) {
2895 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002896 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2897 << ignoredFlag.toString() << flag.toString(),
2898 getLocationOfByte(ignoredFlag.getPosition()),
2899 /*IsStringLocation*/true,
2900 getSpecifierRange(startSpecifier, specifierLen),
2901 FixItHint::CreateRemoval(
2902 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002903}
2904
Richard Smith55ce3522012-06-25 20:30:08 +00002905// Determines if the specified is a C++ class or struct containing
2906// a member with the specified name and kind (e.g. a CXXMethodDecl named
2907// "c_str()").
2908template<typename MemberKind>
2909static llvm::SmallPtrSet<MemberKind*, 1>
2910CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2911 const RecordType *RT = Ty->getAs<RecordType>();
2912 llvm::SmallPtrSet<MemberKind*, 1> Results;
2913
2914 if (!RT)
2915 return Results;
2916 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2917 if (!RD)
2918 return Results;
2919
2920 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2921 Sema::LookupMemberName);
2922
2923 // We just need to include all members of the right kind turned up by the
2924 // filter, at this point.
2925 if (S.LookupQualifiedName(R, RT->getDecl()))
2926 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2927 NamedDecl *decl = (*I)->getUnderlyingDecl();
2928 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2929 Results.insert(FK);
2930 }
2931 return Results;
2932}
2933
2934// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002935// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00002936// Returns true when a c_str() conversion method is found.
2937bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002938 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith55ce3522012-06-25 20:30:08 +00002939 const CharSourceRange &CSR) {
2940 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2941
2942 MethodSet Results =
2943 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2944
2945 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2946 MI != ME; ++MI) {
2947 const CXXMethodDecl *Method = *MI;
2948 if (Method->getNumParams() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00002949 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00002950 // FIXME: Suggest parens if the expression needs them.
2951 SourceLocation EndLoc =
2952 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2953 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2954 << "c_str()"
2955 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2956 return true;
2957 }
2958 }
2959
2960 return false;
2961}
2962
Ted Kremenekab278de2010-01-28 23:39:18 +00002963bool
Ted Kremenek02087932010-07-16 02:11:22 +00002964CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00002965 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00002966 const char *startSpecifier,
2967 unsigned specifierLen) {
2968
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002969 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00002970 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002971 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00002972
Ted Kremenek6cd69422010-07-19 22:01:06 +00002973 if (FS.consumesDataArgument()) {
2974 if (atFirstArg) {
2975 atFirstArg = false;
2976 usesPositionalArgs = FS.usesPositionalArg();
2977 }
2978 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002979 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2980 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00002981 return false;
2982 }
Ted Kremenek5739de72010-01-29 01:06:55 +00002983 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002984
Ted Kremenekd1668192010-02-27 01:41:03 +00002985 // First check if the field width, precision, and conversion specifier
2986 // have matching data arguments.
2987 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2988 startSpecifier, specifierLen)) {
2989 return false;
2990 }
2991
2992 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2993 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002994 return false;
2995 }
2996
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002997 if (!CS.consumesDataArgument()) {
2998 // FIXME: Technically specifying a precision or field width here
2999 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003000 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003001 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003002
Ted Kremenek4a49d982010-02-26 19:18:41 +00003003 // Consume the argument.
3004 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003005 if (argIndex < NumDataArgs) {
3006 // The check to see if the argIndex is valid will come later.
3007 // We set the bit here because we may exit early from this
3008 // function if we encounter some other error.
3009 CoveredArgs.set(argIndex);
3010 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003011
3012 // Check for using an Objective-C specific conversion specifier
3013 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003014 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003015 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3016 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003017 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003018
Tom Careb49ec692010-06-17 19:00:27 +00003019 // Check for invalid use of field width
3020 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003021 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003022 startSpecifier, specifierLen);
3023 }
3024
3025 // Check for invalid use of precision
3026 if (!FS.hasValidPrecision()) {
3027 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3028 startSpecifier, specifierLen);
3029 }
3030
3031 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003032 if (!FS.hasValidThousandsGroupingPrefix())
3033 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003034 if (!FS.hasValidLeadingZeros())
3035 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3036 if (!FS.hasValidPlusPrefix())
3037 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003038 if (!FS.hasValidSpacePrefix())
3039 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003040 if (!FS.hasValidAlternativeForm())
3041 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3042 if (!FS.hasValidLeftJustified())
3043 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3044
3045 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003046 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3047 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3048 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003049 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3050 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3051 startSpecifier, specifierLen);
3052
3053 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003054 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003055 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3056 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003057 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003058 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003059 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003060 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3061 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003062
Jordan Rose92303592012-09-08 04:00:03 +00003063 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3064 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3065
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003066 // The remaining checks depend on the data arguments.
3067 if (HasVAListArg)
3068 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003069
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003070 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003071 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003072
Jordan Rose58bbe422012-07-19 18:10:08 +00003073 const Expr *Arg = getDataArg(argIndex);
3074 if (!Arg)
3075 return true;
3076
3077 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003078}
3079
Jordan Roseaee34382012-09-05 22:56:26 +00003080static bool requiresParensToAddCast(const Expr *E) {
3081 // FIXME: We should have a general way to reason about operator
3082 // precedence and whether parens are actually needed here.
3083 // Take care of a few common cases where they aren't.
3084 const Expr *Inside = E->IgnoreImpCasts();
3085 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3086 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3087
3088 switch (Inside->getStmtClass()) {
3089 case Stmt::ArraySubscriptExprClass:
3090 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003091 case Stmt::CharacterLiteralClass:
3092 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003093 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003094 case Stmt::FloatingLiteralClass:
3095 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003096 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003097 case Stmt::ObjCArrayLiteralClass:
3098 case Stmt::ObjCBoolLiteralExprClass:
3099 case Stmt::ObjCBoxedExprClass:
3100 case Stmt::ObjCDictionaryLiteralClass:
3101 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003102 case Stmt::ObjCIvarRefExprClass:
3103 case Stmt::ObjCMessageExprClass:
3104 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003105 case Stmt::ObjCStringLiteralClass:
3106 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003107 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003108 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003109 case Stmt::UnaryOperatorClass:
3110 return false;
3111 default:
3112 return true;
3113 }
3114}
3115
Richard Smith55ce3522012-06-25 20:30:08 +00003116bool
3117CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3118 const char *StartSpecifier,
3119 unsigned SpecifierLen,
3120 const Expr *E) {
3121 using namespace analyze_format_string;
3122 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003123 // Now type check the data expression that matches the
3124 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003125 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3126 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003127 if (!AT.isValid())
3128 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003129
Jordan Rose598ec092012-12-05 18:44:40 +00003130 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003131 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3132 ExprTy = TET->getUnderlyingExpr()->getType();
3133 }
3134
Jordan Rose598ec092012-12-05 18:44:40 +00003135 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003136 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003137
Jordan Rose22b74712012-09-05 22:56:19 +00003138 // Look through argument promotions for our error message's reported type.
3139 // This includes the integral and floating promotions, but excludes array
3140 // and function pointer decay; seeing that an argument intended to be a
3141 // string has type 'char [6]' is probably more confusing than 'char *'.
3142 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3143 if (ICE->getCastKind() == CK_IntegralCast ||
3144 ICE->getCastKind() == CK_FloatingCast) {
3145 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003146 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003147
3148 // Check if we didn't match because of an implicit cast from a 'char'
3149 // or 'short' to an 'int'. This is done because printf is a varargs
3150 // function.
3151 if (ICE->getType() == S.Context.IntTy ||
3152 ICE->getType() == S.Context.UnsignedIntTy) {
3153 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003154 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003155 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003156 }
Jordan Rose98709982012-06-04 22:48:57 +00003157 }
Jordan Rose598ec092012-12-05 18:44:40 +00003158 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3159 // Special case for 'a', which has type 'int' in C.
3160 // Note, however, that we do /not/ want to treat multibyte constants like
3161 // 'MooV' as characters! This form is deprecated but still exists.
3162 if (ExprTy == S.Context.IntTy)
3163 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3164 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003165 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003166
Jordan Rose0e5badd2012-12-05 18:44:49 +00003167 // %C in an Objective-C context prints a unichar, not a wchar_t.
3168 // If the argument is an integer of some kind, believe the %C and suggest
3169 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003170 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003171 if (ObjCContext &&
3172 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3173 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3174 !ExprTy->isCharType()) {
3175 // 'unichar' is defined as a typedef of unsigned short, but we should
3176 // prefer using the typedef if it is visible.
3177 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003178
3179 // While we are here, check if the value is an IntegerLiteral that happens
3180 // to be within the valid range.
3181 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3182 const llvm::APInt &V = IL->getValue();
3183 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3184 return true;
3185 }
3186
Jordan Rose0e5badd2012-12-05 18:44:49 +00003187 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3188 Sema::LookupOrdinaryName);
3189 if (S.LookupName(Result, S.getCurScope())) {
3190 NamedDecl *ND = Result.getFoundDecl();
3191 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3192 if (TD->getUnderlyingType() == IntendedTy)
3193 IntendedTy = S.Context.getTypedefType(TD);
3194 }
3195 }
3196 }
3197
3198 // Special-case some of Darwin's platform-independence types by suggesting
3199 // casts to primitive types that are known to be large enough.
3200 bool ShouldNotPrintDirectly = false;
Jordan Roseaee34382012-09-05 22:56:26 +00003201 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003202 // Use a 'while' to peel off layers of typedefs.
3203 QualType TyTy = IntendedTy;
3204 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseaee34382012-09-05 22:56:26 +00003205 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose0e5badd2012-12-05 18:44:49 +00003206 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseaee34382012-09-05 22:56:26 +00003207 .Case("NSInteger", S.Context.LongTy)
3208 .Case("NSUInteger", S.Context.UnsignedLongTy)
3209 .Case("SInt32", S.Context.IntTy)
3210 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose0e5badd2012-12-05 18:44:49 +00003211 .Default(QualType());
3212
3213 if (!CastTy.isNull()) {
3214 ShouldNotPrintDirectly = true;
3215 IntendedTy = CastTy;
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003216 break;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003217 }
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003218 TyTy = UserTy->desugar();
Jordan Roseaee34382012-09-05 22:56:26 +00003219 }
3220 }
3221
Jordan Rose22b74712012-09-05 22:56:19 +00003222 // We may be able to offer a FixItHint if it is a supported type.
3223 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003224 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003225 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003226
Jordan Rose22b74712012-09-05 22:56:19 +00003227 if (success) {
3228 // Get the fix string from the fixed format specifier
3229 SmallString<16> buf;
3230 llvm::raw_svector_ostream os(buf);
3231 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003232
Jordan Roseaee34382012-09-05 22:56:26 +00003233 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3234
Jordan Rose0e5badd2012-12-05 18:44:49 +00003235 if (IntendedTy == ExprTy) {
3236 // In this case, the specifier is wrong and should be changed to match
3237 // the argument.
3238 EmitFormatDiagnostic(
3239 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3240 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3241 << E->getSourceRange(),
3242 E->getLocStart(),
3243 /*IsStringLocation*/false,
3244 SpecRange,
3245 FixItHint::CreateReplacement(SpecRange, os.str()));
3246
3247 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003248 // The canonical type for formatting this value is different from the
3249 // actual type of the expression. (This occurs, for example, with Darwin's
3250 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3251 // should be printed as 'long' for 64-bit compatibility.)
3252 // Rather than emitting a normal format/argument mismatch, we want to
3253 // add a cast to the recommended type (and correct the format string
3254 // if necessary).
3255 SmallString<16> CastBuf;
3256 llvm::raw_svector_ostream CastFix(CastBuf);
3257 CastFix << "(";
3258 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3259 CastFix << ")";
3260
3261 SmallVector<FixItHint,4> Hints;
3262 if (!AT.matchesType(S.Context, IntendedTy))
3263 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3264
3265 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3266 // If there's already a cast present, just replace it.
3267 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3268 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3269
3270 } else if (!requiresParensToAddCast(E)) {
3271 // If the expression has high enough precedence,
3272 // just write the C-style cast.
3273 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3274 CastFix.str()));
3275 } else {
3276 // Otherwise, add parens around the expression as well as the cast.
3277 CastFix << "(";
3278 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3279 CastFix.str()));
3280
3281 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3282 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3283 }
3284
Jordan Rose0e5badd2012-12-05 18:44:49 +00003285 if (ShouldNotPrintDirectly) {
3286 // The expression has a type that should not be printed directly.
3287 // We extract the name from the typedef because we don't want to show
3288 // the underlying type in the diagnostic.
3289 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseaee34382012-09-05 22:56:26 +00003290
Jordan Rose0e5badd2012-12-05 18:44:49 +00003291 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3292 << Name << IntendedTy
3293 << E->getSourceRange(),
3294 E->getLocStart(), /*IsStringLocation=*/false,
3295 SpecRange, Hints);
3296 } else {
3297 // In this case, the expression could be printed using a different
3298 // specifier, but we've decided that the specifier is probably correct
3299 // and we should cast instead. Just use the normal warning message.
3300 EmitFormatDiagnostic(
3301 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3302 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3303 << E->getSourceRange(),
3304 E->getLocStart(), /*IsStringLocation*/false,
3305 SpecRange, Hints);
3306 }
Jordan Roseaee34382012-09-05 22:56:26 +00003307 }
Jordan Rose22b74712012-09-05 22:56:19 +00003308 } else {
3309 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3310 SpecifierLen);
3311 // Since the warning for passing non-POD types to variadic functions
3312 // was deferred until now, we emit a warning for non-POD
3313 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003314 switch (S.isValidVarArgType(ExprTy)) {
3315 case Sema::VAK_Valid:
3316 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003317 EmitFormatDiagnostic(
Richard Smithd7293d72013-08-05 18:49:43 +00003318 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3319 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3320 << CSR
3321 << E->getSourceRange(),
3322 E->getLocStart(), /*IsStringLocation*/false, CSR);
3323 break;
3324
3325 case Sema::VAK_Undefined:
3326 EmitFormatDiagnostic(
3327 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003328 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003329 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003330 << CallType
3331 << AT.getRepresentativeTypeName(S.Context)
3332 << CSR
3333 << E->getSourceRange(),
3334 E->getLocStart(), /*IsStringLocation*/false, CSR);
Jordan Rose22b74712012-09-05 22:56:19 +00003335 checkForCStrMembers(AT, E, CSR);
Richard Smithd7293d72013-08-05 18:49:43 +00003336 break;
3337
3338 case Sema::VAK_Invalid:
3339 if (ExprTy->isObjCObjectType())
3340 EmitFormatDiagnostic(
3341 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3342 << S.getLangOpts().CPlusPlus11
3343 << ExprTy
3344 << CallType
3345 << AT.getRepresentativeTypeName(S.Context)
3346 << CSR
3347 << E->getSourceRange(),
3348 E->getLocStart(), /*IsStringLocation*/false, CSR);
3349 else
3350 // FIXME: If this is an initializer list, suggest removing the braces
3351 // or inserting a cast to the target type.
3352 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3353 << isa<InitListExpr>(E) << ExprTy << CallType
3354 << AT.getRepresentativeTypeName(S.Context)
3355 << E->getSourceRange();
3356 break;
3357 }
3358
3359 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3360 "format string specifier index out of range");
3361 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003362 }
3363
Ted Kremenekab278de2010-01-28 23:39:18 +00003364 return true;
3365}
3366
Ted Kremenek02087932010-07-16 02:11:22 +00003367//===--- CHECK: Scanf format string checking ------------------------------===//
3368
3369namespace {
3370class CheckScanfHandler : public CheckFormatHandler {
3371public:
3372 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3373 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003374 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003375 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003376 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003377 Sema::VariadicCallType CallType,
3378 llvm::SmallBitVector &CheckedVarArgs)
3379 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3380 numDataArgs, beg, hasVAListArg,
3381 Args, formatIdx, inFunctionCall, CallType,
3382 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003383 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003384
3385 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3386 const char *startSpecifier,
3387 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003388
3389 bool HandleInvalidScanfConversionSpecifier(
3390 const analyze_scanf::ScanfSpecifier &FS,
3391 const char *startSpecifier,
3392 unsigned specifierLen);
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003393
3394 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek02087932010-07-16 02:11:22 +00003395};
Ted Kremenek019d2242010-01-29 01:50:07 +00003396}
Ted Kremenekab278de2010-01-28 23:39:18 +00003397
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003398void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3399 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003400 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3401 getLocationOfByte(end), /*IsStringLocation*/true,
3402 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003403}
3404
Ted Kremenekce815422010-07-19 21:25:57 +00003405bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3406 const analyze_scanf::ScanfSpecifier &FS,
3407 const char *startSpecifier,
3408 unsigned specifierLen) {
3409
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003410 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003411 FS.getConversionSpecifier();
3412
3413 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3414 getLocationOfByte(CS.getStart()),
3415 startSpecifier, specifierLen,
3416 CS.getStart(), CS.getLength());
3417}
3418
Ted Kremenek02087932010-07-16 02:11:22 +00003419bool CheckScanfHandler::HandleScanfSpecifier(
3420 const analyze_scanf::ScanfSpecifier &FS,
3421 const char *startSpecifier,
3422 unsigned specifierLen) {
3423
3424 using namespace analyze_scanf;
3425 using namespace analyze_format_string;
3426
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003427 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003428
Ted Kremenek6cd69422010-07-19 22:01:06 +00003429 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3430 // be used to decide if we are using positional arguments consistently.
3431 if (FS.consumesDataArgument()) {
3432 if (atFirstArg) {
3433 atFirstArg = false;
3434 usesPositionalArgs = FS.usesPositionalArg();
3435 }
3436 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003437 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3438 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003439 return false;
3440 }
Ted Kremenek02087932010-07-16 02:11:22 +00003441 }
3442
3443 // Check if the field with is non-zero.
3444 const OptionalAmount &Amt = FS.getFieldWidth();
3445 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3446 if (Amt.getConstantAmount() == 0) {
3447 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3448 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003449 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3450 getLocationOfByte(Amt.getStart()),
3451 /*IsStringLocation*/true, R,
3452 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003453 }
3454 }
3455
3456 if (!FS.consumesDataArgument()) {
3457 // FIXME: Technically specifying a precision or field width here
3458 // makes no sense. Worth issuing a warning at some point.
3459 return true;
3460 }
3461
3462 // Consume the argument.
3463 unsigned argIndex = FS.getArgIndex();
3464 if (argIndex < NumDataArgs) {
3465 // The check to see if the argIndex is valid will come later.
3466 // We set the bit here because we may exit early from this
3467 // function if we encounter some other error.
3468 CoveredArgs.set(argIndex);
3469 }
3470
Ted Kremenek4407ea42010-07-20 20:04:47 +00003471 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003472 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003473 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3474 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003475 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003476 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003477 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003478 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3479 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003480
Jordan Rose92303592012-09-08 04:00:03 +00003481 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3482 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3483
Ted Kremenek02087932010-07-16 02:11:22 +00003484 // The remaining checks depend on the data arguments.
3485 if (HasVAListArg)
3486 return true;
3487
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003488 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003489 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003490
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003491 // Check that the argument type matches the format specifier.
3492 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003493 if (!Ex)
3494 return true;
3495
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003496 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3497 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003498 ScanfSpecifier fixedFS = FS;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003499 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgd99d6882012-02-15 09:59:46 +00003500 S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003501
3502 if (success) {
3503 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003504 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003505 llvm::raw_svector_ostream os(buf);
3506 fixedFS.toString(os);
3507
3508 EmitFormatDiagnostic(
3509 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003510 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003511 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003512 Ex->getLocStart(),
3513 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003514 getSpecifierRange(startSpecifier, specifierLen),
3515 FixItHint::CreateReplacement(
3516 getSpecifierRange(startSpecifier, specifierLen),
3517 os.str()));
3518 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003519 EmitFormatDiagnostic(
3520 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003521 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003522 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003523 Ex->getLocStart(),
3524 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003525 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003526 }
3527 }
3528
Ted Kremenek02087932010-07-16 02:11:22 +00003529 return true;
3530}
3531
3532void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003533 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003534 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003535 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003536 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003537 bool inFunctionCall, VariadicCallType CallType,
3538 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003539
Ted Kremenekab278de2010-01-28 23:39:18 +00003540 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003541 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003542 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003543 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003544 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3545 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003546 return;
3547 }
Ted Kremenek02087932010-07-16 02:11:22 +00003548
Ted Kremenekab278de2010-01-28 23:39:18 +00003549 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003550 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003551 const char *Str = StrRef.data();
3552 unsigned StrLen = StrRef.size();
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003553 const unsigned numDataArgs = Args.size() - firstDataArg;
Ted Kremenek02087932010-07-16 02:11:22 +00003554
Ted Kremenekab278de2010-01-28 23:39:18 +00003555 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00003556 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003557 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003558 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003559 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3560 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003561 return;
3562 }
Ted Kremenek02087932010-07-16 02:11:22 +00003563
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003564 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00003565 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003566 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003567 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003568 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003569
Hans Wennborg23926bd2011-12-15 10:25:47 +00003570 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003571 getLangOpts(),
3572 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003573 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003574 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003575 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003576 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003577 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003578
Hans Wennborg23926bd2011-12-15 10:25:47 +00003579 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003580 getLangOpts(),
3581 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003582 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003583 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00003584}
3585
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003586//===--- CHECK: Standard memory functions ---------------------------------===//
3587
Nico Weber0e6daef2013-12-26 23:38:39 +00003588/// \brief Takes the expression passed to the size_t parameter of functions
3589/// such as memcmp, strncat, etc and warns if it's a comparison.
3590///
3591/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
3592static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
3593 IdentifierInfo *FnName,
3594 SourceLocation FnLoc,
3595 SourceLocation RParenLoc) {
3596 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
3597 if (!Size)
3598 return false;
3599
3600 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
3601 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
3602 return false;
3603
3604 Preprocessor &PP = S.getPreprocessor();
3605 SourceRange SizeRange = Size->getSourceRange();
3606 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
3607 << SizeRange << FnName;
3608 S.Diag(FnLoc, diag::warn_memsize_comparison_paren_note)
3609 << FnName
3610 << FixItHint::CreateInsertion(
3611 PP.getLocForEndOfToken(Size->getLHS()->getLocEnd()),
3612 ")")
3613 << FixItHint::CreateRemoval(RParenLoc);
3614 S.Diag(SizeRange.getBegin(), diag::warn_memsize_comparison_cast_note)
3615 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
3616 << FixItHint::CreateInsertion(
3617 PP.getLocForEndOfToken(SizeRange.getEnd()), ")");
3618
3619 return true;
3620}
3621
Douglas Gregora74926b2011-05-03 20:05:22 +00003622/// \brief Determine whether the given type is a dynamic class type (e.g.,
3623/// whether it has a vtable).
3624static bool isDynamicClassType(QualType T) {
3625 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3626 if (CXXRecordDecl *Definition = Record->getDefinition())
3627 if (Definition->isDynamicClass())
3628 return true;
3629
3630 return false;
3631}
3632
Chandler Carruth889ed862011-06-21 23:04:20 +00003633/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003634/// otherwise returns NULL.
3635static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00003636 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003637 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3638 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3639 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00003640
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003641 return 0;
3642}
3643
Chandler Carruth889ed862011-06-21 23:04:20 +00003644/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003645static QualType getSizeOfArgType(const Expr* E) {
3646 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3647 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3648 if (SizeOf->getKind() == clang::UETT_SizeOf)
3649 return SizeOf->getTypeOfArgument();
3650
3651 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00003652}
3653
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003654/// \brief Check for dangerous or invalid arguments to memset().
3655///
Chandler Carruthac687262011-06-03 06:23:57 +00003656/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00003657/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3658/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003659///
3660/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00003661void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00003662 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00003663 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00003664 assert(BId != 0);
3665
Ted Kremenekb5fabb22011-04-28 01:38:02 +00003666 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00003667 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00003668 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00003669 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00003670 return;
3671
Anna Zaks22122702012-01-17 00:37:07 +00003672 unsigned LastArg = (BId == Builtin::BImemset ||
3673 BId == Builtin::BIstrndup ? 1 : 2);
3674 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00003675 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003676
Nico Weber0e6daef2013-12-26 23:38:39 +00003677 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
3678 Call->getLocStart(), Call->getRParenLoc()))
3679 return;
3680
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003681 // We have special checking when the length is a sizeof expression.
3682 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3683 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3684 llvm::FoldingSetNodeID SizeOfArgID;
3685
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003686 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3687 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00003688 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003689
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003690 QualType DestTy = Dest->getType();
3691 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3692 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00003693
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003694 // Never warn about void type pointers. This can be used to suppress
3695 // false positives.
3696 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003697 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003698
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003699 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3700 // actually comparing the expressions for equality. Because computing the
3701 // expression IDs can be expensive, we only do this if the diagnostic is
3702 // enabled.
3703 if (SizeOfArg &&
3704 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3705 SizeOfArg->getExprLoc())) {
3706 // We only compute IDs for expressions if the warning is enabled, and
3707 // cache the sizeof arg's ID.
3708 if (SizeOfArgID == llvm::FoldingSetNodeID())
3709 SizeOfArg->Profile(SizeOfArgID, Context, true);
3710 llvm::FoldingSetNodeID DestID;
3711 Dest->Profile(DestID, Context, true);
3712 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00003713 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3714 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003715 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00003716 StringRef ReadableName = FnName->getName();
3717
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003718 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00003719 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003720 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00003721 if (!PointeeTy->isIncompleteType() &&
3722 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003723 ActionIdx = 2; // If the pointee's size is sizeof(char),
3724 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00003725
3726 // If the function is defined as a builtin macro, do not show macro
3727 // expansion.
3728 SourceLocation SL = SizeOfArg->getExprLoc();
3729 SourceRange DSR = Dest->getSourceRange();
3730 SourceRange SSR = SizeOfArg->getSourceRange();
3731 SourceManager &SM = PP.getSourceManager();
3732
3733 if (SM.isMacroArgExpansion(SL)) {
3734 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3735 SL = SM.getSpellingLoc(SL);
3736 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3737 SM.getSpellingLoc(DSR.getEnd()));
3738 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3739 SM.getSpellingLoc(SSR.getEnd()));
3740 }
3741
Anna Zaksd08d9152012-05-30 23:14:52 +00003742 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003743 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00003744 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00003745 << PointeeTy
3746 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00003747 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00003748 << SSR);
3749 DiagRuntimeBehavior(SL, SizeOfArg,
3750 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3751 << ActionIdx
3752 << SSR);
3753
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003754 break;
3755 }
3756 }
3757
3758 // Also check for cases where the sizeof argument is the exact same
3759 // type as the memory argument, and where it points to a user-defined
3760 // record type.
3761 if (SizeOfArgTy != QualType()) {
3762 if (PointeeTy->isRecordType() &&
3763 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3764 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3765 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3766 << FnName << SizeOfArgTy << ArgIdx
3767 << PointeeTy << Dest->getSourceRange()
3768 << LenExpr->getSourceRange());
3769 break;
3770 }
Nico Weberc5e73862011-06-14 16:14:58 +00003771 }
3772
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003773 // Always complain about dynamic classes.
Anna Zaks22122702012-01-17 00:37:07 +00003774 if (isDynamicClassType(PointeeTy)) {
3775
3776 unsigned OperationType = 0;
3777 // "overwritten" if we're warning about the destination for any call
3778 // but memcmp; otherwise a verb appropriate to the call.
3779 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3780 if (BId == Builtin::BImemcpy)
3781 OperationType = 1;
3782 else if(BId == Builtin::BImemmove)
3783 OperationType = 2;
3784 else if (BId == Builtin::BImemcmp)
3785 OperationType = 3;
3786 }
3787
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00003788 DiagRuntimeBehavior(
3789 Dest->getExprLoc(), Dest,
3790 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00003791 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaks201d4892012-01-13 21:52:01 +00003792 << FnName << PointeeTy
Anna Zaks22122702012-01-17 00:37:07 +00003793 << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00003794 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00003795 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3796 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00003797 DiagRuntimeBehavior(
3798 Dest->getExprLoc(), Dest,
3799 PDiag(diag::warn_arc_object_memaccess)
3800 << ArgIdx << FnName << PointeeTy
3801 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00003802 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003803 continue;
John McCall31168b02011-06-15 23:02:42 +00003804
3805 DiagRuntimeBehavior(
3806 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00003807 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003808 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3809 break;
3810 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003811 }
3812}
3813
Ted Kremenek6865f772011-08-18 20:55:45 +00003814// A little helper routine: ignore addition and subtraction of integer literals.
3815// This intentionally does not ignore all integer constant expressions because
3816// we don't want to remove sizeof().
3817static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3818 Ex = Ex->IgnoreParenCasts();
3819
3820 for (;;) {
3821 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3822 if (!BO || !BO->isAdditiveOp())
3823 break;
3824
3825 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3826 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3827
3828 if (isa<IntegerLiteral>(RHS))
3829 Ex = LHS;
3830 else if (isa<IntegerLiteral>(LHS))
3831 Ex = RHS;
3832 else
3833 break;
3834 }
3835
3836 return Ex;
3837}
3838
Anna Zaks13b08572012-08-08 21:42:23 +00003839static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3840 ASTContext &Context) {
3841 // Only handle constant-sized or VLAs, but not flexible members.
3842 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3843 // Only issue the FIXIT for arrays of size > 1.
3844 if (CAT->getSize().getSExtValue() <= 1)
3845 return false;
3846 } else if (!Ty->isVariableArrayType()) {
3847 return false;
3848 }
3849 return true;
3850}
3851
Ted Kremenek6865f772011-08-18 20:55:45 +00003852// Warn if the user has made the 'size' argument to strlcpy or strlcat
3853// be the size of the source, instead of the destination.
3854void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3855 IdentifierInfo *FnName) {
3856
3857 // Don't crash if the user has the wrong number of arguments
3858 if (Call->getNumArgs() != 3)
3859 return;
3860
3861 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3862 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3863 const Expr *CompareWithSrc = NULL;
Nico Weber0e6daef2013-12-26 23:38:39 +00003864
3865 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
3866 Call->getLocStart(), Call->getRParenLoc()))
3867 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00003868
3869 // Look for 'strlcpy(dst, x, sizeof(x))'
3870 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3871 CompareWithSrc = Ex;
3872 else {
3873 // Look for 'strlcpy(dst, x, strlen(x))'
3874 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00003875 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
3876 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00003877 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3878 }
3879 }
3880
3881 if (!CompareWithSrc)
3882 return;
3883
3884 // Determine if the argument to sizeof/strlen is equal to the source
3885 // argument. In principle there's all kinds of things you could do
3886 // here, for instance creating an == expression and evaluating it with
3887 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3888 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3889 if (!SrcArgDRE)
3890 return;
3891
3892 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3893 if (!CompareWithSrcDRE ||
3894 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3895 return;
3896
3897 const Expr *OriginalSizeArg = Call->getArg(2);
3898 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3899 << OriginalSizeArg->getSourceRange() << FnName;
3900
3901 // Output a FIXIT hint if the destination is an array (rather than a
3902 // pointer to an array). This could be enhanced to handle some
3903 // pointers if we know the actual size, like if DstArg is 'array+2'
3904 // we could say 'sizeof(array)-2'.
3905 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00003906 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00003907 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00003908
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003909 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00003910 llvm::raw_svector_ostream OS(sizeString);
3911 OS << "sizeof(";
Richard Smith235341b2012-08-16 03:56:14 +00003912 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00003913 OS << ")";
3914
3915 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3916 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3917 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00003918}
3919
Anna Zaks314cd092012-02-01 19:08:57 +00003920/// Check if two expressions refer to the same declaration.
3921static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3922 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3923 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3924 return D1->getDecl() == D2->getDecl();
3925 return false;
3926}
3927
3928static const Expr *getStrlenExprArg(const Expr *E) {
3929 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3930 const FunctionDecl *FD = CE->getDirectCallee();
3931 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3932 return 0;
3933 return CE->getArg(0)->IgnoreParenCasts();
3934 }
3935 return 0;
3936}
3937
3938// Warn on anti-patterns as the 'size' argument to strncat.
3939// The correct size argument should look like following:
3940// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3941void Sema::CheckStrncatArguments(const CallExpr *CE,
3942 IdentifierInfo *FnName) {
3943 // Don't crash if the user has the wrong number of arguments.
3944 if (CE->getNumArgs() < 3)
3945 return;
3946 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3947 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3948 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3949
Nico Weber0e6daef2013-12-26 23:38:39 +00003950 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
3951 CE->getRParenLoc()))
3952 return;
3953
Anna Zaks314cd092012-02-01 19:08:57 +00003954 // Identify common expressions, which are wrongly used as the size argument
3955 // to strncat and may lead to buffer overflows.
3956 unsigned PatternType = 0;
3957 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3958 // - sizeof(dst)
3959 if (referToTheSameDecl(SizeOfArg, DstArg))
3960 PatternType = 1;
3961 // - sizeof(src)
3962 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3963 PatternType = 2;
3964 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3965 if (BE->getOpcode() == BO_Sub) {
3966 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3967 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3968 // - sizeof(dst) - strlen(dst)
3969 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3970 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3971 PatternType = 1;
3972 // - sizeof(src) - (anything)
3973 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3974 PatternType = 2;
3975 }
3976 }
3977
3978 if (PatternType == 0)
3979 return;
3980
Anna Zaks5069aa32012-02-03 01:27:37 +00003981 // Generate the diagnostic.
3982 SourceLocation SL = LenArg->getLocStart();
3983 SourceRange SR = LenArg->getSourceRange();
3984 SourceManager &SM = PP.getSourceManager();
3985
3986 // If the function is defined as a builtin macro, do not show macro expansion.
3987 if (SM.isMacroArgExpansion(SL)) {
3988 SL = SM.getSpellingLoc(SL);
3989 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3990 SM.getSpellingLoc(SR.getEnd()));
3991 }
3992
Anna Zaks13b08572012-08-08 21:42:23 +00003993 // Check if the destination is an array (rather than a pointer to an array).
3994 QualType DstTy = DstArg->getType();
3995 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3996 Context);
3997 if (!isKnownSizeArray) {
3998 if (PatternType == 1)
3999 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4000 else
4001 Diag(SL, diag::warn_strncat_src_size) << SR;
4002 return;
4003 }
4004
Anna Zaks314cd092012-02-01 19:08:57 +00004005 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004006 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004007 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004008 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004009
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004010 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004011 llvm::raw_svector_ostream OS(sizeString);
4012 OS << "sizeof(";
Richard Smith235341b2012-08-16 03:56:14 +00004013 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004014 OS << ") - ";
4015 OS << "strlen(";
Richard Smith235341b2012-08-16 03:56:14 +00004016 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004017 OS << ") - 1";
4018
Anna Zaks5069aa32012-02-03 01:27:37 +00004019 Diag(SL, diag::note_strncat_wrong_size)
4020 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004021}
4022
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004023//===--- CHECK: Return Address of Stack Variable --------------------------===//
4024
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004025static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4026 Decl *ParentDecl);
4027static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4028 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004029
4030/// CheckReturnStackAddr - Check if a return statement returns the address
4031/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004032static void
4033CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4034 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004035
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004036 Expr *stackE = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004037 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004038
4039 // Perform checking for returned stack addresses, local blocks,
4040 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004041 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004042 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004043 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stump12b8ce12009-08-04 21:02:39 +00004044 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004045 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004046 }
4047
4048 if (stackE == 0)
4049 return; // Nothing suspicious was found.
4050
4051 SourceLocation diagLoc;
4052 SourceRange diagRange;
4053 if (refVars.empty()) {
4054 diagLoc = stackE->getLocStart();
4055 diagRange = stackE->getSourceRange();
4056 } else {
4057 // We followed through a reference variable. 'stackE' contains the
4058 // problematic expression but we will warn at the return statement pointing
4059 // at the reference variable. We will later display the "trail" of
4060 // reference variables using notes.
4061 diagLoc = refVars[0]->getLocStart();
4062 diagRange = refVars[0]->getSourceRange();
4063 }
4064
4065 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004066 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004067 : diag::warn_ret_stack_addr)
4068 << DR->getDecl()->getDeclName() << diagRange;
4069 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004070 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004071 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004072 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004073 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004074 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4075 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004076 << diagRange;
4077 }
4078
4079 // Display the "trail" of reference variables that we followed until we
4080 // found the problematic expression using notes.
4081 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4082 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4083 // If this var binds to another reference var, show the range of the next
4084 // var, otherwise the var binds to the problematic expression, in which case
4085 // show the range of the expression.
4086 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4087 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004088 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4089 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004090 }
4091}
4092
4093/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4094/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004095/// to a location on the stack, a local block, an address of a label, or a
4096/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004097/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004098/// encounter a subexpression that (1) clearly does not lead to one of the
4099/// above problematic expressions (2) is something we cannot determine leads to
4100/// a problematic expression based on such local checking.
4101///
4102/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4103/// the expression that they point to. Such variables are added to the
4104/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004105///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004106/// EvalAddr processes expressions that are pointers that are used as
4107/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004108/// At the base case of the recursion is a check for the above problematic
4109/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004110///
4111/// This implementation handles:
4112///
4113/// * pointer-to-pointer casts
4114/// * implicit conversions from array references to pointers
4115/// * taking the address of fields
4116/// * arbitrary interplay between "&" and "*" operators
4117/// * pointer arithmetic from an address of a stack variable
4118/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004119static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4120 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004121 if (E->isTypeDependent())
Craig Topper47005942013-08-02 05:10:31 +00004122 return NULL;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004123
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004124 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00004125 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004126 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004127 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00004128 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00004129
Peter Collingbourne91147592011-04-15 00:35:48 +00004130 E = E->IgnoreParens();
4131
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004132 // Our "symbolic interpreter" is just a dispatch off the currently
4133 // viewed AST node. We then recursively traverse the AST by calling
4134 // EvalAddr and EvalVal appropriately.
4135 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004136 case Stmt::DeclRefExprClass: {
4137 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4138
4139 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4140 // If this is a reference variable, follow through to the expression that
4141 // it points to.
4142 if (V->hasLocalStorage() &&
4143 V->getType()->isReferenceType() && V->hasInit()) {
4144 // Add the reference variable to the "trail".
4145 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004146 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004147 }
4148
4149 return NULL;
4150 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004151
Chris Lattner934edb22007-12-28 05:31:15 +00004152 case Stmt::UnaryOperatorClass: {
4153 // The only unary operator that make sense to handle here
4154 // is AddrOf. All others don't make sense as pointers.
4155 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004156
John McCalle3027922010-08-25 11:45:40 +00004157 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004158 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004159 else
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004160 return NULL;
4161 }
Mike Stump11289f42009-09-09 15:08:12 +00004162
Chris Lattner934edb22007-12-28 05:31:15 +00004163 case Stmt::BinaryOperatorClass: {
4164 // Handle pointer arithmetic. All other binary operators are not valid
4165 // in this context.
4166 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00004167 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00004168
John McCalle3027922010-08-25 11:45:40 +00004169 if (op != BO_Add && op != BO_Sub)
Chris Lattner934edb22007-12-28 05:31:15 +00004170 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00004171
Chris Lattner934edb22007-12-28 05:31:15 +00004172 Expr *Base = B->getLHS();
4173
4174 // Determine which argument is the real pointer base. It could be
4175 // the RHS argument instead of the LHS.
4176 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00004177
Chris Lattner934edb22007-12-28 05:31:15 +00004178 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004179 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004180 }
Steve Naroff2752a172008-09-10 19:17:48 +00004181
Chris Lattner934edb22007-12-28 05:31:15 +00004182 // For conditional operators we need to see if either the LHS or RHS are
4183 // valid DeclRefExpr*s. If one of them is valid, we return it.
4184 case Stmt::ConditionalOperatorClass: {
4185 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004186
Chris Lattner934edb22007-12-28 05:31:15 +00004187 // Handle the GNU extension for missing LHS.
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004188 if (Expr *lhsExpr = C->getLHS()) {
4189 // In C++, we can have a throw-expression, which has 'void' type.
4190 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004191 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004192 return LHS;
4193 }
Chris Lattner934edb22007-12-28 05:31:15 +00004194
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004195 // In C++, we can have a throw-expression, which has 'void' type.
4196 if (C->getRHS()->getType()->isVoidType())
4197 return NULL;
4198
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004199 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004200 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004201
4202 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00004203 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004204 return E; // local block.
4205 return NULL;
4206
4207 case Stmt::AddrLabelExprClass:
4208 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00004209
John McCall28fc7092011-11-10 05:35:25 +00004210 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004211 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4212 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004213
Ted Kremenekc3b4c522008-08-07 00:49:01 +00004214 // For casts, we need to handle conversions from arrays to
4215 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00004216 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00004217 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00004218 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00004219 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00004220 case Stmt::CXXStaticCastExprClass:
4221 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00004222 case Stmt::CXXConstCastExprClass:
4223 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00004224 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4225 switch (cast<CastExpr>(E)->getCastKind()) {
4226 case CK_BitCast:
4227 case CK_LValueToRValue:
4228 case CK_NoOp:
4229 case CK_BaseToDerived:
4230 case CK_DerivedToBase:
4231 case CK_UncheckedDerivedToBase:
4232 case CK_Dynamic:
4233 case CK_CPointerToObjCPointerCast:
4234 case CK_BlockPointerToObjCPointerCast:
4235 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004236 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004237
4238 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004239 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004240
4241 default:
4242 return 0;
4243 }
Chris Lattner934edb22007-12-28 05:31:15 +00004244 }
Mike Stump11289f42009-09-09 15:08:12 +00004245
Douglas Gregorfe314812011-06-21 17:03:29 +00004246 case Stmt::MaterializeTemporaryExprClass:
4247 if (Expr *Result = EvalAddr(
4248 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004249 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004250 return Result;
4251
4252 return E;
4253
Chris Lattner934edb22007-12-28 05:31:15 +00004254 // Everything else: we simply don't reason about them.
4255 default:
4256 return NULL;
4257 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004258}
Mike Stump11289f42009-09-09 15:08:12 +00004259
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004260
4261/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4262/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004263static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4264 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004265do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004266 // We should only be called for evaluating non-pointer expressions, or
4267 // expressions with a pointer type that are not used as references but instead
4268 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00004269
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004270 // Our "symbolic interpreter" is just a dispatch off the currently
4271 // viewed AST node. We then recursively traverse the AST by calling
4272 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00004273
4274 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004275 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004276 case Stmt::ImplicitCastExprClass: {
4277 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00004278 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004279 E = IE->getSubExpr();
4280 continue;
4281 }
4282 return NULL;
4283 }
4284
John McCall28fc7092011-11-10 05:35:25 +00004285 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004286 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004287
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004288 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004289 // When we hit a DeclRefExpr we are looking at code that refers to a
4290 // variable's name. If it's not a reference variable we check if it has
4291 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004292 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004293
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004294 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4295 // Check if it refers to itself, e.g. "int& i = i;".
4296 if (V == ParentDecl)
4297 return DR;
4298
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004299 if (V->hasLocalStorage()) {
4300 if (!V->getType()->isReferenceType())
4301 return DR;
4302
4303 // Reference variable, follow through to the expression that
4304 // it points to.
4305 if (V->hasInit()) {
4306 // Add the reference variable to the "trail".
4307 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004308 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004309 }
4310 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004311 }
Mike Stump11289f42009-09-09 15:08:12 +00004312
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004313 return NULL;
4314 }
Mike Stump11289f42009-09-09 15:08:12 +00004315
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004316 case Stmt::UnaryOperatorClass: {
4317 // The only unary operator that make sense to handle here
4318 // is Deref. All others don't resolve to a "name." This includes
4319 // handling all sorts of rvalues passed to a unary operator.
4320 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004321
John McCalle3027922010-08-25 11:45:40 +00004322 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004323 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004324
4325 return NULL;
4326 }
Mike Stump11289f42009-09-09 15:08:12 +00004327
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004328 case Stmt::ArraySubscriptExprClass: {
4329 // Array subscripts are potential references to data on the stack. We
4330 // retrieve the DeclRefExpr* for the array variable if it indeed
4331 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004332 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004333 }
Mike Stump11289f42009-09-09 15:08:12 +00004334
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004335 case Stmt::ConditionalOperatorClass: {
4336 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004337 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004338 ConditionalOperator *C = cast<ConditionalOperator>(E);
4339
Anders Carlsson801c5c72007-11-30 19:04:31 +00004340 // Handle the GNU extension for missing LHS.
4341 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004342 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson801c5c72007-11-30 19:04:31 +00004343 return LHS;
4344
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004345 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004346 }
Mike Stump11289f42009-09-09 15:08:12 +00004347
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004348 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00004349 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004350 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004351
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004352 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004353 if (M->isArrow())
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004354 return NULL;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004355
4356 // Check whether the member type is itself a reference, in which case
4357 // we're not going to refer to the member, but to what the member refers to.
4358 if (M->getMemberDecl()->getType()->isReferenceType())
4359 return NULL;
4360
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004361 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004362 }
Mike Stump11289f42009-09-09 15:08:12 +00004363
Douglas Gregorfe314812011-06-21 17:03:29 +00004364 case Stmt::MaterializeTemporaryExprClass:
4365 if (Expr *Result = EvalVal(
4366 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004367 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004368 return Result;
4369
4370 return E;
4371
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004372 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004373 // Check that we don't return or take the address of a reference to a
4374 // temporary. This is only useful in C++.
4375 if (!E->isTypeDependent() && E->isRValue())
4376 return E;
4377
4378 // Everything else: we simply don't reason about them.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004379 return NULL;
4380 }
Ted Kremenekb7861562010-08-04 20:01:07 +00004381} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004382}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004383
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004384void
4385Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
4386 SourceLocation ReturnLoc,
4387 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00004388 const AttrVec *Attrs,
4389 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004390 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
4391
4392 // Check if the return value is null but should not be.
4393 if (Attrs)
4394 for (specific_attr_iterator<ReturnsNonNullAttr>
4395 I = specific_attr_iterator<ReturnsNonNullAttr>(Attrs->begin()),
4396 E = specific_attr_iterator<ReturnsNonNullAttr>(Attrs->end());
4397 I != E; ++I) {
4398 if (CheckNonNullExpr(*this, RetValExp))
4399 Diag(ReturnLoc, diag::warn_null_ret)
4400 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
4401 break;
4402 }
Artyom Skrobov9f213442014-01-24 11:10:39 +00004403
4404 // C++11 [basic.stc.dynamic.allocation]p4:
4405 // If an allocation function declared with a non-throwing
4406 // exception-specification fails to allocate storage, it shall return
4407 // a null pointer. Any other allocation function that fails to allocate
4408 // storage shall indicate failure only by throwing an exception [...]
4409 if (FD) {
4410 OverloadedOperatorKind Op = FD->getOverloadedOperator();
4411 if (Op == OO_New || Op == OO_Array_New) {
4412 const FunctionProtoType *Proto
4413 = FD->getType()->castAs<FunctionProtoType>();
4414 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
4415 CheckNonNullExpr(*this, RetValExp))
4416 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
4417 << FD << getLangOpts().CPlusPlus11;
4418 }
4419 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004420}
4421
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004422//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4423
4424/// Check for comparisons of floating point operands using != and ==.
4425/// Issue a warning if these are no self-comparisons, as they are not likely
4426/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00004427void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00004428 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4429 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004430
4431 // Special case: check for x == x (which is OK).
4432 // Do not emit warnings for such cases.
4433 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4434 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4435 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00004436 return;
Mike Stump11289f42009-09-09 15:08:12 +00004437
4438
Ted Kremenekeda40e22007-11-29 00:59:04 +00004439 // Special case: check for comparisons against literals that can be exactly
4440 // represented by APFloat. In such cases, do not emit a warning. This
4441 // is a heuristic: often comparison against such literals are used to
4442 // detect if a value in a variable has not changed. This clearly can
4443 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00004444 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4445 if (FLL->isExact())
4446 return;
4447 } else
4448 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4449 if (FLR->isExact())
4450 return;
Mike Stump11289f42009-09-09 15:08:12 +00004451
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004452 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00004453 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004454 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004455 return;
Mike Stump11289f42009-09-09 15:08:12 +00004456
David Blaikie1f4ff152012-07-16 20:47:22 +00004457 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004458 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004459 return;
Mike Stump11289f42009-09-09 15:08:12 +00004460
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004461 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00004462 Diag(Loc, diag::warn_floatingpoint_eq)
4463 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004464}
John McCallca01b222010-01-04 23:21:16 +00004465
John McCall70aa5392010-01-06 05:24:50 +00004466//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4467//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00004468
John McCall70aa5392010-01-06 05:24:50 +00004469namespace {
John McCallca01b222010-01-04 23:21:16 +00004470
John McCall70aa5392010-01-06 05:24:50 +00004471/// Structure recording the 'active' range of an integer-valued
4472/// expression.
4473struct IntRange {
4474 /// The number of bits active in the int.
4475 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00004476
John McCall70aa5392010-01-06 05:24:50 +00004477 /// True if the int is known not to have negative values.
4478 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00004479
John McCall70aa5392010-01-06 05:24:50 +00004480 IntRange(unsigned Width, bool NonNegative)
4481 : Width(Width), NonNegative(NonNegative)
4482 {}
John McCallca01b222010-01-04 23:21:16 +00004483
John McCall817d4af2010-11-10 23:38:19 +00004484 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00004485 static IntRange forBoolType() {
4486 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00004487 }
4488
John McCall817d4af2010-11-10 23:38:19 +00004489 /// Returns the range of an opaque value of the given integral type.
4490 static IntRange forValueOfType(ASTContext &C, QualType T) {
4491 return forValueOfCanonicalType(C,
4492 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00004493 }
4494
John McCall817d4af2010-11-10 23:38:19 +00004495 /// Returns the range of an opaque value of a canonical integral type.
4496 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00004497 assert(T->isCanonicalUnqualified());
4498
4499 if (const VectorType *VT = dyn_cast<VectorType>(T))
4500 T = VT->getElementType().getTypePtr();
4501 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4502 T = CT->getElementType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00004503
David Majnemer6a426652013-06-07 22:07:20 +00004504 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00004505 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00004506 EnumDecl *Enum = ET->getDecl();
4507 if (!Enum->isCompleteDefinition())
4508 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00004509
David Majnemer6a426652013-06-07 22:07:20 +00004510 unsigned NumPositive = Enum->getNumPositiveBits();
4511 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00004512
David Majnemer6a426652013-06-07 22:07:20 +00004513 if (NumNegative == 0)
4514 return IntRange(NumPositive, true/*NonNegative*/);
4515 else
4516 return IntRange(std::max(NumPositive + 1, NumNegative),
4517 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00004518 }
John McCall70aa5392010-01-06 05:24:50 +00004519
4520 const BuiltinType *BT = cast<BuiltinType>(T);
4521 assert(BT->isInteger());
4522
4523 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4524 }
4525
John McCall817d4af2010-11-10 23:38:19 +00004526 /// Returns the "target" range of a canonical integral type, i.e.
4527 /// the range of values expressible in the type.
4528 ///
4529 /// This matches forValueOfCanonicalType except that enums have the
4530 /// full range of their type, not the range of their enumerators.
4531 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4532 assert(T->isCanonicalUnqualified());
4533
4534 if (const VectorType *VT = dyn_cast<VectorType>(T))
4535 T = VT->getElementType().getTypePtr();
4536 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4537 T = CT->getElementType().getTypePtr();
4538 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00004539 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00004540
4541 const BuiltinType *BT = cast<BuiltinType>(T);
4542 assert(BT->isInteger());
4543
4544 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4545 }
4546
4547 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00004548 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00004549 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00004550 L.NonNegative && R.NonNegative);
4551 }
4552
John McCall817d4af2010-11-10 23:38:19 +00004553 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00004554 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00004555 return IntRange(std::min(L.Width, R.Width),
4556 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00004557 }
4558};
4559
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004560static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4561 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004562 if (value.isSigned() && value.isNegative())
4563 return IntRange(value.getMinSignedBits(), false);
4564
4565 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00004566 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004567
4568 // isNonNegative() just checks the sign bit without considering
4569 // signedness.
4570 return IntRange(value.getActiveBits(), true);
4571}
4572
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004573static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4574 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004575 if (result.isInt())
4576 return GetValueRange(C, result.getInt(), MaxWidth);
4577
4578 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00004579 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4580 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4581 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4582 R = IntRange::join(R, El);
4583 }
John McCall70aa5392010-01-06 05:24:50 +00004584 return R;
4585 }
4586
4587 if (result.isComplexInt()) {
4588 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4589 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4590 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00004591 }
4592
4593 // This can happen with lossless casts to intptr_t of "based" lvalues.
4594 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00004595 // FIXME: The only reason we need to pass the type in here is to get
4596 // the sign right on this one case. It would be nice if APValue
4597 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004598 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00004599 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00004600}
John McCall70aa5392010-01-06 05:24:50 +00004601
Eli Friedmane6d33952013-07-08 20:20:06 +00004602static QualType GetExprType(Expr *E) {
4603 QualType Ty = E->getType();
4604 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4605 Ty = AtomicRHS->getValueType();
4606 return Ty;
4607}
4608
John McCall70aa5392010-01-06 05:24:50 +00004609/// Pseudo-evaluate the given integer expression, estimating the
4610/// range of values it might take.
4611///
4612/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004613static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004614 E = E->IgnoreParens();
4615
4616 // Try a full evaluation first.
4617 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00004618 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00004619 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004620
4621 // I think we only want to look through implicit casts here; if the
4622 // user has an explicit widening cast, we should treat the value as
4623 // being of the new, wider type.
4624 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00004625 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00004626 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4627
Eli Friedmane6d33952013-07-08 20:20:06 +00004628 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00004629
John McCalle3027922010-08-25 11:45:40 +00004630 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00004631
John McCall70aa5392010-01-06 05:24:50 +00004632 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00004633 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00004634 return OutputTypeRange;
4635
4636 IntRange SubRange
4637 = GetExprRange(C, CE->getSubExpr(),
4638 std::min(MaxWidth, OutputTypeRange.Width));
4639
4640 // Bail out if the subexpr's range is as wide as the cast type.
4641 if (SubRange.Width >= OutputTypeRange.Width)
4642 return OutputTypeRange;
4643
4644 // Otherwise, we take the smaller width, and we're non-negative if
4645 // either the output type or the subexpr is.
4646 return IntRange(SubRange.Width,
4647 SubRange.NonNegative || OutputTypeRange.NonNegative);
4648 }
4649
4650 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4651 // If we can fold the condition, just take that operand.
4652 bool CondResult;
4653 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4654 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4655 : CO->getFalseExpr(),
4656 MaxWidth);
4657
4658 // Otherwise, conservatively merge.
4659 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4660 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4661 return IntRange::join(L, R);
4662 }
4663
4664 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4665 switch (BO->getOpcode()) {
4666
4667 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00004668 case BO_LAnd:
4669 case BO_LOr:
4670 case BO_LT:
4671 case BO_GT:
4672 case BO_LE:
4673 case BO_GE:
4674 case BO_EQ:
4675 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00004676 return IntRange::forBoolType();
4677
John McCallc3688382011-07-13 06:35:24 +00004678 // The type of the assignments is the type of the LHS, so the RHS
4679 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00004680 case BO_MulAssign:
4681 case BO_DivAssign:
4682 case BO_RemAssign:
4683 case BO_AddAssign:
4684 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00004685 case BO_XorAssign:
4686 case BO_OrAssign:
4687 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00004688 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00004689
John McCallc3688382011-07-13 06:35:24 +00004690 // Simple assignments just pass through the RHS, which will have
4691 // been coerced to the LHS type.
4692 case BO_Assign:
4693 // TODO: bitfields?
4694 return GetExprRange(C, BO->getRHS(), MaxWidth);
4695
John McCall70aa5392010-01-06 05:24:50 +00004696 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00004697 case BO_PtrMemD:
4698 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00004699 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00004700
John McCall2ce81ad2010-01-06 22:07:33 +00004701 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00004702 case BO_And:
4703 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00004704 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4705 GetExprRange(C, BO->getRHS(), MaxWidth));
4706
John McCall70aa5392010-01-06 05:24:50 +00004707 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00004708 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00004709 // ...except that we want to treat '1 << (blah)' as logically
4710 // positive. It's an important idiom.
4711 if (IntegerLiteral *I
4712 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4713 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00004714 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00004715 return IntRange(R.Width, /*NonNegative*/ true);
4716 }
4717 }
4718 // fallthrough
4719
John McCalle3027922010-08-25 11:45:40 +00004720 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00004721 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00004722
John McCall2ce81ad2010-01-06 22:07:33 +00004723 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00004724 case BO_Shr:
4725 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00004726 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4727
4728 // If the shift amount is a positive constant, drop the width by
4729 // that much.
4730 llvm::APSInt shift;
4731 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4732 shift.isNonNegative()) {
4733 unsigned zext = shift.getZExtValue();
4734 if (zext >= L.Width)
4735 L.Width = (L.NonNegative ? 0 : 1);
4736 else
4737 L.Width -= zext;
4738 }
4739
4740 return L;
4741 }
4742
4743 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00004744 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00004745 return GetExprRange(C, BO->getRHS(), MaxWidth);
4746
John McCall2ce81ad2010-01-06 22:07:33 +00004747 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00004748 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00004749 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00004750 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00004751 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004752
John McCall51431812011-07-14 22:39:48 +00004753 // The width of a division result is mostly determined by the size
4754 // of the LHS.
4755 case BO_Div: {
4756 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00004757 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00004758 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4759
4760 // If the divisor is constant, use that.
4761 llvm::APSInt divisor;
4762 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4763 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4764 if (log2 >= L.Width)
4765 L.Width = (L.NonNegative ? 0 : 1);
4766 else
4767 L.Width = std::min(L.Width - log2, MaxWidth);
4768 return L;
4769 }
4770
4771 // Otherwise, just use the LHS's width.
4772 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4773 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4774 }
4775
4776 // The result of a remainder can't be larger than the result of
4777 // either side.
4778 case BO_Rem: {
4779 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00004780 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00004781 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4782 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4783
4784 IntRange meet = IntRange::meet(L, R);
4785 meet.Width = std::min(meet.Width, MaxWidth);
4786 return meet;
4787 }
4788
4789 // The default behavior is okay for these.
4790 case BO_Mul:
4791 case BO_Add:
4792 case BO_Xor:
4793 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00004794 break;
4795 }
4796
John McCall51431812011-07-14 22:39:48 +00004797 // The default case is to treat the operation as if it were closed
4798 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00004799 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4800 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4801 return IntRange::join(L, R);
4802 }
4803
4804 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4805 switch (UO->getOpcode()) {
4806 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00004807 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00004808 return IntRange::forBoolType();
4809
4810 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00004811 case UO_Deref:
4812 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00004813 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00004814
4815 default:
4816 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4817 }
4818 }
4819
Ted Kremeneka553fbf2013-10-14 18:55:27 +00004820 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
4821 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
4822
John McCalld25db7e2013-05-06 21:39:12 +00004823 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00004824 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00004825 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00004826
Eli Friedmane6d33952013-07-08 20:20:06 +00004827 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00004828}
John McCall263a48b2010-01-04 23:31:57 +00004829
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004830static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00004831 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00004832}
4833
John McCall263a48b2010-01-04 23:31:57 +00004834/// Checks whether the given value, which currently has the given
4835/// source semantics, has the same value when coerced through the
4836/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004837static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4838 const llvm::fltSemantics &Src,
4839 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00004840 llvm::APFloat truncated = value;
4841
4842 bool ignored;
4843 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4844 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4845
4846 return truncated.bitwiseIsEqual(value);
4847}
4848
4849/// Checks whether the given value, which currently has the given
4850/// source semantics, has the same value when coerced through the
4851/// target semantics.
4852///
4853/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004854static bool IsSameFloatAfterCast(const APValue &value,
4855 const llvm::fltSemantics &Src,
4856 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00004857 if (value.isFloat())
4858 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4859
4860 if (value.isVector()) {
4861 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4862 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4863 return false;
4864 return true;
4865 }
4866
4867 assert(value.isComplexFloat());
4868 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4869 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4870}
4871
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004872static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00004873
Ted Kremenek6274be42010-09-23 21:43:44 +00004874static bool IsZero(Sema &S, Expr *E) {
4875 // Suppress cases where we are comparing against an enum constant.
4876 if (const DeclRefExpr *DR =
4877 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4878 if (isa<EnumConstantDecl>(DR->getDecl()))
4879 return false;
4880
4881 // Suppress cases where the '0' value is expanded from a macro.
4882 if (E->getLocStart().isMacroID())
4883 return false;
4884
John McCallcc7e5bf2010-05-06 08:58:33 +00004885 llvm::APSInt Value;
4886 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4887}
4888
John McCall2551c1b2010-10-06 00:25:24 +00004889static bool HasEnumType(Expr *E) {
4890 // Strip off implicit integral promotions.
4891 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00004892 if (ICE->getCastKind() != CK_IntegralCast &&
4893 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00004894 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00004895 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00004896 }
4897
4898 return E->getType()->isEnumeralType();
4899}
4900
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004901static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00004902 // Disable warning in template instantiations.
4903 if (!S.ActiveTemplateInstantiations.empty())
4904 return;
4905
John McCalle3027922010-08-25 11:45:40 +00004906 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00004907 if (E->isValueDependent())
4908 return;
4909
John McCalle3027922010-08-25 11:45:40 +00004910 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004911 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00004912 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00004913 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004914 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004915 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00004916 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00004917 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004918 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004919 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00004920 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00004921 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004922 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004923 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00004924 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00004925 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4926 }
4927}
4928
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004929static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004930 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004931 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004932 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00004933 // Disable warning in template instantiations.
4934 if (!S.ActiveTemplateInstantiations.empty())
4935 return;
4936
Richard Trieu560910c2012-11-14 22:50:24 +00004937 // 0 values are handled later by CheckTrivialUnsignedComparison().
4938 if (Value == 0)
4939 return;
4940
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004941 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004942 QualType OtherT = Other->getType();
4943 QualType ConstantT = Constant->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00004944 QualType CommonT = E->getLHS()->getType();
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004945 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004946 return;
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004947 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004948 && "comparison with non-integer type");
Richard Trieu560910c2012-11-14 22:50:24 +00004949
4950 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu560910c2012-11-14 22:50:24 +00004951 bool CommonSigned = CommonT->isSignedIntegerType();
4952
4953 bool EqualityOnly = false;
4954
4955 // TODO: Investigate using GetExprRange() to get tighter bounds on
4956 // on the bit ranges.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004957 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu560910c2012-11-14 22:50:24 +00004958 unsigned OtherWidth = OtherRange.Width;
4959
4960 if (CommonSigned) {
4961 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedman5ac98752012-11-30 23:09:29 +00004962 if (!OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00004963 // Check that the constant is representable in type OtherT.
4964 if (ConstantSigned) {
4965 if (OtherWidth >= Value.getMinSignedBits())
4966 return;
4967 } else { // !ConstantSigned
4968 if (OtherWidth >= Value.getActiveBits() + 1)
4969 return;
4970 }
4971 } else { // !OtherSigned
4972 // Check that the constant is representable in type OtherT.
4973 // Negative values are out of range.
4974 if (ConstantSigned) {
4975 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4976 return;
4977 } else { // !ConstantSigned
4978 if (OtherWidth >= Value.getActiveBits())
4979 return;
4980 }
4981 }
4982 } else { // !CommonSigned
Eli Friedman5ac98752012-11-30 23:09:29 +00004983 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00004984 if (OtherWidth >= Value.getActiveBits())
4985 return;
Eli Friedman5ac98752012-11-30 23:09:29 +00004986 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu560910c2012-11-14 22:50:24 +00004987 // Check to see if the constant is representable in OtherT.
4988 if (OtherWidth > Value.getActiveBits())
4989 return;
4990 // Check to see if the constant is equivalent to a negative value
4991 // cast to CommonT.
4992 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu03c3a2f2012-11-15 03:43:50 +00004993 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu560910c2012-11-14 22:50:24 +00004994 return;
4995 // The constant value rests between values that OtherT can represent after
4996 // conversion. Relational comparison still works, but equality
4997 // comparisons will be tautological.
4998 EqualityOnly = true;
4999 } else { // OtherSigned && ConstantSigned
5000 assert(0 && "Two signed types converted to unsigned types.");
5001 }
5002 }
5003
5004 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5005
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005006 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005007 if (op == BO_EQ || op == BO_NE) {
5008 IsTrue = op == BO_NE;
5009 } else if (EqualityOnly) {
5010 return;
5011 } else if (RhsConstant) {
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005012 if (op == BO_GT || op == BO_GE)
Richard Trieu560910c2012-11-14 22:50:24 +00005013 IsTrue = !PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005014 else // op == BO_LT || op == BO_LE
Richard Trieu560910c2012-11-14 22:50:24 +00005015 IsTrue = PositiveConstant;
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005016 } else {
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005017 if (op == BO_LT || op == BO_LE)
Richard Trieu560910c2012-11-14 22:50:24 +00005018 IsTrue = !PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005019 else // op == BO_GT || op == BO_GE
Richard Trieu560910c2012-11-14 22:50:24 +00005020 IsTrue = PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005021 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005022
5023 // If this is a comparison to an enum constant, include that
5024 // constant in the diagnostic.
5025 const EnumConstantDecl *ED = 0;
5026 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5027 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5028
5029 SmallString<64> PrettySourceValue;
5030 llvm::raw_svector_ostream OS(PrettySourceValue);
5031 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00005032 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005033 else
5034 OS << Value;
5035
Richard Trieuc38786b2014-01-10 04:38:09 +00005036 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5037 S.PDiag(diag::warn_out_of_range_compare)
5038 << OS.str() << OtherT << IsTrue
5039 << E->getLHS()->getSourceRange()
5040 << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005041}
5042
John McCallcc7e5bf2010-05-06 08:58:33 +00005043/// Analyze the operands of the given comparison. Implements the
5044/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005045static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00005046 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5047 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00005048}
John McCall263a48b2010-01-04 23:31:57 +00005049
John McCallca01b222010-01-04 23:21:16 +00005050/// \brief Implements -Wsign-compare.
5051///
Richard Trieu82402a02011-09-15 21:56:47 +00005052/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005053static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005054 // The type the comparison is being performed in.
5055 QualType T = E->getLHS()->getType();
5056 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5057 && "comparison with mismatched types");
Fariborz Jahanian282071e2012-09-18 17:46:26 +00005058 if (E->isValueDependent())
5059 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005060
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005061 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5062 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005063
5064 bool IsComparisonConstant = false;
5065
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005066 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005067 // of 'true' or 'false'.
5068 if (T->isIntegralType(S.Context)) {
5069 llvm::APSInt RHSValue;
5070 bool IsRHSIntegralLiteral =
5071 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5072 llvm::APSInt LHSValue;
5073 bool IsLHSIntegralLiteral =
5074 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5075 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5076 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5077 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5078 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5079 else
5080 IsComparisonConstant =
5081 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005082 } else if (!T->hasUnsignedIntegerRepresentation())
5083 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005084
John McCallcc7e5bf2010-05-06 08:58:33 +00005085 // We don't do anything special if this isn't an unsigned integral
5086 // comparison: we're only interested in integral comparisons, and
5087 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00005088 //
5089 // We also don't care about value-dependent expressions or expressions
5090 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005091 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00005092 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005093
John McCallcc7e5bf2010-05-06 08:58:33 +00005094 // Check to see if one of the (unmodified) operands is of different
5095 // signedness.
5096 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00005097 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5098 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00005099 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00005100 signedOperand = LHS;
5101 unsignedOperand = RHS;
5102 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5103 signedOperand = RHS;
5104 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00005105 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00005106 CheckTrivialUnsignedComparison(S, E);
5107 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005108 }
5109
John McCallcc7e5bf2010-05-06 08:58:33 +00005110 // Otherwise, calculate the effective range of the signed operand.
5111 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00005112
John McCallcc7e5bf2010-05-06 08:58:33 +00005113 // Go ahead and analyze implicit conversions in the operands. Note
5114 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00005115 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5116 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00005117
John McCallcc7e5bf2010-05-06 08:58:33 +00005118 // If the signed range is non-negative, -Wsign-compare won't fire,
5119 // but we should still check for comparisons which are always true
5120 // or false.
5121 if (signedRange.NonNegative)
5122 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005123
5124 // For (in)equality comparisons, if the unsigned operand is a
5125 // constant which cannot collide with a overflowed signed operand,
5126 // then reinterpreting the signed operand as unsigned will not
5127 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00005128 if (E->isEqualityOp()) {
5129 unsigned comparisonWidth = S.Context.getIntWidth(T);
5130 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00005131
John McCallcc7e5bf2010-05-06 08:58:33 +00005132 // We should never be unable to prove that the unsigned operand is
5133 // non-negative.
5134 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5135
5136 if (unsignedRange.Width < comparisonWidth)
5137 return;
5138 }
5139
Douglas Gregorbfb4a212012-05-01 01:53:49 +00005140 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5141 S.PDiag(diag::warn_mixed_sign_comparison)
5142 << LHS->getType() << RHS->getType()
5143 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00005144}
5145
John McCall1f425642010-11-11 03:21:53 +00005146/// Analyzes an attempt to assign the given value to a bitfield.
5147///
5148/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005149static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5150 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00005151 assert(Bitfield->isBitField());
5152 if (Bitfield->isInvalidDecl())
5153 return false;
5154
John McCalldeebbcf2010-11-11 05:33:51 +00005155 // White-list bool bitfields.
5156 if (Bitfield->getType()->isBooleanType())
5157 return false;
5158
Douglas Gregor789adec2011-02-04 13:09:01 +00005159 // Ignore value- or type-dependent expressions.
5160 if (Bitfield->getBitWidth()->isValueDependent() ||
5161 Bitfield->getBitWidth()->isTypeDependent() ||
5162 Init->isValueDependent() ||
5163 Init->isTypeDependent())
5164 return false;
5165
John McCall1f425642010-11-11 03:21:53 +00005166 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5167
Richard Smith5fab0c92011-12-28 19:48:30 +00005168 llvm::APSInt Value;
5169 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00005170 return false;
5171
John McCall1f425642010-11-11 03:21:53 +00005172 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00005173 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00005174
5175 if (OriginalWidth <= FieldWidth)
5176 return false;
5177
Eli Friedmanc267a322012-01-26 23:11:39 +00005178 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005179 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00005180 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00005181
Eli Friedmanc267a322012-01-26 23:11:39 +00005182 // Check whether the stored value is equal to the original value.
5183 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00005184 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00005185 return false;
5186
Eli Friedmanc267a322012-01-26 23:11:39 +00005187 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00005188 // therefore don't strictly fit into a signed bitfield of width 1.
5189 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00005190 return false;
5191
John McCall1f425642010-11-11 03:21:53 +00005192 std::string PrettyValue = Value.toString(10);
5193 std::string PrettyTrunc = TruncatedValue.toString(10);
5194
5195 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5196 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5197 << Init->getSourceRange();
5198
5199 return true;
5200}
5201
John McCalld2a53122010-11-09 23:24:47 +00005202/// Analyze the given simple or compound assignment for warning-worthy
5203/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005204static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00005205 // Just recurse on the LHS.
5206 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5207
5208 // We want to recurse on the RHS as normal unless we're assigning to
5209 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00005210 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005211 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00005212 E->getOperatorLoc())) {
5213 // Recurse, ignoring any implicit conversions on the RHS.
5214 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5215 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00005216 }
5217 }
5218
5219 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5220}
5221
John McCall263a48b2010-01-04 23:31:57 +00005222/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005223static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005224 SourceLocation CContext, unsigned diag,
5225 bool pruneControlFlow = false) {
5226 if (pruneControlFlow) {
5227 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5228 S.PDiag(diag)
5229 << SourceType << T << E->getSourceRange()
5230 << SourceRange(CContext));
5231 return;
5232 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00005233 S.Diag(E->getExprLoc(), diag)
5234 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5235}
5236
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005237/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005238static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005239 SourceLocation CContext, unsigned diag,
5240 bool pruneControlFlow = false) {
5241 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005242}
5243
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005244/// Diagnose an implicit cast from a literal expression. Does not warn when the
5245/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00005246void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5247 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005248 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00005249 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005250 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00005251 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5252 T->hasUnsignedIntegerRepresentation());
5253 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00005254 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005255 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00005256 return;
5257
Eli Friedman07185912013-08-29 23:44:43 +00005258 // FIXME: Force the precision of the source value down so we don't print
5259 // digits which are usually useless (we don't really care here if we
5260 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5261 // would automatically print the shortest representation, but it's a bit
5262 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00005263 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00005264 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5265 precision = (precision * 59 + 195) / 196;
5266 Value.toString(PrettySourceValue, precision);
5267
David Blaikie9b88cc02012-05-15 17:18:27 +00005268 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00005269 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5270 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5271 else
David Blaikie9b88cc02012-05-15 17:18:27 +00005272 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00005273
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005274 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00005275 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5276 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00005277}
5278
John McCall18a2c2c2010-11-09 22:22:12 +00005279std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5280 if (!Range.Width) return "0";
5281
5282 llvm::APSInt ValueInRange = Value;
5283 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00005284 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00005285 return ValueInRange.toString(10);
5286}
5287
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005288static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5289 if (!isa<ImplicitCastExpr>(Ex))
5290 return false;
5291
5292 Expr *InnerE = Ex->IgnoreParenImpCasts();
5293 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5294 const Type *Source =
5295 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5296 if (Target->isDependentType())
5297 return false;
5298
5299 const BuiltinType *FloatCandidateBT =
5300 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5301 const Type *BoolCandidateType = ToBool ? Target : Source;
5302
5303 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5304 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5305}
5306
5307void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5308 SourceLocation CC) {
5309 unsigned NumArgs = TheCall->getNumArgs();
5310 for (unsigned i = 0; i < NumArgs; ++i) {
5311 Expr *CurrA = TheCall->getArg(i);
5312 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5313 continue;
5314
5315 bool IsSwapped = ((i > 0) &&
5316 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5317 IsSwapped |= ((i < (NumArgs - 1)) &&
5318 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5319 if (IsSwapped) {
5320 // Warn on this floating-point to bool conversion.
5321 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5322 CurrA->getType(), CC,
5323 diag::warn_impcast_floating_point_to_bool);
5324 }
5325 }
5326}
5327
John McCallcc7e5bf2010-05-06 08:58:33 +00005328void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005329 SourceLocation CC, bool *ICContext = 0) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005330 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00005331
John McCallcc7e5bf2010-05-06 08:58:33 +00005332 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5333 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5334 if (Source == Target) return;
5335 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00005336
Chandler Carruthc22845a2011-07-26 05:40:03 +00005337 // If the conversion context location is invalid don't complain. We also
5338 // don't want to emit a warning if the issue occurs from the expansion of
5339 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5340 // delay this check as long as possible. Once we detect we are in that
5341 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005342 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00005343 return;
5344
Richard Trieu021baa32011-09-23 20:10:00 +00005345 // Diagnose implicit casts to bool.
5346 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5347 if (isa<StringLiteral>(E))
5348 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00005349 // and expressions, for instance, assert(0 && "error here"), are
5350 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00005351 return DiagnoseImpCast(S, E, T, CC,
5352 diag::warn_impcast_string_literal_to_bool);
Lang Hamesdf5c1212011-12-05 20:49:50 +00005353 if (Source->isFunctionType()) {
5354 // Warn on function to bool. Checks free functions and static member
5355 // functions. Weakly imported functions are excluded from the check,
5356 // since it's common to test their value to check whether the linker
5357 // found a definition for them.
5358 ValueDecl *D = 0;
5359 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
5360 D = R->getDecl();
5361 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
5362 D = M->getMemberDecl();
5363 }
5364
5365 if (D && !D->isWeak()) {
Richard Trieu5f623222011-12-06 04:48:01 +00005366 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
5367 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
5368 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie10eb4b62011-12-09 21:42:37 +00005369 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
5370 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
5371 QualType ReturnType;
5372 UnresolvedSet<4> NonTemplateOverloads;
David Blaikiee5323aa2013-06-21 23:54:45 +00005373 S.tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
David Blaikie10eb4b62011-12-09 21:42:37 +00005374 if (!ReturnType.isNull()
5375 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
5376 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
5377 << FixItHint::CreateInsertion(
5378 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu5f623222011-12-06 04:48:01 +00005379 return;
5380 }
Lang Hamesdf5c1212011-12-05 20:49:50 +00005381 }
5382 }
Richard Trieu021baa32011-09-23 20:10:00 +00005383 }
John McCall263a48b2010-01-04 23:31:57 +00005384
5385 // Strip vector types.
5386 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005387 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005388 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005389 return;
John McCallacf0ee52010-10-08 02:01:28 +00005390 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005391 }
Chris Lattneree7286f2011-06-14 04:51:15 +00005392
5393 // If the vector cast is cast between two vectors of the same size, it is
5394 // a bitcast, not a conversion.
5395 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5396 return;
John McCall263a48b2010-01-04 23:31:57 +00005397
5398 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5399 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5400 }
5401
5402 // Strip complex types.
5403 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005404 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005405 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005406 return;
5407
John McCallacf0ee52010-10-08 02:01:28 +00005408 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005409 }
John McCall263a48b2010-01-04 23:31:57 +00005410
5411 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5412 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5413 }
5414
5415 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5416 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5417
5418 // If the source is floating point...
5419 if (SourceBT && SourceBT->isFloatingPoint()) {
5420 // ...and the target is floating point...
5421 if (TargetBT && TargetBT->isFloatingPoint()) {
5422 // ...then warn if we're dropping FP rank.
5423
5424 // Builtin FP kinds are ordered by increasing FP rank.
5425 if (SourceBT->getKind() > TargetBT->getKind()) {
5426 // Don't warn about float constants that are precisely
5427 // representable in the target type.
5428 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005429 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00005430 // Value might be a float, a float vector, or a float complex.
5431 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00005432 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5433 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00005434 return;
5435 }
5436
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005437 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005438 return;
5439
John McCallacf0ee52010-10-08 02:01:28 +00005440 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00005441 }
5442 return;
5443 }
5444
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005445 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00005446 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005447 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005448 return;
5449
Chandler Carruth22c7a792011-02-17 11:05:49 +00005450 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00005451 // We also want to warn on, e.g., "int i = -1.234"
5452 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5453 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5454 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5455
Chandler Carruth016ef402011-04-10 08:36:24 +00005456 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5457 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00005458 } else {
5459 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5460 }
5461 }
John McCall263a48b2010-01-04 23:31:57 +00005462
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005463 // If the target is bool, warn if expr is a function or method call.
5464 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5465 isa<CallExpr>(E)) {
5466 // Check last argument of function call to see if it is an
5467 // implicit cast from a type matching the type the result
5468 // is being cast to.
5469 CallExpr *CEx = cast<CallExpr>(E);
5470 unsigned NumArgs = CEx->getNumArgs();
5471 if (NumArgs > 0) {
5472 Expr *LastA = CEx->getArg(NumArgs - 1);
5473 Expr *InnerE = LastA->IgnoreParenImpCasts();
5474 const Type *InnerType =
5475 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5476 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5477 // Warn on this floating-point to bool conversion
5478 DiagnoseImpCast(S, E, T, CC,
5479 diag::warn_impcast_floating_point_to_bool);
5480 }
5481 }
5482 }
John McCall263a48b2010-01-04 23:31:57 +00005483 return;
5484 }
5485
Richard Trieubeaf3452011-05-29 19:59:02 +00005486 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikie9366d2b2012-06-19 21:19:06 +00005487 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiea1edff02012-11-08 00:41:20 +00005488 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikiebcd4b552013-02-16 00:56:22 +00005489 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieae12b182012-03-16 20:30:12 +00005490 SourceLocation Loc = E->getSourceRange().getBegin();
5491 if (Loc.isMacroID())
5492 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie18e9ac72012-05-15 21:57:38 +00005493 if (!Loc.isMacroID() || CC.isMacroID())
5494 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5495 << T << clang::SourceRange(CC)
Richard Smithf7ec86a2013-09-20 00:27:40 +00005496 << FixItHint::CreateReplacement(Loc,
5497 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieubeaf3452011-05-29 19:59:02 +00005498 }
5499
David Blaikie9366d2b2012-06-19 21:19:06 +00005500 if (!Source->isIntegerType() || !Target->isIntegerType())
5501 return;
5502
David Blaikie7555b6a2012-05-15 16:56:36 +00005503 // TODO: remove this early return once the false positives for constant->bool
5504 // in templates, macros, etc, are reduced or removed.
5505 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5506 return;
5507
John McCallcc7e5bf2010-05-06 08:58:33 +00005508 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00005509 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00005510
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005511 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00005512 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005513 // TODO: this should happen for bitfield stores, too.
5514 llvm::APSInt Value(32);
5515 if (E->isIntegerConstantExpr(Value, S.Context)) {
5516 if (S.SourceMgr.isInSystemMacro(CC))
5517 return;
5518
John McCall18a2c2c2010-11-09 22:22:12 +00005519 std::string PrettySourceValue = Value.toString(10);
5520 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005521
Ted Kremenek33ba9952011-10-22 02:37:33 +00005522 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5523 S.PDiag(diag::warn_impcast_integer_precision_constant)
5524 << PrettySourceValue << PrettyTargetValue
5525 << E->getType() << T << E->getSourceRange()
5526 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00005527 return;
5528 }
5529
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005530 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5531 if (S.SourceMgr.isInSystemMacro(CC))
5532 return;
5533
David Blaikie9455da02012-04-12 22:40:54 +00005534 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00005535 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5536 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00005537 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00005538 }
5539
5540 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5541 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5542 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005543
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005544 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005545 return;
5546
John McCallcc7e5bf2010-05-06 08:58:33 +00005547 unsigned DiagID = diag::warn_impcast_integer_sign;
5548
5549 // Traditionally, gcc has warned about this under -Wsign-compare.
5550 // We also want to warn about it in -Wconversion.
5551 // So if -Wconversion is off, use a completely identical diagnostic
5552 // in the sign-compare group.
5553 // The conditional-checking code will
5554 if (ICContext) {
5555 DiagID = diag::warn_impcast_integer_sign_conditional;
5556 *ICContext = true;
5557 }
5558
John McCallacf0ee52010-10-08 02:01:28 +00005559 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00005560 }
5561
Douglas Gregora78f1932011-02-22 02:45:07 +00005562 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00005563 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5564 // type, to give us better diagnostics.
5565 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005566 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00005567 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5568 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5569 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5570 SourceType = S.Context.getTypeDeclType(Enum);
5571 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5572 }
5573 }
5574
Douglas Gregora78f1932011-02-22 02:45:07 +00005575 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5576 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00005577 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5578 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005579 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005580 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005581 return;
5582
Douglas Gregor364f7db2011-03-12 00:14:31 +00005583 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00005584 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005585 }
Douglas Gregora78f1932011-02-22 02:45:07 +00005586
John McCall263a48b2010-01-04 23:31:57 +00005587 return;
5588}
5589
David Blaikie18e9ac72012-05-15 21:57:38 +00005590void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5591 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00005592
5593void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00005594 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005595 E = E->IgnoreParenImpCasts();
5596
5597 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00005598 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00005599
John McCallacf0ee52010-10-08 02:01:28 +00005600 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005601 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00005602 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00005603 return;
5604}
5605
David Blaikie18e9ac72012-05-15 21:57:38 +00005606void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5607 SourceLocation CC, QualType T) {
John McCallacf0ee52010-10-08 02:01:28 +00005608 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005609
5610 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00005611 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5612 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00005613
5614 // If -Wconversion would have warned about either of the candidates
5615 // for a signedness conversion to the context type...
5616 if (!Suspicious) return;
5617
5618 // ...but it's currently ignored...
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005619 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5620 CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00005621 return;
5622
John McCallcc7e5bf2010-05-06 08:58:33 +00005623 // ...then check whether it would have warned about either of the
5624 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00005625 if (E->getType() == T) return;
5626
5627 Suspicious = false;
5628 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5629 E->getType(), CC, &Suspicious);
5630 if (!Suspicious)
5631 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00005632 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00005633}
5634
5635/// AnalyzeImplicitConversions - Find and report any interesting
5636/// implicit conversions in the given expression. There are a couple
5637/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00005638void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005639 QualType T = OrigE->getType();
5640 Expr *E = OrigE->IgnoreParenImpCasts();
5641
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00005642 if (E->isTypeDependent() || E->isValueDependent())
5643 return;
5644
John McCallcc7e5bf2010-05-06 08:58:33 +00005645 // For conditional operators, we analyze the arguments as if they
5646 // were being fed directly into the output.
5647 if (isa<ConditionalOperator>(E)) {
5648 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00005649 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00005650 return;
5651 }
5652
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005653 // Check implicit argument conversions for function calls.
5654 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5655 CheckImplicitArgumentConversions(S, Call, CC);
5656
John McCallcc7e5bf2010-05-06 08:58:33 +00005657 // Go ahead and check any implicit conversions we might have skipped.
5658 // The non-canonical typecheck is just an optimization;
5659 // CheckImplicitConversion will filter out dead implicit conversions.
5660 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00005661 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005662
5663 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00005664
5665 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00005666 if (POE->getResultExpr())
5667 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00005668 }
5669
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00005670 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5671 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5672
John McCallcc7e5bf2010-05-06 08:58:33 +00005673 // Skip past explicit casts.
5674 if (isa<ExplicitCastExpr>(E)) {
5675 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00005676 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005677 }
5678
John McCalld2a53122010-11-09 23:24:47 +00005679 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5680 // Do a somewhat different check with comparison operators.
5681 if (BO->isComparisonOp())
5682 return AnalyzeComparison(S, BO);
5683
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005684 // And with simple assignments.
5685 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00005686 return AnalyzeAssignment(S, BO);
5687 }
John McCallcc7e5bf2010-05-06 08:58:33 +00005688
5689 // These break the otherwise-useful invariant below. Fortunately,
5690 // we don't really need to recurse into them, because any internal
5691 // expressions should have been analyzed already when they were
5692 // built into statements.
5693 if (isa<StmtExpr>(E)) return;
5694
5695 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00005696 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00005697
5698 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00005699 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00005700 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00005701 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00005702 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00005703 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00005704 if (!ChildExpr)
5705 continue;
5706
Richard Trieu955231d2014-01-25 01:10:35 +00005707 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00005708 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00005709 // Ignore checking string literals that are in logical and operators.
5710 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00005711 continue;
5712 AnalyzeImplicitConversions(S, ChildExpr, CC);
5713 }
John McCallcc7e5bf2010-05-06 08:58:33 +00005714}
5715
5716} // end anonymous namespace
5717
5718/// Diagnoses "dangerous" implicit conversions within the given
5719/// expression (which is a full expression). Implements -Wconversion
5720/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00005721///
5722/// \param CC the "context" location of the implicit conversion, i.e.
5723/// the most location of the syntactic entity requiring the implicit
5724/// conversion
5725void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005726 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00005727 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00005728 return;
5729
5730 // Don't diagnose for value- or type-dependent expressions.
5731 if (E->isTypeDependent() || E->isValueDependent())
5732 return;
5733
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00005734 // Check for array bounds violations in cases where the check isn't triggered
5735 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5736 // ArraySubscriptExpr is on the RHS of a variable initialization.
5737 CheckArrayAccess(E);
5738
John McCallacf0ee52010-10-08 02:01:28 +00005739 // This is not the right CC for (e.g.) a variable initialization.
5740 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005741}
5742
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00005743/// Diagnose when expression is an integer constant expression and its evaluation
5744/// results in integer overflow
5745void Sema::CheckForIntOverflow (Expr *E) {
Richard Smithe9ff7702013-11-05 22:23:30 +00005746 if (isa<BinaryOperator>(E->IgnoreParens()))
5747 E->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00005748}
5749
Richard Smithc406cb72013-01-17 01:17:56 +00005750namespace {
5751/// \brief Visitor for expressions which looks for unsequenced operations on the
5752/// same object.
5753class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00005754 typedef EvaluatedExprVisitor<SequenceChecker> Base;
5755
Richard Smithc406cb72013-01-17 01:17:56 +00005756 /// \brief A tree of sequenced regions within an expression. Two regions are
5757 /// unsequenced if one is an ancestor or a descendent of the other. When we
5758 /// finish processing an expression with sequencing, such as a comma
5759 /// expression, we fold its tree nodes into its parent, since they are
5760 /// unsequenced with respect to nodes we will visit later.
5761 class SequenceTree {
5762 struct Value {
5763 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5764 unsigned Parent : 31;
5765 bool Merged : 1;
5766 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005767 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00005768
5769 public:
5770 /// \brief A region within an expression which may be sequenced with respect
5771 /// to some other region.
5772 class Seq {
5773 explicit Seq(unsigned N) : Index(N) {}
5774 unsigned Index;
5775 friend class SequenceTree;
5776 public:
5777 Seq() : Index(0) {}
5778 };
5779
5780 SequenceTree() { Values.push_back(Value(0)); }
5781 Seq root() const { return Seq(0); }
5782
5783 /// \brief Create a new sequence of operations, which is an unsequenced
5784 /// subset of \p Parent. This sequence of operations is sequenced with
5785 /// respect to other children of \p Parent.
5786 Seq allocate(Seq Parent) {
5787 Values.push_back(Value(Parent.Index));
5788 return Seq(Values.size() - 1);
5789 }
5790
5791 /// \brief Merge a sequence of operations into its parent.
5792 void merge(Seq S) {
5793 Values[S.Index].Merged = true;
5794 }
5795
5796 /// \brief Determine whether two operations are unsequenced. This operation
5797 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5798 /// should have been merged into its parent as appropriate.
5799 bool isUnsequenced(Seq Cur, Seq Old) {
5800 unsigned C = representative(Cur.Index);
5801 unsigned Target = representative(Old.Index);
5802 while (C >= Target) {
5803 if (C == Target)
5804 return true;
5805 C = Values[C].Parent;
5806 }
5807 return false;
5808 }
5809
5810 private:
5811 /// \brief Pick a representative for a sequence.
5812 unsigned representative(unsigned K) {
5813 if (Values[K].Merged)
5814 // Perform path compression as we go.
5815 return Values[K].Parent = representative(Values[K].Parent);
5816 return K;
5817 }
5818 };
5819
5820 /// An object for which we can track unsequenced uses.
5821 typedef NamedDecl *Object;
5822
5823 /// Different flavors of object usage which we track. We only track the
5824 /// least-sequenced usage of each kind.
5825 enum UsageKind {
5826 /// A read of an object. Multiple unsequenced reads are OK.
5827 UK_Use,
5828 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00005829 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00005830 UK_ModAsValue,
5831 /// A modification of an object which is not sequenced before the value
5832 /// computation of the expression, such as n++.
5833 UK_ModAsSideEffect,
5834
5835 UK_Count = UK_ModAsSideEffect + 1
5836 };
5837
5838 struct Usage {
5839 Usage() : Use(0), Seq() {}
5840 Expr *Use;
5841 SequenceTree::Seq Seq;
5842 };
5843
5844 struct UsageInfo {
5845 UsageInfo() : Diagnosed(false) {}
5846 Usage Uses[UK_Count];
5847 /// Have we issued a diagnostic for this variable already?
5848 bool Diagnosed;
5849 };
5850 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5851
5852 Sema &SemaRef;
5853 /// Sequenced regions within the expression.
5854 SequenceTree Tree;
5855 /// Declaration modifications and references which we have seen.
5856 UsageInfoMap UsageMap;
5857 /// The region we are currently within.
5858 SequenceTree::Seq Region;
5859 /// Filled in with declarations which were modified as a side-effect
5860 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005861 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00005862 /// Expressions to check later. We defer checking these to reduce
5863 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005864 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00005865
5866 /// RAII object wrapping the visitation of a sequenced subexpression of an
5867 /// expression. At the end of this process, the side-effects of the evaluation
5868 /// become sequenced with respect to the value computation of the result, so
5869 /// we downgrade any UK_ModAsSideEffect within the evaluation to
5870 /// UK_ModAsValue.
5871 struct SequencedSubexpression {
5872 SequencedSubexpression(SequenceChecker &Self)
5873 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5874 Self.ModAsSideEffect = &ModAsSideEffect;
5875 }
5876 ~SequencedSubexpression() {
5877 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5878 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5879 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5880 Self.addUsage(U, ModAsSideEffect[I].first,
5881 ModAsSideEffect[I].second.Use, UK_ModAsValue);
5882 }
5883 Self.ModAsSideEffect = OldModAsSideEffect;
5884 }
5885
5886 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005887 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5888 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00005889 };
5890
Richard Smith40238f02013-06-20 22:21:56 +00005891 /// RAII object wrapping the visitation of a subexpression which we might
5892 /// choose to evaluate as a constant. If any subexpression is evaluated and
5893 /// found to be non-constant, this allows us to suppress the evaluation of
5894 /// the outer expression.
5895 class EvaluationTracker {
5896 public:
5897 EvaluationTracker(SequenceChecker &Self)
5898 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
5899 Self.EvalTracker = this;
5900 }
5901 ~EvaluationTracker() {
5902 Self.EvalTracker = Prev;
5903 if (Prev)
5904 Prev->EvalOK &= EvalOK;
5905 }
5906
5907 bool evaluate(const Expr *E, bool &Result) {
5908 if (!EvalOK || E->isValueDependent())
5909 return false;
5910 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
5911 return EvalOK;
5912 }
5913
5914 private:
5915 SequenceChecker &Self;
5916 EvaluationTracker *Prev;
5917 bool EvalOK;
5918 } *EvalTracker;
5919
Richard Smithc406cb72013-01-17 01:17:56 +00005920 /// \brief Find the object which is produced by the specified expression,
5921 /// if any.
5922 Object getObject(Expr *E, bool Mod) const {
5923 E = E->IgnoreParenCasts();
5924 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5925 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5926 return getObject(UO->getSubExpr(), Mod);
5927 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5928 if (BO->getOpcode() == BO_Comma)
5929 return getObject(BO->getRHS(), Mod);
5930 if (Mod && BO->isAssignmentOp())
5931 return getObject(BO->getLHS(), Mod);
5932 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5933 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5934 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5935 return ME->getMemberDecl();
5936 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5937 // FIXME: If this is a reference, map through to its value.
5938 return DRE->getDecl();
5939 return 0;
5940 }
5941
5942 /// \brief Note that an object was modified or used by an expression.
5943 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5944 Usage &U = UI.Uses[UK];
5945 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5946 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5947 ModAsSideEffect->push_back(std::make_pair(O, U));
5948 U.Use = Ref;
5949 U.Seq = Region;
5950 }
5951 }
5952 /// \brief Check whether a modification or use conflicts with a prior usage.
5953 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5954 bool IsModMod) {
5955 if (UI.Diagnosed)
5956 return;
5957
5958 const Usage &U = UI.Uses[OtherKind];
5959 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5960 return;
5961
5962 Expr *Mod = U.Use;
5963 Expr *ModOrUse = Ref;
5964 if (OtherKind == UK_Use)
5965 std::swap(Mod, ModOrUse);
5966
5967 SemaRef.Diag(Mod->getExprLoc(),
5968 IsModMod ? diag::warn_unsequenced_mod_mod
5969 : diag::warn_unsequenced_mod_use)
5970 << O << SourceRange(ModOrUse->getExprLoc());
5971 UI.Diagnosed = true;
5972 }
5973
5974 void notePreUse(Object O, Expr *Use) {
5975 UsageInfo &U = UsageMap[O];
5976 // Uses conflict with other modifications.
5977 checkUsage(O, U, Use, UK_ModAsValue, false);
5978 }
5979 void notePostUse(Object O, Expr *Use) {
5980 UsageInfo &U = UsageMap[O];
5981 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5982 addUsage(U, O, Use, UK_Use);
5983 }
5984
5985 void notePreMod(Object O, Expr *Mod) {
5986 UsageInfo &U = UsageMap[O];
5987 // Modifications conflict with other modifications and with uses.
5988 checkUsage(O, U, Mod, UK_ModAsValue, true);
5989 checkUsage(O, U, Mod, UK_Use, false);
5990 }
5991 void notePostMod(Object O, Expr *Use, UsageKind UK) {
5992 UsageInfo &U = UsageMap[O];
5993 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5994 addUsage(U, O, Use, UK);
5995 }
5996
5997public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005998 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
5999 : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
6000 WorkList(WorkList), EvalTracker(0) {
Richard Smithc406cb72013-01-17 01:17:56 +00006001 Visit(E);
6002 }
6003
6004 void VisitStmt(Stmt *S) {
6005 // Skip all statements which aren't expressions for now.
6006 }
6007
6008 void VisitExpr(Expr *E) {
6009 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00006010 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006011 }
6012
6013 void VisitCastExpr(CastExpr *E) {
6014 Object O = Object();
6015 if (E->getCastKind() == CK_LValueToRValue)
6016 O = getObject(E->getSubExpr(), false);
6017
6018 if (O)
6019 notePreUse(O, E);
6020 VisitExpr(E);
6021 if (O)
6022 notePostUse(O, E);
6023 }
6024
6025 void VisitBinComma(BinaryOperator *BO) {
6026 // C++11 [expr.comma]p1:
6027 // Every value computation and side effect associated with the left
6028 // expression is sequenced before every value computation and side
6029 // effect associated with the right expression.
6030 SequenceTree::Seq LHS = Tree.allocate(Region);
6031 SequenceTree::Seq RHS = Tree.allocate(Region);
6032 SequenceTree::Seq OldRegion = Region;
6033
6034 {
6035 SequencedSubexpression SeqLHS(*this);
6036 Region = LHS;
6037 Visit(BO->getLHS());
6038 }
6039
6040 Region = RHS;
6041 Visit(BO->getRHS());
6042
6043 Region = OldRegion;
6044
6045 // Forget that LHS and RHS are sequenced. They are both unsequenced
6046 // with respect to other stuff.
6047 Tree.merge(LHS);
6048 Tree.merge(RHS);
6049 }
6050
6051 void VisitBinAssign(BinaryOperator *BO) {
6052 // The modification is sequenced after the value computation of the LHS
6053 // and RHS, so check it before inspecting the operands and update the
6054 // map afterwards.
6055 Object O = getObject(BO->getLHS(), true);
6056 if (!O)
6057 return VisitExpr(BO);
6058
6059 notePreMod(O, BO);
6060
6061 // C++11 [expr.ass]p7:
6062 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
6063 // only once.
6064 //
6065 // Therefore, for a compound assignment operator, O is considered used
6066 // everywhere except within the evaluation of E1 itself.
6067 if (isa<CompoundAssignOperator>(BO))
6068 notePreUse(O, BO);
6069
6070 Visit(BO->getLHS());
6071
6072 if (isa<CompoundAssignOperator>(BO))
6073 notePostUse(O, BO);
6074
6075 Visit(BO->getRHS());
6076
Richard Smith83e37bee2013-06-26 23:16:51 +00006077 // C++11 [expr.ass]p1:
6078 // the assignment is sequenced [...] before the value computation of the
6079 // assignment expression.
6080 // C11 6.5.16/3 has no such rule.
6081 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6082 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006083 }
6084 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6085 VisitBinAssign(CAO);
6086 }
6087
6088 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6089 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6090 void VisitUnaryPreIncDec(UnaryOperator *UO) {
6091 Object O = getObject(UO->getSubExpr(), true);
6092 if (!O)
6093 return VisitExpr(UO);
6094
6095 notePreMod(O, UO);
6096 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00006097 // C++11 [expr.pre.incr]p1:
6098 // the expression ++x is equivalent to x+=1
6099 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6100 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006101 }
6102
6103 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6104 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6105 void VisitUnaryPostIncDec(UnaryOperator *UO) {
6106 Object O = getObject(UO->getSubExpr(), true);
6107 if (!O)
6108 return VisitExpr(UO);
6109
6110 notePreMod(O, UO);
6111 Visit(UO->getSubExpr());
6112 notePostMod(O, UO, UK_ModAsSideEffect);
6113 }
6114
6115 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6116 void VisitBinLOr(BinaryOperator *BO) {
6117 // The side-effects of the LHS of an '&&' are sequenced before the
6118 // value computation of the RHS, and hence before the value computation
6119 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6120 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00006121 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006122 {
6123 SequencedSubexpression Sequenced(*this);
6124 Visit(BO->getLHS());
6125 }
6126
6127 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006128 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006129 if (!Result)
6130 Visit(BO->getRHS());
6131 } else {
6132 // Check for unsequenced operations in the RHS, treating it as an
6133 // entirely separate evaluation.
6134 //
6135 // FIXME: If there are operations in the RHS which are unsequenced
6136 // with respect to operations outside the RHS, and those operations
6137 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00006138 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006139 }
Richard Smithc406cb72013-01-17 01:17:56 +00006140 }
6141 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00006142 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006143 {
6144 SequencedSubexpression Sequenced(*this);
6145 Visit(BO->getLHS());
6146 }
6147
6148 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006149 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006150 if (Result)
6151 Visit(BO->getRHS());
6152 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00006153 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006154 }
Richard Smithc406cb72013-01-17 01:17:56 +00006155 }
6156
6157 // Only visit the condition, unless we can be sure which subexpression will
6158 // be chosen.
6159 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00006160 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00006161 {
6162 SequencedSubexpression Sequenced(*this);
6163 Visit(CO->getCond());
6164 }
Richard Smithc406cb72013-01-17 01:17:56 +00006165
6166 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006167 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00006168 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006169 else {
Richard Smithd33f5202013-01-17 23:18:09 +00006170 WorkList.push_back(CO->getTrueExpr());
6171 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006172 }
Richard Smithc406cb72013-01-17 01:17:56 +00006173 }
6174
Richard Smithe3dbfe02013-06-30 10:40:20 +00006175 void VisitCallExpr(CallExpr *CE) {
6176 // C++11 [intro.execution]p15:
6177 // When calling a function [...], every value computation and side effect
6178 // associated with any argument expression, or with the postfix expression
6179 // designating the called function, is sequenced before execution of every
6180 // expression or statement in the body of the function [and thus before
6181 // the value computation of its result].
6182 SequencedSubexpression Sequenced(*this);
6183 Base::VisitCallExpr(CE);
6184
6185 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6186 }
6187
Richard Smithc406cb72013-01-17 01:17:56 +00006188 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006189 // This is a call, so all subexpressions are sequenced before the result.
6190 SequencedSubexpression Sequenced(*this);
6191
Richard Smithc406cb72013-01-17 01:17:56 +00006192 if (!CCE->isListInitialization())
6193 return VisitExpr(CCE);
6194
6195 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006196 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006197 SequenceTree::Seq Parent = Region;
6198 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6199 E = CCE->arg_end();
6200 I != E; ++I) {
6201 Region = Tree.allocate(Parent);
6202 Elts.push_back(Region);
6203 Visit(*I);
6204 }
6205
6206 // Forget that the initializers are sequenced.
6207 Region = Parent;
6208 for (unsigned I = 0; I < Elts.size(); ++I)
6209 Tree.merge(Elts[I]);
6210 }
6211
6212 void VisitInitListExpr(InitListExpr *ILE) {
6213 if (!SemaRef.getLangOpts().CPlusPlus11)
6214 return VisitExpr(ILE);
6215
6216 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006217 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006218 SequenceTree::Seq Parent = Region;
6219 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6220 Expr *E = ILE->getInit(I);
6221 if (!E) continue;
6222 Region = Tree.allocate(Parent);
6223 Elts.push_back(Region);
6224 Visit(E);
6225 }
6226
6227 // Forget that the initializers are sequenced.
6228 Region = Parent;
6229 for (unsigned I = 0; I < Elts.size(); ++I)
6230 Tree.merge(Elts[I]);
6231 }
6232};
6233}
6234
6235void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006236 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00006237 WorkList.push_back(E);
6238 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00006239 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00006240 SequenceChecker(*this, Item, WorkList);
6241 }
Richard Smithc406cb72013-01-17 01:17:56 +00006242}
6243
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006244void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6245 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006246 CheckImplicitConversions(E, CheckLoc);
6247 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006248 if (!IsConstexpr && !E->isValueDependent())
6249 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006250}
6251
John McCall1f425642010-11-11 03:21:53 +00006252void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6253 FieldDecl *BitField,
6254 Expr *Init) {
6255 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6256}
6257
Mike Stump0c2ec772010-01-21 03:59:47 +00006258/// CheckParmsForFunctionDef - Check that the parameters of the given
6259/// function are appropriate for the definition of a function. This
6260/// takes care of any checks that cannot be performed on the
6261/// declaration itself, e.g., that the types of each of the function
6262/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00006263bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6264 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00006265 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006266 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00006267 for (; P != PEnd; ++P) {
6268 ParmVarDecl *Param = *P;
6269
Mike Stump0c2ec772010-01-21 03:59:47 +00006270 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6271 // function declarator that is part of a function definition of
6272 // that function shall not have incomplete type.
6273 //
6274 // This is also C++ [dcl.fct]p6.
6275 if (!Param->isInvalidDecl() &&
6276 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006277 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006278 Param->setInvalidDecl();
6279 HasInvalidParm = true;
6280 }
6281
6282 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6283 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00006284 if (CheckParameterNames &&
6285 Param->getIdentifier() == 0 &&
Mike Stump0c2ec772010-01-21 03:59:47 +00006286 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006287 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00006288 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00006289
6290 // C99 6.7.5.3p12:
6291 // If the function declarator is not part of a definition of that
6292 // function, parameters may have incomplete type and may use the [*]
6293 // notation in their sequences of declarator specifiers to specify
6294 // variable length array types.
6295 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006296 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00006297 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00006298 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00006299 // information is added for it.
6300 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006301 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00006302 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006303 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00006304 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006305
6306 // MSVC destroys objects passed by value in the callee. Therefore a
6307 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006308 // object's destructor. However, we don't perform any direct access check
6309 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00006310 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
6311 .getCXXABI()
6312 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00006313 if (!Param->isInvalidDecl()) {
6314 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
6315 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
6316 if (!ClassDecl->isInvalidDecl() &&
6317 !ClassDecl->hasIrrelevantDestructor() &&
6318 !ClassDecl->isDependentContext()) {
6319 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6320 MarkFunctionReferenced(Param->getLocation(), Destructor);
6321 DiagnoseUseOfDecl(Destructor, Param->getLocation());
6322 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006323 }
6324 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006325 }
Mike Stump0c2ec772010-01-21 03:59:47 +00006326 }
6327
6328 return HasInvalidParm;
6329}
John McCall2b5c1b22010-08-12 21:44:57 +00006330
6331/// CheckCastAlign - Implements -Wcast-align, which warns when a
6332/// pointer cast increases the alignment requirements.
6333void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6334 // This is actually a lot of work to potentially be doing on every
6335 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00006336 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6337 TRange.getBegin())
David Blaikie9c902b52011-09-25 23:23:43 +00006338 == DiagnosticsEngine::Ignored)
John McCall2b5c1b22010-08-12 21:44:57 +00006339 return;
6340
6341 // Ignore dependent types.
6342 if (T->isDependentType() || Op->getType()->isDependentType())
6343 return;
6344
6345 // Require that the destination be a pointer type.
6346 const PointerType *DestPtr = T->getAs<PointerType>();
6347 if (!DestPtr) return;
6348
6349 // If the destination has alignment 1, we're done.
6350 QualType DestPointee = DestPtr->getPointeeType();
6351 if (DestPointee->isIncompleteType()) return;
6352 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6353 if (DestAlign.isOne()) return;
6354
6355 // Require that the source be a pointer type.
6356 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6357 if (!SrcPtr) return;
6358 QualType SrcPointee = SrcPtr->getPointeeType();
6359
6360 // Whitelist casts from cv void*. We already implicitly
6361 // whitelisted casts to cv void*, since they have alignment 1.
6362 // Also whitelist casts involving incomplete types, which implicitly
6363 // includes 'void'.
6364 if (SrcPointee->isIncompleteType()) return;
6365
6366 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6367 if (SrcAlign >= DestAlign) return;
6368
6369 Diag(TRange.getBegin(), diag::warn_cast_align)
6370 << Op->getType() << T
6371 << static_cast<unsigned>(SrcAlign.getQuantity())
6372 << static_cast<unsigned>(DestAlign.getQuantity())
6373 << TRange << Op->getSourceRange();
6374}
6375
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006376static const Type* getElementType(const Expr *BaseExpr) {
6377 const Type* EltType = BaseExpr->getType().getTypePtr();
6378 if (EltType->isAnyPointerType())
6379 return EltType->getPointeeType().getTypePtr();
6380 else if (EltType->isArrayType())
6381 return EltType->getBaseElementTypeUnsafe();
6382 return EltType;
6383}
6384
Chandler Carruth28389f02011-08-05 09:10:50 +00006385/// \brief Check whether this array fits the idiom of a size-one tail padded
6386/// array member of a struct.
6387///
6388/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6389/// commonly used to emulate flexible arrays in C89 code.
6390static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6391 const NamedDecl *ND) {
6392 if (Size != 1 || !ND) return false;
6393
6394 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6395 if (!FD) return false;
6396
6397 // Don't consider sizes resulting from macro expansions or template argument
6398 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00006399
6400 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006401 while (TInfo) {
6402 TypeLoc TL = TInfo->getTypeLoc();
6403 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00006404 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6405 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006406 TInfo = TDL->getTypeSourceInfo();
6407 continue;
6408 }
David Blaikie6adc78e2013-02-18 22:06:02 +00006409 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6410 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00006411 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6412 return false;
6413 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006414 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00006415 }
Chandler Carruth28389f02011-08-05 09:10:50 +00006416
6417 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00006418 if (!RD) return false;
6419 if (RD->isUnion()) return false;
6420 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6421 if (!CRD->isStandardLayout()) return false;
6422 }
Chandler Carruth28389f02011-08-05 09:10:50 +00006423
Benjamin Kramer8c543672011-08-06 03:04:42 +00006424 // See if this is the last field decl in the record.
6425 const Decl *D = FD;
6426 while ((D = D->getNextDeclInContext()))
6427 if (isa<FieldDecl>(D))
6428 return false;
6429 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00006430}
6431
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006432void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006433 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00006434 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006435 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006436 if (IndexExpr->isValueDependent())
6437 return;
6438
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00006439 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006440 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006441 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006442 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006443 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00006444 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00006445
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006446 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006447 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00006448 return;
Richard Smith13f67182011-12-16 19:31:14 +00006449 if (IndexNegated)
6450 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00006451
Chandler Carruth126b1552011-08-05 08:07:29 +00006452 const NamedDecl *ND = NULL;
Chandler Carruth126b1552011-08-05 08:07:29 +00006453 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6454 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00006455 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00006456 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00006457
Ted Kremeneke4b316c2011-02-23 23:06:04 +00006458 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006459 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00006460 if (!size.isStrictlyPositive())
6461 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006462
6463 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00006464 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006465 // Make sure we're comparing apples to apples when comparing index to size
6466 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6467 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00006468 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00006469 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006470 if (ptrarith_typesize != array_typesize) {
6471 // There's a cast to a different size type involved
6472 uint64_t ratio = array_typesize / ptrarith_typesize;
6473 // TODO: Be smarter about handling cases where array_typesize is not a
6474 // multiple of ptrarith_typesize
6475 if (ptrarith_typesize * ratio == array_typesize)
6476 size *= llvm::APInt(size.getBitWidth(), ratio);
6477 }
6478 }
6479
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006480 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006481 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006482 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006483 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006484
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006485 // For array subscripting the index must be less than size, but for pointer
6486 // arithmetic also allow the index (offset) to be equal to size since
6487 // computing the next address after the end of the array is legal and
6488 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006489 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00006490 return;
6491
6492 // Also don't warn for arrays of size 1 which are members of some
6493 // structure. These are often used to approximate flexible arrays in C89
6494 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006495 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00006496 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006497
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006498 // Suppress the warning if the subscript expression (as identified by the
6499 // ']' location) and the index expression are both from macro expansions
6500 // within a system header.
6501 if (ASE) {
6502 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6503 ASE->getRBracketLoc());
6504 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6505 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6506 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00006507 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006508 return;
6509 }
6510 }
6511
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006512 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006513 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006514 DiagID = diag::warn_array_index_exceeds_bounds;
6515
6516 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6517 PDiag(DiagID) << index.toString(10, true)
6518 << size.toString(10, true)
6519 << (unsigned)size.getLimitedValue(~0U)
6520 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006521 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006522 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006523 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006524 DiagID = diag::warn_ptr_arith_precedes_bounds;
6525 if (index.isNegative()) index = -index;
6526 }
6527
6528 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6529 PDiag(DiagID) << index.toString(10, true)
6530 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00006531 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00006532
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00006533 if (!ND) {
6534 // Try harder to find a NamedDecl to point at in the note.
6535 while (const ArraySubscriptExpr *ASE =
6536 dyn_cast<ArraySubscriptExpr>(BaseExpr))
6537 BaseExpr = ASE->getBase()->IgnoreParenCasts();
6538 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6539 ND = dyn_cast<NamedDecl>(DRE->getDecl());
6540 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6541 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6542 }
6543
Chandler Carruth1af88f12011-02-17 21:10:52 +00006544 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006545 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6546 PDiag(diag::note_array_index_out_of_bounds)
6547 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00006548}
6549
Ted Kremenekdf26df72011-03-01 18:41:00 +00006550void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006551 int AllowOnePastEnd = 0;
6552 while (expr) {
6553 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00006554 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006555 case Stmt::ArraySubscriptExprClass: {
6556 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006557 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006558 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00006559 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006560 }
6561 case Stmt::UnaryOperatorClass: {
6562 // Only unwrap the * and & unary operators
6563 const UnaryOperator *UO = cast<UnaryOperator>(expr);
6564 expr = UO->getSubExpr();
6565 switch (UO->getOpcode()) {
6566 case UO_AddrOf:
6567 AllowOnePastEnd++;
6568 break;
6569 case UO_Deref:
6570 AllowOnePastEnd--;
6571 break;
6572 default:
6573 return;
6574 }
6575 break;
6576 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00006577 case Stmt::ConditionalOperatorClass: {
6578 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
6579 if (const Expr *lhs = cond->getLHS())
6580 CheckArrayAccess(lhs);
6581 if (const Expr *rhs = cond->getRHS())
6582 CheckArrayAccess(rhs);
6583 return;
6584 }
6585 default:
6586 return;
6587 }
Peter Collingbourne91147592011-04-15 00:35:48 +00006588 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00006589}
John McCall31168b02011-06-15 23:02:42 +00006590
6591//===--- CHECK: Objective-C retain cycles ----------------------------------//
6592
6593namespace {
6594 struct RetainCycleOwner {
6595 RetainCycleOwner() : Variable(0), Indirect(false) {}
6596 VarDecl *Variable;
6597 SourceRange Range;
6598 SourceLocation Loc;
6599 bool Indirect;
6600
6601 void setLocsFrom(Expr *e) {
6602 Loc = e->getExprLoc();
6603 Range = e->getSourceRange();
6604 }
6605 };
6606}
6607
6608/// Consider whether capturing the given variable can possibly lead to
6609/// a retain cycle.
6610static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00006611 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00006612 // lifetime. In MRR, it's captured strongly if the variable is
6613 // __block and has an appropriate type.
6614 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6615 return false;
6616
6617 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00006618 if (ref)
6619 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00006620 return true;
6621}
6622
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006623static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00006624 while (true) {
6625 e = e->IgnoreParens();
6626 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6627 switch (cast->getCastKind()) {
6628 case CK_BitCast:
6629 case CK_LValueBitCast:
6630 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00006631 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00006632 e = cast->getSubExpr();
6633 continue;
6634
John McCall31168b02011-06-15 23:02:42 +00006635 default:
6636 return false;
6637 }
6638 }
6639
6640 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6641 ObjCIvarDecl *ivar = ref->getDecl();
6642 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6643 return false;
6644
6645 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006646 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00006647 return false;
6648
6649 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6650 owner.Indirect = true;
6651 return true;
6652 }
6653
6654 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6655 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6656 if (!var) return false;
6657 return considerVariable(var, ref, owner);
6658 }
6659
John McCall31168b02011-06-15 23:02:42 +00006660 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6661 if (member->isArrow()) return false;
6662
6663 // Don't count this as an indirect ownership.
6664 e = member->getBase();
6665 continue;
6666 }
6667
John McCallfe96e0b2011-11-06 09:01:30 +00006668 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6669 // Only pay attention to pseudo-objects on property references.
6670 ObjCPropertyRefExpr *pre
6671 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6672 ->IgnoreParens());
6673 if (!pre) return false;
6674 if (pre->isImplicitProperty()) return false;
6675 ObjCPropertyDecl *property = pre->getExplicitProperty();
6676 if (!property->isRetaining() &&
6677 !(property->getPropertyIvarDecl() &&
6678 property->getPropertyIvarDecl()->getType()
6679 .getObjCLifetime() == Qualifiers::OCL_Strong))
6680 return false;
6681
6682 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006683 if (pre->isSuperReceiver()) {
6684 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6685 if (!owner.Variable)
6686 return false;
6687 owner.Loc = pre->getLocation();
6688 owner.Range = pre->getSourceRange();
6689 return true;
6690 }
John McCallfe96e0b2011-11-06 09:01:30 +00006691 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6692 ->getSourceExpr());
6693 continue;
6694 }
6695
John McCall31168b02011-06-15 23:02:42 +00006696 // Array ivars?
6697
6698 return false;
6699 }
6700}
6701
6702namespace {
6703 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6704 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6705 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6706 Variable(variable), Capturer(0) {}
6707
6708 VarDecl *Variable;
6709 Expr *Capturer;
6710
6711 void VisitDeclRefExpr(DeclRefExpr *ref) {
6712 if (ref->getDecl() == Variable && !Capturer)
6713 Capturer = ref;
6714 }
6715
John McCall31168b02011-06-15 23:02:42 +00006716 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6717 if (Capturer) return;
6718 Visit(ref->getBase());
6719 if (Capturer && ref->isFreeIvar())
6720 Capturer = ref;
6721 }
6722
6723 void VisitBlockExpr(BlockExpr *block) {
6724 // Look inside nested blocks
6725 if (block->getBlockDecl()->capturesVariable(Variable))
6726 Visit(block->getBlockDecl()->getBody());
6727 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00006728
6729 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6730 if (Capturer) return;
6731 if (OVE->getSourceExpr())
6732 Visit(OVE->getSourceExpr());
6733 }
John McCall31168b02011-06-15 23:02:42 +00006734 };
6735}
6736
6737/// Check whether the given argument is a block which captures a
6738/// variable.
6739static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6740 assert(owner.Variable && owner.Loc.isValid());
6741
6742 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00006743
6744 // Look through [^{...} copy] and Block_copy(^{...}).
6745 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6746 Selector Cmd = ME->getSelector();
6747 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6748 e = ME->getInstanceReceiver();
6749 if (!e)
6750 return 0;
6751 e = e->IgnoreParenCasts();
6752 }
6753 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6754 if (CE->getNumArgs() == 1) {
6755 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00006756 if (Fn) {
6757 const IdentifierInfo *FnI = Fn->getIdentifier();
6758 if (FnI && FnI->isStr("_Block_copy")) {
6759 e = CE->getArg(0)->IgnoreParenCasts();
6760 }
6761 }
Jordan Rose67e887c2012-09-17 17:54:30 +00006762 }
6763 }
6764
John McCall31168b02011-06-15 23:02:42 +00006765 BlockExpr *block = dyn_cast<BlockExpr>(e);
6766 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6767 return 0;
6768
6769 FindCaptureVisitor visitor(S.Context, owner.Variable);
6770 visitor.Visit(block->getBlockDecl()->getBody());
6771 return visitor.Capturer;
6772}
6773
6774static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6775 RetainCycleOwner &owner) {
6776 assert(capturer);
6777 assert(owner.Variable && owner.Loc.isValid());
6778
6779 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6780 << owner.Variable << capturer->getSourceRange();
6781 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6782 << owner.Indirect << owner.Range;
6783}
6784
6785/// Check for a keyword selector that starts with the word 'add' or
6786/// 'set'.
6787static bool isSetterLikeSelector(Selector sel) {
6788 if (sel.isUnarySelector()) return false;
6789
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006790 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00006791 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00006792 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00006793 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00006794 else if (str.startswith("add")) {
6795 // Specially whitelist 'addOperationWithBlock:'.
6796 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6797 return false;
6798 str = str.substr(3);
6799 }
John McCall31168b02011-06-15 23:02:42 +00006800 else
6801 return false;
6802
6803 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00006804 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00006805}
6806
6807/// Check a message send to see if it's likely to cause a retain cycle.
6808void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6809 // Only check instance methods whose selector looks like a setter.
6810 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6811 return;
6812
6813 // Try to find a variable that the receiver is strongly owned by.
6814 RetainCycleOwner owner;
6815 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006816 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00006817 return;
6818 } else {
6819 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6820 owner.Variable = getCurMethodDecl()->getSelfDecl();
6821 owner.Loc = msg->getSuperLoc();
6822 owner.Range = msg->getSuperLoc();
6823 }
6824
6825 // Check whether the receiver is captured by any of the arguments.
6826 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6827 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6828 return diagnoseRetainCycle(*this, capturer, owner);
6829}
6830
6831/// Check a property assign to see if it's likely to cause a retain cycle.
6832void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6833 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006834 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00006835 return;
6836
6837 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6838 diagnoseRetainCycle(*this, capturer, owner);
6839}
6840
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00006841void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6842 RetainCycleOwner Owner;
6843 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6844 return;
6845
6846 // Because we don't have an expression for the variable, we have to set the
6847 // location explicitly here.
6848 Owner.Loc = Var->getLocation();
6849 Owner.Range = Var->getSourceRange();
6850
6851 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6852 diagnoseRetainCycle(*this, Capturer, Owner);
6853}
6854
Ted Kremenek9304da92012-12-21 08:04:28 +00006855static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6856 Expr *RHS, bool isProperty) {
6857 // Check if RHS is an Objective-C object literal, which also can get
6858 // immediately zapped in a weak reference. Note that we explicitly
6859 // allow ObjCStringLiterals, since those are designed to never really die.
6860 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00006861
Ted Kremenek64873352012-12-21 22:46:35 +00006862 // This enum needs to match with the 'select' in
6863 // warn_objc_arc_literal_assign (off-by-1).
6864 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6865 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6866 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00006867
6868 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00006869 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00006870 << (isProperty ? 0 : 1)
6871 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00006872
6873 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00006874}
6875
Ted Kremenekc1f014a2012-12-21 19:45:30 +00006876static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6877 Qualifiers::ObjCLifetime LT,
6878 Expr *RHS, bool isProperty) {
6879 // Strip off any implicit cast added to get to the one ARC-specific.
6880 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6881 if (cast->getCastKind() == CK_ARCConsumeObject) {
6882 S.Diag(Loc, diag::warn_arc_retained_assign)
6883 << (LT == Qualifiers::OCL_ExplicitNone)
6884 << (isProperty ? 0 : 1)
6885 << RHS->getSourceRange();
6886 return true;
6887 }
6888 RHS = cast->getSubExpr();
6889 }
6890
6891 if (LT == Qualifiers::OCL_Weak &&
6892 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6893 return true;
6894
6895 return false;
6896}
6897
Ted Kremenekb36234d2012-12-21 08:04:20 +00006898bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6899 QualType LHS, Expr *RHS) {
6900 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6901
6902 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6903 return false;
6904
6905 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6906 return true;
6907
6908 return false;
6909}
6910
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006911void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6912 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006913 QualType LHSType;
6914 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00006915 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006916 ObjCPropertyRefExpr *PRE
6917 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6918 if (PRE && !PRE->isImplicitProperty()) {
6919 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6920 if (PD)
6921 LHSType = PD->getType();
6922 }
6923
6924 if (LHSType.isNull())
6925 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00006926
6927 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6928
6929 if (LT == Qualifiers::OCL_Weak) {
6930 DiagnosticsEngine::Level Level =
6931 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6932 if (Level != DiagnosticsEngine::Ignored)
6933 getCurFunction()->markSafeWeakUse(LHS);
6934 }
6935
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006936 if (checkUnsafeAssigns(Loc, LHSType, RHS))
6937 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00006938
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006939 // FIXME. Check for other life times.
6940 if (LT != Qualifiers::OCL_None)
6941 return;
6942
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006943 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006944 if (PRE->isImplicitProperty())
6945 return;
6946 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6947 if (!PD)
6948 return;
6949
Bill Wendling44426052012-12-20 19:22:21 +00006950 unsigned Attributes = PD->getPropertyAttributes();
6951 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006952 // when 'assign' attribute was not explicitly specified
6953 // by user, ignore it and rely on property type itself
6954 // for lifetime info.
6955 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6956 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6957 LHSType->isObjCRetainableType())
6958 return;
6959
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006960 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00006961 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006962 Diag(Loc, diag::warn_arc_retained_property_assign)
6963 << RHS->getSourceRange();
6964 return;
6965 }
6966 RHS = cast->getSubExpr();
6967 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006968 }
Bill Wendling44426052012-12-20 19:22:21 +00006969 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00006970 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6971 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00006972 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006973 }
6974}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00006975
6976//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6977
6978namespace {
6979bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6980 SourceLocation StmtLoc,
6981 const NullStmt *Body) {
6982 // Do not warn if the body is a macro that expands to nothing, e.g:
6983 //
6984 // #define CALL(x)
6985 // if (condition)
6986 // CALL(0);
6987 //
6988 if (Body->hasLeadingEmptyMacro())
6989 return false;
6990
6991 // Get line numbers of statement and body.
6992 bool StmtLineInvalid;
6993 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6994 &StmtLineInvalid);
6995 if (StmtLineInvalid)
6996 return false;
6997
6998 bool BodyLineInvalid;
6999 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
7000 &BodyLineInvalid);
7001 if (BodyLineInvalid)
7002 return false;
7003
7004 // Warn if null statement and body are on the same line.
7005 if (StmtLine != BodyLine)
7006 return false;
7007
7008 return true;
7009}
7010} // Unnamed namespace
7011
7012void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
7013 const Stmt *Body,
7014 unsigned DiagID) {
7015 // Since this is a syntactic check, don't emit diagnostic for template
7016 // instantiations, this just adds noise.
7017 if (CurrentInstantiationScope)
7018 return;
7019
7020 // The body should be a null statement.
7021 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7022 if (!NBody)
7023 return;
7024
7025 // Do the usual checks.
7026 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7027 return;
7028
7029 Diag(NBody->getSemiLoc(), DiagID);
7030 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7031}
7032
7033void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
7034 const Stmt *PossibleBody) {
7035 assert(!CurrentInstantiationScope); // Ensured by caller
7036
7037 SourceLocation StmtLoc;
7038 const Stmt *Body;
7039 unsigned DiagID;
7040 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
7041 StmtLoc = FS->getRParenLoc();
7042 Body = FS->getBody();
7043 DiagID = diag::warn_empty_for_body;
7044 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
7045 StmtLoc = WS->getCond()->getSourceRange().getEnd();
7046 Body = WS->getBody();
7047 DiagID = diag::warn_empty_while_body;
7048 } else
7049 return; // Neither `for' nor `while'.
7050
7051 // The body should be a null statement.
7052 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7053 if (!NBody)
7054 return;
7055
7056 // Skip expensive checks if diagnostic is disabled.
7057 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
7058 DiagnosticsEngine::Ignored)
7059 return;
7060
7061 // Do the usual checks.
7062 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7063 return;
7064
7065 // `for(...);' and `while(...);' are popular idioms, so in order to keep
7066 // noise level low, emit diagnostics only if for/while is followed by a
7067 // CompoundStmt, e.g.:
7068 // for (int i = 0; i < n; i++);
7069 // {
7070 // a(i);
7071 // }
7072 // or if for/while is followed by a statement with more indentation
7073 // than for/while itself:
7074 // for (int i = 0; i < n; i++);
7075 // a(i);
7076 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
7077 if (!ProbableTypo) {
7078 bool BodyColInvalid;
7079 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
7080 PossibleBody->getLocStart(),
7081 &BodyColInvalid);
7082 if (BodyColInvalid)
7083 return;
7084
7085 bool StmtColInvalid;
7086 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7087 S->getLocStart(),
7088 &StmtColInvalid);
7089 if (StmtColInvalid)
7090 return;
7091
7092 if (BodyCol > StmtCol)
7093 ProbableTypo = true;
7094 }
7095
7096 if (ProbableTypo) {
7097 Diag(NBody->getSemiLoc(), DiagID);
7098 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7099 }
7100}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007101
7102//===--- Layout compatibility ----------------------------------------------//
7103
7104namespace {
7105
7106bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7107
7108/// \brief Check if two enumeration types are layout-compatible.
7109bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7110 // C++11 [dcl.enum] p8:
7111 // Two enumeration types are layout-compatible if they have the same
7112 // underlying type.
7113 return ED1->isComplete() && ED2->isComplete() &&
7114 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7115}
7116
7117/// \brief Check if two fields are layout-compatible.
7118bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7119 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7120 return false;
7121
7122 if (Field1->isBitField() != Field2->isBitField())
7123 return false;
7124
7125 if (Field1->isBitField()) {
7126 // Make sure that the bit-fields are the same length.
7127 unsigned Bits1 = Field1->getBitWidthValue(C);
7128 unsigned Bits2 = Field2->getBitWidthValue(C);
7129
7130 if (Bits1 != Bits2)
7131 return false;
7132 }
7133
7134 return true;
7135}
7136
7137/// \brief Check if two standard-layout structs are layout-compatible.
7138/// (C++11 [class.mem] p17)
7139bool isLayoutCompatibleStruct(ASTContext &C,
7140 RecordDecl *RD1,
7141 RecordDecl *RD2) {
7142 // If both records are C++ classes, check that base classes match.
7143 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7144 // If one of records is a CXXRecordDecl we are in C++ mode,
7145 // thus the other one is a CXXRecordDecl, too.
7146 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7147 // Check number of base classes.
7148 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7149 return false;
7150
7151 // Check the base classes.
7152 for (CXXRecordDecl::base_class_const_iterator
7153 Base1 = D1CXX->bases_begin(),
7154 BaseEnd1 = D1CXX->bases_end(),
7155 Base2 = D2CXX->bases_begin();
7156 Base1 != BaseEnd1;
7157 ++Base1, ++Base2) {
7158 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7159 return false;
7160 }
7161 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7162 // If only RD2 is a C++ class, it should have zero base classes.
7163 if (D2CXX->getNumBases() > 0)
7164 return false;
7165 }
7166
7167 // Check the fields.
7168 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7169 Field2End = RD2->field_end(),
7170 Field1 = RD1->field_begin(),
7171 Field1End = RD1->field_end();
7172 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7173 if (!isLayoutCompatible(C, *Field1, *Field2))
7174 return false;
7175 }
7176 if (Field1 != Field1End || Field2 != Field2End)
7177 return false;
7178
7179 return true;
7180}
7181
7182/// \brief Check if two standard-layout unions are layout-compatible.
7183/// (C++11 [class.mem] p18)
7184bool isLayoutCompatibleUnion(ASTContext &C,
7185 RecordDecl *RD1,
7186 RecordDecl *RD2) {
7187 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
7188 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
7189 Field2End = RD2->field_end();
7190 Field2 != Field2End; ++Field2) {
7191 UnmatchedFields.insert(*Field2);
7192 }
7193
7194 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
7195 Field1End = RD1->field_end();
7196 Field1 != Field1End; ++Field1) {
7197 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7198 I = UnmatchedFields.begin(),
7199 E = UnmatchedFields.end();
7200
7201 for ( ; I != E; ++I) {
7202 if (isLayoutCompatible(C, *Field1, *I)) {
7203 bool Result = UnmatchedFields.erase(*I);
7204 (void) Result;
7205 assert(Result);
7206 break;
7207 }
7208 }
7209 if (I == E)
7210 return false;
7211 }
7212
7213 return UnmatchedFields.empty();
7214}
7215
7216bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7217 if (RD1->isUnion() != RD2->isUnion())
7218 return false;
7219
7220 if (RD1->isUnion())
7221 return isLayoutCompatibleUnion(C, RD1, RD2);
7222 else
7223 return isLayoutCompatibleStruct(C, RD1, RD2);
7224}
7225
7226/// \brief Check if two types are layout-compatible in C++11 sense.
7227bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7228 if (T1.isNull() || T2.isNull())
7229 return false;
7230
7231 // C++11 [basic.types] p11:
7232 // If two types T1 and T2 are the same type, then T1 and T2 are
7233 // layout-compatible types.
7234 if (C.hasSameType(T1, T2))
7235 return true;
7236
7237 T1 = T1.getCanonicalType().getUnqualifiedType();
7238 T2 = T2.getCanonicalType().getUnqualifiedType();
7239
7240 const Type::TypeClass TC1 = T1->getTypeClass();
7241 const Type::TypeClass TC2 = T2->getTypeClass();
7242
7243 if (TC1 != TC2)
7244 return false;
7245
7246 if (TC1 == Type::Enum) {
7247 return isLayoutCompatible(C,
7248 cast<EnumType>(T1)->getDecl(),
7249 cast<EnumType>(T2)->getDecl());
7250 } else if (TC1 == Type::Record) {
7251 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7252 return false;
7253
7254 return isLayoutCompatible(C,
7255 cast<RecordType>(T1)->getDecl(),
7256 cast<RecordType>(T2)->getDecl());
7257 }
7258
7259 return false;
7260}
7261}
7262
7263//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7264
7265namespace {
7266/// \brief Given a type tag expression find the type tag itself.
7267///
7268/// \param TypeExpr Type tag expression, as it appears in user's code.
7269///
7270/// \param VD Declaration of an identifier that appears in a type tag.
7271///
7272/// \param MagicValue Type tag magic value.
7273bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7274 const ValueDecl **VD, uint64_t *MagicValue) {
7275 while(true) {
7276 if (!TypeExpr)
7277 return false;
7278
7279 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7280
7281 switch (TypeExpr->getStmtClass()) {
7282 case Stmt::UnaryOperatorClass: {
7283 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7284 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7285 TypeExpr = UO->getSubExpr();
7286 continue;
7287 }
7288 return false;
7289 }
7290
7291 case Stmt::DeclRefExprClass: {
7292 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7293 *VD = DRE->getDecl();
7294 return true;
7295 }
7296
7297 case Stmt::IntegerLiteralClass: {
7298 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7299 llvm::APInt MagicValueAPInt = IL->getValue();
7300 if (MagicValueAPInt.getActiveBits() <= 64) {
7301 *MagicValue = MagicValueAPInt.getZExtValue();
7302 return true;
7303 } else
7304 return false;
7305 }
7306
7307 case Stmt::BinaryConditionalOperatorClass:
7308 case Stmt::ConditionalOperatorClass: {
7309 const AbstractConditionalOperator *ACO =
7310 cast<AbstractConditionalOperator>(TypeExpr);
7311 bool Result;
7312 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7313 if (Result)
7314 TypeExpr = ACO->getTrueExpr();
7315 else
7316 TypeExpr = ACO->getFalseExpr();
7317 continue;
7318 }
7319 return false;
7320 }
7321
7322 case Stmt::BinaryOperatorClass: {
7323 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7324 if (BO->getOpcode() == BO_Comma) {
7325 TypeExpr = BO->getRHS();
7326 continue;
7327 }
7328 return false;
7329 }
7330
7331 default:
7332 return false;
7333 }
7334 }
7335}
7336
7337/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7338///
7339/// \param TypeExpr Expression that specifies a type tag.
7340///
7341/// \param MagicValues Registered magic values.
7342///
7343/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7344/// kind.
7345///
7346/// \param TypeInfo Information about the corresponding C type.
7347///
7348/// \returns true if the corresponding C type was found.
7349bool GetMatchingCType(
7350 const IdentifierInfo *ArgumentKind,
7351 const Expr *TypeExpr, const ASTContext &Ctx,
7352 const llvm::DenseMap<Sema::TypeTagMagicValue,
7353 Sema::TypeTagData> *MagicValues,
7354 bool &FoundWrongKind,
7355 Sema::TypeTagData &TypeInfo) {
7356 FoundWrongKind = false;
7357
7358 // Variable declaration that has type_tag_for_datatype attribute.
7359 const ValueDecl *VD = NULL;
7360
7361 uint64_t MagicValue;
7362
7363 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7364 return false;
7365
7366 if (VD) {
7367 for (specific_attr_iterator<TypeTagForDatatypeAttr>
7368 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
7369 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
7370 I != E; ++I) {
7371 if (I->getArgumentKind() != ArgumentKind) {
7372 FoundWrongKind = true;
7373 return false;
7374 }
7375 TypeInfo.Type = I->getMatchingCType();
7376 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7377 TypeInfo.MustBeNull = I->getMustBeNull();
7378 return true;
7379 }
7380 return false;
7381 }
7382
7383 if (!MagicValues)
7384 return false;
7385
7386 llvm::DenseMap<Sema::TypeTagMagicValue,
7387 Sema::TypeTagData>::const_iterator I =
7388 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7389 if (I == MagicValues->end())
7390 return false;
7391
7392 TypeInfo = I->second;
7393 return true;
7394}
7395} // unnamed namespace
7396
7397void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7398 uint64_t MagicValue, QualType Type,
7399 bool LayoutCompatible,
7400 bool MustBeNull) {
7401 if (!TypeTagForDatatypeMagicValues)
7402 TypeTagForDatatypeMagicValues.reset(
7403 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7404
7405 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7406 (*TypeTagForDatatypeMagicValues)[Magic] =
7407 TypeTagData(Type, LayoutCompatible, MustBeNull);
7408}
7409
7410namespace {
7411bool IsSameCharType(QualType T1, QualType T2) {
7412 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7413 if (!BT1)
7414 return false;
7415
7416 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7417 if (!BT2)
7418 return false;
7419
7420 BuiltinType::Kind T1Kind = BT1->getKind();
7421 BuiltinType::Kind T2Kind = BT2->getKind();
7422
7423 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
7424 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
7425 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7426 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7427}
7428} // unnamed namespace
7429
7430void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7431 const Expr * const *ExprArgs) {
7432 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7433 bool IsPointerAttr = Attr->getIsPointer();
7434
7435 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7436 bool FoundWrongKind;
7437 TypeTagData TypeInfo;
7438 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7439 TypeTagForDatatypeMagicValues.get(),
7440 FoundWrongKind, TypeInfo)) {
7441 if (FoundWrongKind)
7442 Diag(TypeTagExpr->getExprLoc(),
7443 diag::warn_type_tag_for_datatype_wrong_kind)
7444 << TypeTagExpr->getSourceRange();
7445 return;
7446 }
7447
7448 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7449 if (IsPointerAttr) {
7450 // Skip implicit cast of pointer to `void *' (as a function argument).
7451 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00007452 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00007453 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007454 ArgumentExpr = ICE->getSubExpr();
7455 }
7456 QualType ArgumentType = ArgumentExpr->getType();
7457
7458 // Passing a `void*' pointer shouldn't trigger a warning.
7459 if (IsPointerAttr && ArgumentType->isVoidPointerType())
7460 return;
7461
7462 if (TypeInfo.MustBeNull) {
7463 // Type tag with matching void type requires a null pointer.
7464 if (!ArgumentExpr->isNullPointerConstant(Context,
7465 Expr::NPC_ValueDependentIsNotNull)) {
7466 Diag(ArgumentExpr->getExprLoc(),
7467 diag::warn_type_safety_null_pointer_required)
7468 << ArgumentKind->getName()
7469 << ArgumentExpr->getSourceRange()
7470 << TypeTagExpr->getSourceRange();
7471 }
7472 return;
7473 }
7474
7475 QualType RequiredType = TypeInfo.Type;
7476 if (IsPointerAttr)
7477 RequiredType = Context.getPointerType(RequiredType);
7478
7479 bool mismatch = false;
7480 if (!TypeInfo.LayoutCompatible) {
7481 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7482
7483 // C++11 [basic.fundamental] p1:
7484 // Plain char, signed char, and unsigned char are three distinct types.
7485 //
7486 // But we treat plain `char' as equivalent to `signed char' or `unsigned
7487 // char' depending on the current char signedness mode.
7488 if (mismatch)
7489 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7490 RequiredType->getPointeeType())) ||
7491 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7492 mismatch = false;
7493 } else
7494 if (IsPointerAttr)
7495 mismatch = !isLayoutCompatible(Context,
7496 ArgumentType->getPointeeType(),
7497 RequiredType->getPointeeType());
7498 else
7499 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7500
7501 if (mismatch)
7502 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00007503 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007504 << TypeInfo.LayoutCompatible << RequiredType
7505 << ArgumentExpr->getSourceRange()
7506 << TypeTagExpr->getSourceRange();
7507}