blob: f3f08dec97fa851a34b9d563d62411cb63cec4c5 [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.
Tim Northover3402dc72014-02-12 12:04:59 +0000329static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000330 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000331 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000332 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 Northover12670412014-02-19 10:37:05 +0000391bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000392 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000393 uint64_t mask = 0;
394 unsigned TV = 0;
395 int PtrArgNum = -1;
396 bool HasConstPtr = false;
397 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000398#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000399#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000400#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000401 }
402
403 // For NEON intrinsics which are overloaded on vector element type, validate
404 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000405 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000406 if (mask) {
407 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
408 return true;
409
410 TV = Result.getLimitedValue(64);
411 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
412 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000413 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000414 }
415
416 if (PtrArgNum >= 0) {
417 // Check that pointer arguments have the specified type.
418 Expr *Arg = TheCall->getArg(PtrArgNum);
419 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
420 Arg = ICE->getSubExpr();
421 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
422 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000423
424 bool IsAArch64 =
425 Context.getTargetInfo().getTriple().getArch() == llvm::Triple::aarch64;
426 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context, IsAArch64);
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;
Tim Northover12670412014-02-19 10:37:05 +0000445#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000446#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000447#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000448 }
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 Northover12670412014-02-19 10:37:05 +0000469bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
470 CallExpr *TheCall) {
471 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
472 return true;
473
474 return false;
475}
476
Tim Northover6aacd492013-07-16 09:47:53 +0000477bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall) {
478 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
479 BuiltinID == ARM::BI__builtin_arm_strex) &&
480 "unexpected ARM builtin");
481 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex;
482
483 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
484
485 // Ensure that we have the proper number of arguments.
486 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
487 return true;
488
489 // Inspect the pointer argument of the atomic builtin. This should always be
490 // a pointer type, whose element is an integral scalar or pointer type.
491 // Because it is a pointer type, we don't have to worry about any implicit
492 // casts here.
493 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
494 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
495 if (PointerArgRes.isInvalid())
496 return true;
497 PointerArg = PointerArgRes.take();
498
499 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
500 if (!pointerType) {
501 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
502 << PointerArg->getType() << PointerArg->getSourceRange();
503 return true;
504 }
505
506 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
507 // task is to insert the appropriate casts into the AST. First work out just
508 // what the appropriate type is.
509 QualType ValType = pointerType->getPointeeType();
510 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
511 if (IsLdrex)
512 AddrType.addConst();
513
514 // Issue a warning if the cast is dodgy.
515 CastKind CastNeeded = CK_NoOp;
516 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
517 CastNeeded = CK_BitCast;
518 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
519 << PointerArg->getType()
520 << Context.getPointerType(AddrType)
521 << AA_Passing << PointerArg->getSourceRange();
522 }
523
524 // Finally, do the cast and replace the argument with the corrected version.
525 AddrType = Context.getPointerType(AddrType);
526 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
527 if (PointerArgRes.isInvalid())
528 return true;
529 PointerArg = PointerArgRes.take();
530
531 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
532
533 // In general, we allow ints, floats and pointers to be loaded and stored.
534 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
535 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
536 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
537 << PointerArg->getType() << PointerArg->getSourceRange();
538 return true;
539 }
540
541 // But ARM doesn't have instructions to deal with 128-bit versions.
542 if (Context.getTypeSize(ValType) > 64) {
543 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
544 << PointerArg->getType() << PointerArg->getSourceRange();
545 return true;
546 }
547
548 switch (ValType.getObjCLifetime()) {
549 case Qualifiers::OCL_None:
550 case Qualifiers::OCL_ExplicitNone:
551 // okay
552 break;
553
554 case Qualifiers::OCL_Weak:
555 case Qualifiers::OCL_Strong:
556 case Qualifiers::OCL_Autoreleasing:
557 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
558 << ValType << PointerArg->getSourceRange();
559 return true;
560 }
561
562
563 if (IsLdrex) {
564 TheCall->setType(ValType);
565 return false;
566 }
567
568 // Initialize the argument to be stored.
569 ExprResult ValArg = TheCall->getArg(0);
570 InitializedEntity Entity = InitializedEntity::InitializeParameter(
571 Context, ValType, /*consume*/ false);
572 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
573 if (ValArg.isInvalid())
574 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000575 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000576
577 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
578 // but the custom checker bypasses all default analysis.
579 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000580 return false;
581}
582
Nate Begeman4904e322010-06-08 02:47:44 +0000583bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000584 llvm::APSInt Result;
585
Tim Northover6aacd492013-07-16 09:47:53 +0000586 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
587 BuiltinID == ARM::BI__builtin_arm_strex) {
588 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall);
589 }
590
Tim Northover12670412014-02-19 10:37:05 +0000591 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
592 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000593
Nate Begemand773fe62010-06-13 04:47:52 +0000594 // For NEON intrinsics which take an immediate value as part of the
595 // instruction, range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000596 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000597 switch (BuiltinID) {
598 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000599 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
600 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000601 case ARM::BI__builtin_arm_vcvtr_f:
602 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000603 case ARM::BI__builtin_arm_dmb:
604 case ARM::BI__builtin_arm_dsb: l = 0; u = 15; break;
Nate Begemand773fe62010-06-13 04:47:52 +0000605 };
606
Douglas Gregor98c3cfc2012-06-29 01:05:22 +0000607 // We can't check the value of a dependent argument.
608 if (TheCall->getArg(i)->isTypeDependent() ||
609 TheCall->getArg(i)->isValueDependent())
610 return false;
611
Nate Begeman91e1fea2010-06-14 05:21:25 +0000612 // Check that the immediate argument is actually a constant.
Nate Begemand773fe62010-06-13 04:47:52 +0000613 if (SemaBuiltinConstantArg(TheCall, i, Result))
614 return true;
615
Nate Begeman91e1fea2010-06-14 05:21:25 +0000616 // Range check against the upper/lower values for this isntruction.
Nate Begemand773fe62010-06-13 04:47:52 +0000617 unsigned Val = Result.getZExtValue();
Nate Begeman91e1fea2010-06-14 05:21:25 +0000618 if (Val < l || Val > (u + l))
Nate Begemand773fe62010-06-13 04:47:52 +0000619 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramere8394df2010-08-11 14:47:12 +0000620 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begemand773fe62010-06-13 04:47:52 +0000621
Nate Begemanf568b072010-08-03 21:32:34 +0000622 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman4904e322010-06-08 02:47:44 +0000623 return false;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000624}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000625
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000626bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
627 unsigned i = 0, l = 0, u = 0;
628 switch (BuiltinID) {
629 default: return false;
630 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
631 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000632 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
633 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
634 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
635 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
636 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000637 };
638
639 // We can't check the value of a dependent argument.
640 if (TheCall->getArg(i)->isTypeDependent() ||
641 TheCall->getArg(i)->isValueDependent())
642 return false;
643
644 // Check that the immediate argument is actually a constant.
645 llvm::APSInt Result;
646 if (SemaBuiltinConstantArg(TheCall, i, Result))
647 return true;
648
649 // Range check against the upper/lower values for this instruction.
650 unsigned Val = Result.getZExtValue();
651 if (Val < l || Val > u)
652 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
653 << l << u << TheCall->getArg(i)->getSourceRange();
654
655 return false;
656}
657
Richard Smith55ce3522012-06-25 20:30:08 +0000658/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
659/// parameter with the FormatAttr's correct format_idx and firstDataArg.
660/// Returns true when the format fits the function and the FormatStringInfo has
661/// been populated.
662bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
663 FormatStringInfo *FSI) {
664 FSI->HasVAListArg = Format->getFirstArg() == 0;
665 FSI->FormatIdx = Format->getFormatIdx() - 1;
666 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000667
Richard Smith55ce3522012-06-25 20:30:08 +0000668 // The way the format attribute works in GCC, the implicit this argument
669 // of member functions is counted. However, it doesn't appear in our own
670 // lists, so decrement format_idx in that case.
671 if (IsCXXMember) {
672 if(FSI->FormatIdx == 0)
673 return false;
674 --FSI->FormatIdx;
675 if (FSI->FirstDataArg != 0)
676 --FSI->FirstDataArg;
677 }
678 return true;
679}
Mike Stump11289f42009-09-09 15:08:12 +0000680
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000681/// Checks if a the given expression evaluates to null.
682///
683/// \brief Returns true if the value evaluates to null.
684static bool CheckNonNullExpr(Sema &S,
685 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000686 // As a special case, transparent unions initialized with zero are
687 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000688 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000689 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
690 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000691 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000692 if (const InitListExpr *ILE =
693 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000694 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000695 }
696
697 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000698 return (!Expr->isValueDependent() &&
699 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
700 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000701}
702
703static void CheckNonNullArgument(Sema &S,
704 const Expr *ArgExpr,
705 SourceLocation CallSiteLoc) {
706 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000707 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
708}
709
Ted Kremenek2bc73332014-01-17 06:24:43 +0000710static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +0000711 const NamedDecl *FDecl,
Ted Kremenek2bc73332014-01-17 06:24:43 +0000712 const Expr * const *ExprArgs,
713 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000714 // Check the attributes attached to the method/function itself.
Ted Kremeneka146db32014-01-17 06:24:47 +0000715 for (specific_attr_iterator<NonNullAttr>
716 I = FDecl->specific_attr_begin<NonNullAttr>(),
717 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I) {
Ted Kremenek2bc73332014-01-17 06:24:43 +0000718
Ted Kremeneka146db32014-01-17 06:24:47 +0000719 const NonNullAttr *NonNull = *I;
720 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
721 e = NonNull->args_end();
722 i != e; ++i) {
723 CheckNonNullArgument(S, ExprArgs[*i], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +0000724 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000725 }
Ted Kremenek9aedc152014-01-17 06:24:56 +0000726
727 // Check the attributes on the parameters.
728 ArrayRef<ParmVarDecl*> parms;
729 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
730 parms = FD->parameters();
731 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
732 parms = MD->parameters();
733
734 unsigned argIndex = 0;
735 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
736 I != E; ++I, ++argIndex) {
737 const ParmVarDecl *PVD = *I;
738 if (PVD->hasAttr<NonNullAttr>())
739 CheckNonNullArgument(S, ExprArgs[argIndex], CallSiteLoc);
740 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000741}
742
Richard Smith55ce3522012-06-25 20:30:08 +0000743/// Handles the checks for format strings, non-POD arguments to vararg
744/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000745void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
746 unsigned NumParams, bool IsMemberFunction,
747 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +0000748 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +0000749 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +0000750 if (CurContext->isDependentContext())
751 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000752
Ted Kremenekb8176da2010-09-09 04:33:05 +0000753 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +0000754 llvm::SmallBitVector CheckedVarArgs;
755 if (FDecl) {
Richard Trieu41bc0992013-06-22 00:20:41 +0000756 for (specific_attr_iterator<FormatAttr>
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000757 I = FDecl->specific_attr_begin<FormatAttr>(),
758 E = FDecl->specific_attr_end<FormatAttr>();
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000759 I != E; ++I) {
760 // Only create vector if there are format attributes.
761 CheckedVarArgs.resize(Args.size());
762
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000763 CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc, Range,
764 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000765 }
Richard Smithd7293d72013-08-05 18:49:43 +0000766 }
Richard Smith55ce3522012-06-25 20:30:08 +0000767
768 // Refuse POD arguments that weren't caught by the format string
769 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +0000770 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000771 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000772 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +0000773 if (const Expr *Arg = Args[ArgIdx]) {
774 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
775 checkVariadicArgument(Arg, CallType);
776 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000777 }
Richard Smithd7293d72013-08-05 18:49:43 +0000778 }
Mike Stump11289f42009-09-09 15:08:12 +0000779
Richard Trieu41bc0992013-06-22 00:20:41 +0000780 if (FDecl) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000781 CheckNonNullArguments(*this, FDecl, Args.data(), Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000782
Richard Trieu41bc0992013-06-22 00:20:41 +0000783 // Type safety checking.
784 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
785 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
786 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>();
787 i != e; ++i) {
788 CheckArgumentWithTypeTag(*i, Args.data());
789 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000790 }
Richard Smith55ce3522012-06-25 20:30:08 +0000791}
792
793/// CheckConstructorCall - Check a constructor call for correctness and safety
794/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000795void Sema::CheckConstructorCall(FunctionDecl *FDecl,
796 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +0000797 const FunctionProtoType *Proto,
798 SourceLocation Loc) {
799 VariadicCallType CallType =
800 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +0000801 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +0000802 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
803}
804
805/// CheckFunctionCall - Check a direct function call for various correctness
806/// and safety properties not strictly enforced by the C type system.
807bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
808 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000809 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
810 isa<CXXMethodDecl>(FDecl);
811 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
812 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +0000813 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
814 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000815 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +0000816 Expr** Args = TheCall->getArgs();
817 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +0000818 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000819 // If this is a call to a member operator, hide the first argument
820 // from checkCall.
821 // FIXME: Our choice of AST representation here is less than ideal.
822 ++Args;
823 --NumArgs;
824 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000825 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +0000826 IsMemberFunction, TheCall->getRParenLoc(),
827 TheCall->getCallee()->getSourceRange(), CallType);
828
829 IdentifierInfo *FnInfo = FDecl->getIdentifier();
830 // None of the checks below are needed for functions that don't have
831 // simple names (e.g., C++ conversion functions).
832 if (!FnInfo)
833 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000834
Anna Zaks22122702012-01-17 00:37:07 +0000835 unsigned CMId = FDecl->getMemoryFunctionKind();
836 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +0000837 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +0000838
Anna Zaks201d4892012-01-13 21:52:01 +0000839 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +0000840 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +0000841 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +0000842 else if (CMId == Builtin::BIstrncat)
843 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +0000844 else
Anna Zaks22122702012-01-17 00:37:07 +0000845 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +0000846
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000847 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000848}
849
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000850bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000851 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +0000852 VariadicCallType CallType =
853 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000854
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000855 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +0000856 /*IsMemberFunction=*/false,
857 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000858
859 return false;
860}
861
Richard Trieu664c4c62013-06-20 21:03:13 +0000862bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
863 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000864 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
865 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000866 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000867
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000868 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +0000869 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000870 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000871
Richard Trieu664c4c62013-06-20 21:03:13 +0000872 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +0000873 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +0000874 CallType = VariadicDoesNotApply;
875 } else if (Ty->isBlockPointerType()) {
876 CallType = VariadicBlock;
877 } else { // Ty->isFunctionPointerType()
878 CallType = VariadicFunction;
879 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000880 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000881
Alp Toker9cacbab2014-01-20 20:26:09 +0000882 checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
883 TheCall->getNumArgs()),
884 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +0000885 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +0000886
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000887 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000888}
889
Richard Trieu41bc0992013-06-22 00:20:41 +0000890/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
891/// such as function pointers returned from functions.
892bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
893 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
894 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000895 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +0000896
Alp Toker9cacbab2014-01-20 20:26:09 +0000897 checkCall(/*FDecl=*/0, llvm::makeArrayRef<const Expr *>(
898 TheCall->getArgs(), TheCall->getNumArgs()),
899 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +0000900 TheCall->getCallee()->getSourceRange(), CallType);
901
902 return false;
903}
904
Richard Smithfeea8832012-04-12 05:08:17 +0000905ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
906 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000907 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
908 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000909
Richard Smithfeea8832012-04-12 05:08:17 +0000910 // All these operations take one of the following forms:
911 enum {
912 // C __c11_atomic_init(A *, C)
913 Init,
914 // C __c11_atomic_load(A *, int)
915 Load,
916 // void __atomic_load(A *, CP, int)
917 Copy,
918 // C __c11_atomic_add(A *, M, int)
919 Arithmetic,
920 // C __atomic_exchange_n(A *, CP, int)
921 Xchg,
922 // void __atomic_exchange(A *, C *, CP, int)
923 GNUXchg,
924 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
925 C11CmpXchg,
926 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
927 GNUCmpXchg
928 } Form = Init;
929 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
930 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
931 // where:
932 // C is an appropriate type,
933 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
934 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
935 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
936 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000937
Richard Smithfeea8832012-04-12 05:08:17 +0000938 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
939 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
940 && "need to update code for modified C11 atomics");
941 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
942 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
943 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
944 Op == AtomicExpr::AO__atomic_store_n ||
945 Op == AtomicExpr::AO__atomic_exchange_n ||
946 Op == AtomicExpr::AO__atomic_compare_exchange_n;
947 bool IsAddSub = false;
948
949 switch (Op) {
950 case AtomicExpr::AO__c11_atomic_init:
951 Form = Init;
952 break;
953
954 case AtomicExpr::AO__c11_atomic_load:
955 case AtomicExpr::AO__atomic_load_n:
956 Form = Load;
957 break;
958
959 case AtomicExpr::AO__c11_atomic_store:
960 case AtomicExpr::AO__atomic_load:
961 case AtomicExpr::AO__atomic_store:
962 case AtomicExpr::AO__atomic_store_n:
963 Form = Copy;
964 break;
965
966 case AtomicExpr::AO__c11_atomic_fetch_add:
967 case AtomicExpr::AO__c11_atomic_fetch_sub:
968 case AtomicExpr::AO__atomic_fetch_add:
969 case AtomicExpr::AO__atomic_fetch_sub:
970 case AtomicExpr::AO__atomic_add_fetch:
971 case AtomicExpr::AO__atomic_sub_fetch:
972 IsAddSub = true;
973 // Fall through.
974 case AtomicExpr::AO__c11_atomic_fetch_and:
975 case AtomicExpr::AO__c11_atomic_fetch_or:
976 case AtomicExpr::AO__c11_atomic_fetch_xor:
977 case AtomicExpr::AO__atomic_fetch_and:
978 case AtomicExpr::AO__atomic_fetch_or:
979 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +0000980 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +0000981 case AtomicExpr::AO__atomic_and_fetch:
982 case AtomicExpr::AO__atomic_or_fetch:
983 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +0000984 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +0000985 Form = Arithmetic;
986 break;
987
988 case AtomicExpr::AO__c11_atomic_exchange:
989 case AtomicExpr::AO__atomic_exchange_n:
990 Form = Xchg;
991 break;
992
993 case AtomicExpr::AO__atomic_exchange:
994 Form = GNUXchg;
995 break;
996
997 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
998 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
999 Form = C11CmpXchg;
1000 break;
1001
1002 case AtomicExpr::AO__atomic_compare_exchange:
1003 case AtomicExpr::AO__atomic_compare_exchange_n:
1004 Form = GNUCmpXchg;
1005 break;
1006 }
1007
1008 // Check we have the right number of arguments.
1009 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001010 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001011 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001012 << TheCall->getCallee()->getSourceRange();
1013 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001014 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1015 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001016 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001017 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001018 << TheCall->getCallee()->getSourceRange();
1019 return ExprError();
1020 }
1021
Richard Smithfeea8832012-04-12 05:08:17 +00001022 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001023 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001024 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1025 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1026 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001027 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001028 << Ptr->getType() << Ptr->getSourceRange();
1029 return ExprError();
1030 }
1031
Richard Smithfeea8832012-04-12 05:08:17 +00001032 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1033 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1034 QualType ValType = AtomTy; // 'C'
1035 if (IsC11) {
1036 if (!AtomTy->isAtomicType()) {
1037 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1038 << Ptr->getType() << Ptr->getSourceRange();
1039 return ExprError();
1040 }
Richard Smithe00921a2012-09-15 06:09:58 +00001041 if (AtomTy.isConstQualified()) {
1042 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1043 << Ptr->getType() << Ptr->getSourceRange();
1044 return ExprError();
1045 }
Richard Smithfeea8832012-04-12 05:08:17 +00001046 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001047 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001048
Richard Smithfeea8832012-04-12 05:08:17 +00001049 // For an arithmetic operation, the implied arithmetic must be well-formed.
1050 if (Form == Arithmetic) {
1051 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1052 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1053 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1054 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1055 return ExprError();
1056 }
1057 if (!IsAddSub && !ValType->isIntegerType()) {
1058 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1059 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1060 return ExprError();
1061 }
1062 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1063 // For __atomic_*_n operations, the value type must be a scalar integral or
1064 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001065 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001066 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1067 return ExprError();
1068 }
1069
Eli Friedmanaa769812013-09-11 03:49:34 +00001070 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1071 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001072 // For GNU atomics, require a trivially-copyable type. This is not part of
1073 // the GNU atomics specification, but we enforce it for sanity.
1074 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001075 << Ptr->getType() << Ptr->getSourceRange();
1076 return ExprError();
1077 }
1078
Richard Smithfeea8832012-04-12 05:08:17 +00001079 // FIXME: For any builtin other than a load, the ValType must not be
1080 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001081
1082 switch (ValType.getObjCLifetime()) {
1083 case Qualifiers::OCL_None:
1084 case Qualifiers::OCL_ExplicitNone:
1085 // okay
1086 break;
1087
1088 case Qualifiers::OCL_Weak:
1089 case Qualifiers::OCL_Strong:
1090 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001091 // FIXME: Can this happen? By this point, ValType should be known
1092 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001093 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1094 << ValType << Ptr->getSourceRange();
1095 return ExprError();
1096 }
1097
1098 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001099 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001100 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001101 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001102 ResultType = Context.BoolTy;
1103
Richard Smithfeea8832012-04-12 05:08:17 +00001104 // The type of a parameter passed 'by value'. In the GNU atomics, such
1105 // arguments are actually passed as pointers.
1106 QualType ByValType = ValType; // 'CP'
1107 if (!IsC11 && !IsN)
1108 ByValType = Ptr->getType();
1109
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001110 // The first argument --- the pointer --- has a fixed type; we
1111 // deduce the types of the rest of the arguments accordingly. Walk
1112 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001113 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001114 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001115 if (i < NumVals[Form] + 1) {
1116 switch (i) {
1117 case 1:
1118 // The second argument is the non-atomic operand. For arithmetic, this
1119 // is always passed by value, and for a compare_exchange it is always
1120 // passed by address. For the rest, GNU uses by-address and C11 uses
1121 // by-value.
1122 assert(Form != Load);
1123 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1124 Ty = ValType;
1125 else if (Form == Copy || Form == Xchg)
1126 Ty = ByValType;
1127 else if (Form == Arithmetic)
1128 Ty = Context.getPointerDiffType();
1129 else
1130 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1131 break;
1132 case 2:
1133 // The third argument to compare_exchange / GNU exchange is a
1134 // (pointer to a) desired value.
1135 Ty = ByValType;
1136 break;
1137 case 3:
1138 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1139 Ty = Context.BoolTy;
1140 break;
1141 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001142 } else {
1143 // The order(s) are always converted to int.
1144 Ty = Context.IntTy;
1145 }
Richard Smithfeea8832012-04-12 05:08:17 +00001146
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001147 InitializedEntity Entity =
1148 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001149 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001150 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1151 if (Arg.isInvalid())
1152 return true;
1153 TheCall->setArg(i, Arg.get());
1154 }
1155
Richard Smithfeea8832012-04-12 05:08:17 +00001156 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001157 SmallVector<Expr*, 5> SubExprs;
1158 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001159 switch (Form) {
1160 case Init:
1161 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001162 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001163 break;
1164 case Load:
1165 SubExprs.push_back(TheCall->getArg(1)); // Order
1166 break;
1167 case Copy:
1168 case Arithmetic:
1169 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001170 SubExprs.push_back(TheCall->getArg(2)); // Order
1171 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001172 break;
1173 case GNUXchg:
1174 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1175 SubExprs.push_back(TheCall->getArg(3)); // Order
1176 SubExprs.push_back(TheCall->getArg(1)); // Val1
1177 SubExprs.push_back(TheCall->getArg(2)); // Val2
1178 break;
1179 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001180 SubExprs.push_back(TheCall->getArg(3)); // Order
1181 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001182 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001183 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001184 break;
1185 case GNUCmpXchg:
1186 SubExprs.push_back(TheCall->getArg(4)); // Order
1187 SubExprs.push_back(TheCall->getArg(1)); // Val1
1188 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1189 SubExprs.push_back(TheCall->getArg(2)); // Val2
1190 SubExprs.push_back(TheCall->getArg(3)); // Weak
1191 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001192 }
Fariborz Jahanian615de762013-05-28 17:37:39 +00001193
1194 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1195 SubExprs, ResultType, Op,
1196 TheCall->getRParenLoc());
1197
1198 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1199 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1200 Context.AtomicUsesUnsupportedLibcall(AE))
1201 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1202 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001203
Fariborz Jahanian615de762013-05-28 17:37:39 +00001204 return Owned(AE);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001205}
1206
1207
John McCall29ad95b2011-08-27 01:09:30 +00001208/// checkBuiltinArgument - Given a call to a builtin function, perform
1209/// normal type-checking on the given argument, updating the call in
1210/// place. This is useful when a builtin function requires custom
1211/// type-checking for some of its arguments but not necessarily all of
1212/// them.
1213///
1214/// Returns true on error.
1215static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1216 FunctionDecl *Fn = E->getDirectCallee();
1217 assert(Fn && "builtin call without direct callee!");
1218
1219 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1220 InitializedEntity Entity =
1221 InitializedEntity::InitializeParameter(S.Context, Param);
1222
1223 ExprResult Arg = E->getArg(0);
1224 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1225 if (Arg.isInvalid())
1226 return true;
1227
1228 E->setArg(ArgIndex, Arg.take());
1229 return false;
1230}
1231
Chris Lattnerdc046542009-05-08 06:58:22 +00001232/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1233/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1234/// type of its first argument. The main ActOnCallExpr routines have already
1235/// promoted the types of arguments because all of these calls are prototyped as
1236/// void(...).
1237///
1238/// This function goes through and does final semantic checking for these
1239/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001240ExprResult
1241Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001242 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001243 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1244 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1245
1246 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001247 if (TheCall->getNumArgs() < 1) {
1248 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1249 << 0 << 1 << TheCall->getNumArgs()
1250 << TheCall->getCallee()->getSourceRange();
1251 return ExprError();
1252 }
Mike Stump11289f42009-09-09 15:08:12 +00001253
Chris Lattnerdc046542009-05-08 06:58:22 +00001254 // Inspect the first argument of the atomic builtin. This should always be
1255 // a pointer type, whose element is an integral scalar or pointer type.
1256 // Because it is a pointer type, we don't have to worry about any implicit
1257 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001258 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001259 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001260 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1261 if (FirstArgResult.isInvalid())
1262 return ExprError();
1263 FirstArg = FirstArgResult.take();
1264 TheCall->setArg(0, FirstArg);
1265
John McCall31168b02011-06-15 23:02:42 +00001266 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1267 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001268 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1269 << FirstArg->getType() << FirstArg->getSourceRange();
1270 return ExprError();
1271 }
Mike Stump11289f42009-09-09 15:08:12 +00001272
John McCall31168b02011-06-15 23:02:42 +00001273 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001274 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001275 !ValType->isBlockPointerType()) {
1276 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1277 << FirstArg->getType() << FirstArg->getSourceRange();
1278 return ExprError();
1279 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001280
John McCall31168b02011-06-15 23:02:42 +00001281 switch (ValType.getObjCLifetime()) {
1282 case Qualifiers::OCL_None:
1283 case Qualifiers::OCL_ExplicitNone:
1284 // okay
1285 break;
1286
1287 case Qualifiers::OCL_Weak:
1288 case Qualifiers::OCL_Strong:
1289 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001290 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001291 << ValType << FirstArg->getSourceRange();
1292 return ExprError();
1293 }
1294
John McCallb50451a2011-10-05 07:41:44 +00001295 // Strip any qualifiers off ValType.
1296 ValType = ValType.getUnqualifiedType();
1297
Chandler Carruth3973af72010-07-18 20:54:12 +00001298 // The majority of builtins return a value, but a few have special return
1299 // types, so allow them to override appropriately below.
1300 QualType ResultType = ValType;
1301
Chris Lattnerdc046542009-05-08 06:58:22 +00001302 // We need to figure out which concrete builtin this maps onto. For example,
1303 // __sync_fetch_and_add with a 2 byte object turns into
1304 // __sync_fetch_and_add_2.
1305#define BUILTIN_ROW(x) \
1306 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1307 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001308
Chris Lattnerdc046542009-05-08 06:58:22 +00001309 static const unsigned BuiltinIndices[][5] = {
1310 BUILTIN_ROW(__sync_fetch_and_add),
1311 BUILTIN_ROW(__sync_fetch_and_sub),
1312 BUILTIN_ROW(__sync_fetch_and_or),
1313 BUILTIN_ROW(__sync_fetch_and_and),
1314 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +00001315
Chris Lattnerdc046542009-05-08 06:58:22 +00001316 BUILTIN_ROW(__sync_add_and_fetch),
1317 BUILTIN_ROW(__sync_sub_and_fetch),
1318 BUILTIN_ROW(__sync_and_and_fetch),
1319 BUILTIN_ROW(__sync_or_and_fetch),
1320 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001321
Chris Lattnerdc046542009-05-08 06:58:22 +00001322 BUILTIN_ROW(__sync_val_compare_and_swap),
1323 BUILTIN_ROW(__sync_bool_compare_and_swap),
1324 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001325 BUILTIN_ROW(__sync_lock_release),
1326 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001327 };
Mike Stump11289f42009-09-09 15:08:12 +00001328#undef BUILTIN_ROW
1329
Chris Lattnerdc046542009-05-08 06:58:22 +00001330 // Determine the index of the size.
1331 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001332 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001333 case 1: SizeIndex = 0; break;
1334 case 2: SizeIndex = 1; break;
1335 case 4: SizeIndex = 2; break;
1336 case 8: SizeIndex = 3; break;
1337 case 16: SizeIndex = 4; break;
1338 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001339 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1340 << FirstArg->getType() << FirstArg->getSourceRange();
1341 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001342 }
Mike Stump11289f42009-09-09 15:08:12 +00001343
Chris Lattnerdc046542009-05-08 06:58:22 +00001344 // Each of these builtins has one pointer argument, followed by some number of
1345 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1346 // that we ignore. Find out which row of BuiltinIndices to read from as well
1347 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001348 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001349 unsigned BuiltinIndex, NumFixed = 1;
1350 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001351 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001352 case Builtin::BI__sync_fetch_and_add:
1353 case Builtin::BI__sync_fetch_and_add_1:
1354 case Builtin::BI__sync_fetch_and_add_2:
1355 case Builtin::BI__sync_fetch_and_add_4:
1356 case Builtin::BI__sync_fetch_and_add_8:
1357 case Builtin::BI__sync_fetch_and_add_16:
1358 BuiltinIndex = 0;
1359 break;
1360
1361 case Builtin::BI__sync_fetch_and_sub:
1362 case Builtin::BI__sync_fetch_and_sub_1:
1363 case Builtin::BI__sync_fetch_and_sub_2:
1364 case Builtin::BI__sync_fetch_and_sub_4:
1365 case Builtin::BI__sync_fetch_and_sub_8:
1366 case Builtin::BI__sync_fetch_and_sub_16:
1367 BuiltinIndex = 1;
1368 break;
1369
1370 case Builtin::BI__sync_fetch_and_or:
1371 case Builtin::BI__sync_fetch_and_or_1:
1372 case Builtin::BI__sync_fetch_and_or_2:
1373 case Builtin::BI__sync_fetch_and_or_4:
1374 case Builtin::BI__sync_fetch_and_or_8:
1375 case Builtin::BI__sync_fetch_and_or_16:
1376 BuiltinIndex = 2;
1377 break;
1378
1379 case Builtin::BI__sync_fetch_and_and:
1380 case Builtin::BI__sync_fetch_and_and_1:
1381 case Builtin::BI__sync_fetch_and_and_2:
1382 case Builtin::BI__sync_fetch_and_and_4:
1383 case Builtin::BI__sync_fetch_and_and_8:
1384 case Builtin::BI__sync_fetch_and_and_16:
1385 BuiltinIndex = 3;
1386 break;
Mike Stump11289f42009-09-09 15:08:12 +00001387
Douglas Gregor73722482011-11-28 16:30:08 +00001388 case Builtin::BI__sync_fetch_and_xor:
1389 case Builtin::BI__sync_fetch_and_xor_1:
1390 case Builtin::BI__sync_fetch_and_xor_2:
1391 case Builtin::BI__sync_fetch_and_xor_4:
1392 case Builtin::BI__sync_fetch_and_xor_8:
1393 case Builtin::BI__sync_fetch_and_xor_16:
1394 BuiltinIndex = 4;
1395 break;
1396
1397 case Builtin::BI__sync_add_and_fetch:
1398 case Builtin::BI__sync_add_and_fetch_1:
1399 case Builtin::BI__sync_add_and_fetch_2:
1400 case Builtin::BI__sync_add_and_fetch_4:
1401 case Builtin::BI__sync_add_and_fetch_8:
1402 case Builtin::BI__sync_add_and_fetch_16:
1403 BuiltinIndex = 5;
1404 break;
1405
1406 case Builtin::BI__sync_sub_and_fetch:
1407 case Builtin::BI__sync_sub_and_fetch_1:
1408 case Builtin::BI__sync_sub_and_fetch_2:
1409 case Builtin::BI__sync_sub_and_fetch_4:
1410 case Builtin::BI__sync_sub_and_fetch_8:
1411 case Builtin::BI__sync_sub_and_fetch_16:
1412 BuiltinIndex = 6;
1413 break;
1414
1415 case Builtin::BI__sync_and_and_fetch:
1416 case Builtin::BI__sync_and_and_fetch_1:
1417 case Builtin::BI__sync_and_and_fetch_2:
1418 case Builtin::BI__sync_and_and_fetch_4:
1419 case Builtin::BI__sync_and_and_fetch_8:
1420 case Builtin::BI__sync_and_and_fetch_16:
1421 BuiltinIndex = 7;
1422 break;
1423
1424 case Builtin::BI__sync_or_and_fetch:
1425 case Builtin::BI__sync_or_and_fetch_1:
1426 case Builtin::BI__sync_or_and_fetch_2:
1427 case Builtin::BI__sync_or_and_fetch_4:
1428 case Builtin::BI__sync_or_and_fetch_8:
1429 case Builtin::BI__sync_or_and_fetch_16:
1430 BuiltinIndex = 8;
1431 break;
1432
1433 case Builtin::BI__sync_xor_and_fetch:
1434 case Builtin::BI__sync_xor_and_fetch_1:
1435 case Builtin::BI__sync_xor_and_fetch_2:
1436 case Builtin::BI__sync_xor_and_fetch_4:
1437 case Builtin::BI__sync_xor_and_fetch_8:
1438 case Builtin::BI__sync_xor_and_fetch_16:
1439 BuiltinIndex = 9;
1440 break;
Mike Stump11289f42009-09-09 15:08:12 +00001441
Chris Lattnerdc046542009-05-08 06:58:22 +00001442 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001443 case Builtin::BI__sync_val_compare_and_swap_1:
1444 case Builtin::BI__sync_val_compare_and_swap_2:
1445 case Builtin::BI__sync_val_compare_and_swap_4:
1446 case Builtin::BI__sync_val_compare_and_swap_8:
1447 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001448 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +00001449 NumFixed = 2;
1450 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001451
Chris Lattnerdc046542009-05-08 06:58:22 +00001452 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001453 case Builtin::BI__sync_bool_compare_and_swap_1:
1454 case Builtin::BI__sync_bool_compare_and_swap_2:
1455 case Builtin::BI__sync_bool_compare_and_swap_4:
1456 case Builtin::BI__sync_bool_compare_and_swap_8:
1457 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001458 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +00001459 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001460 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001461 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001462
1463 case Builtin::BI__sync_lock_test_and_set:
1464 case Builtin::BI__sync_lock_test_and_set_1:
1465 case Builtin::BI__sync_lock_test_and_set_2:
1466 case Builtin::BI__sync_lock_test_and_set_4:
1467 case Builtin::BI__sync_lock_test_and_set_8:
1468 case Builtin::BI__sync_lock_test_and_set_16:
1469 BuiltinIndex = 12;
1470 break;
1471
Chris Lattnerdc046542009-05-08 06:58:22 +00001472 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001473 case Builtin::BI__sync_lock_release_1:
1474 case Builtin::BI__sync_lock_release_2:
1475 case Builtin::BI__sync_lock_release_4:
1476 case Builtin::BI__sync_lock_release_8:
1477 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001478 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001479 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001480 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001481 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001482
1483 case Builtin::BI__sync_swap:
1484 case Builtin::BI__sync_swap_1:
1485 case Builtin::BI__sync_swap_2:
1486 case Builtin::BI__sync_swap_4:
1487 case Builtin::BI__sync_swap_8:
1488 case Builtin::BI__sync_swap_16:
1489 BuiltinIndex = 14;
1490 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001491 }
Mike Stump11289f42009-09-09 15:08:12 +00001492
Chris Lattnerdc046542009-05-08 06:58:22 +00001493 // Now that we know how many fixed arguments we expect, first check that we
1494 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001495 if (TheCall->getNumArgs() < 1+NumFixed) {
1496 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1497 << 0 << 1+NumFixed << TheCall->getNumArgs()
1498 << TheCall->getCallee()->getSourceRange();
1499 return ExprError();
1500 }
Mike Stump11289f42009-09-09 15:08:12 +00001501
Chris Lattner5b9241b2009-05-08 15:36:58 +00001502 // Get the decl for the concrete builtin from this, we can tell what the
1503 // concrete integer type we should convert to is.
1504 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1505 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001506 FunctionDecl *NewBuiltinDecl;
1507 if (NewBuiltinID == BuiltinID)
1508 NewBuiltinDecl = FDecl;
1509 else {
1510 // Perform builtin lookup to avoid redeclaring it.
1511 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1512 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1513 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1514 assert(Res.getFoundDecl());
1515 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1516 if (NewBuiltinDecl == 0)
1517 return ExprError();
1518 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001519
John McCallcf142162010-08-07 06:22:56 +00001520 // The first argument --- the pointer --- has a fixed type; we
1521 // deduce the types of the rest of the arguments accordingly. Walk
1522 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001523 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001524 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001525
Chris Lattnerdc046542009-05-08 06:58:22 +00001526 // GCC does an implicit conversion to the pointer or integer ValType. This
1527 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001528 // Initialize the argument.
1529 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1530 ValType, /*consume*/ false);
1531 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001532 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001533 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001534
Chris Lattnerdc046542009-05-08 06:58:22 +00001535 // Okay, we have something that *can* be converted to the right type. Check
1536 // to see if there is a potentially weird extension going on here. This can
1537 // happen when you do an atomic operation on something like an char* and
1538 // pass in 42. The 42 gets converted to char. This is even more strange
1539 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001540 // FIXME: Do this check.
John McCallb50451a2011-10-05 07:41:44 +00001541 TheCall->setArg(i+1, Arg.take());
Chris Lattnerdc046542009-05-08 06:58:22 +00001542 }
Mike Stump11289f42009-09-09 15:08:12 +00001543
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001544 ASTContext& Context = this->getASTContext();
1545
1546 // Create a new DeclRefExpr to refer to the new decl.
1547 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1548 Context,
1549 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001550 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001551 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001552 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001553 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001554 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001555 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001556
Chris Lattnerdc046542009-05-08 06:58:22 +00001557 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001558 // FIXME: This loses syntactic information.
1559 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1560 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1561 CK_BuiltinFnToFnPtr);
John Wiegley01296292011-04-08 18:41:53 +00001562 TheCall->setCallee(PromotedCall.take());
Mike Stump11289f42009-09-09 15:08:12 +00001563
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001564 // Change the result type of the call to match the original value type. This
1565 // is arbitrary, but the codegen for these builtins ins design to handle it
1566 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001567 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001568
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001569 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001570}
1571
Chris Lattner6436fb62009-02-18 06:01:06 +00001572/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001573/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001574/// Note: It might also make sense to do the UTF-16 conversion here (would
1575/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001576bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001577 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001578 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1579
Douglas Gregorfb65e592011-07-27 05:40:30 +00001580 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001581 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1582 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001583 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001584 }
Mike Stump11289f42009-09-09 15:08:12 +00001585
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001586 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001587 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001588 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001589 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001590 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001591 UTF16 *ToPtr = &ToBuf[0];
1592
1593 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1594 &ToPtr, ToPtr + NumBytes,
1595 strictConversion);
1596 // Check for conversion failure.
1597 if (Result != conversionOK)
1598 Diag(Arg->getLocStart(),
1599 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1600 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001601 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001602}
1603
Chris Lattnere202e6a2007-12-20 00:05:45 +00001604/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1605/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001606bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1607 Expr *Fn = TheCall->getCallee();
1608 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001609 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001610 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001611 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1612 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001613 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001614 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001615 return true;
1616 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001617
1618 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001619 return Diag(TheCall->getLocEnd(),
1620 diag::err_typecheck_call_too_few_args_at_least)
1621 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001622 }
1623
John McCall29ad95b2011-08-27 01:09:30 +00001624 // Type-check the first argument normally.
1625 if (checkBuiltinArgument(*this, TheCall, 0))
1626 return true;
1627
Chris Lattnere202e6a2007-12-20 00:05:45 +00001628 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001629 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001630 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001631 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001632 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001633 else if (FunctionDecl *FD = getCurFunctionDecl())
1634 isVariadic = FD->isVariadic();
1635 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001636 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001637
Chris Lattnere202e6a2007-12-20 00:05:45 +00001638 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001639 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1640 return true;
1641 }
Mike Stump11289f42009-09-09 15:08:12 +00001642
Chris Lattner43be2e62007-12-19 23:59:04 +00001643 // Verify that the second argument to the builtin is the last argument of the
1644 // current function or method.
1645 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001646 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001647
Nico Weber9eea7642013-05-24 23:31:57 +00001648 // These are valid if SecondArgIsLastNamedArgument is false after the next
1649 // block.
1650 QualType Type;
1651 SourceLocation ParamLoc;
1652
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001653 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1654 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001655 // FIXME: This isn't correct for methods (results in bogus warning).
1656 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001657 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001658 if (CurBlock)
1659 LastArg = *(CurBlock->TheDecl->param_end()-1);
1660 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001661 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001662 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001663 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001664 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00001665
1666 Type = PV->getType();
1667 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00001668 }
1669 }
Mike Stump11289f42009-09-09 15:08:12 +00001670
Chris Lattner43be2e62007-12-19 23:59:04 +00001671 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001672 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001673 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00001674 else if (Type->isReferenceType()) {
1675 Diag(Arg->getLocStart(),
1676 diag::warn_va_start_of_reference_type_is_undefined);
1677 Diag(ParamLoc, diag::note_parameter_type) << Type;
1678 }
1679
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00001680 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00001681 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001682}
Chris Lattner43be2e62007-12-19 23:59:04 +00001683
Chris Lattner2da14fb2007-12-20 00:26:33 +00001684/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1685/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001686bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1687 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001688 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001689 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001690 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001691 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001692 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001693 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001694 << SourceRange(TheCall->getArg(2)->getLocStart(),
1695 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001696
John Wiegley01296292011-04-08 18:41:53 +00001697 ExprResult OrigArg0 = TheCall->getArg(0);
1698 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001699
Chris Lattner2da14fb2007-12-20 00:26:33 +00001700 // Do standard promotions between the two arguments, returning their common
1701 // type.
Chris Lattner08464942007-12-28 05:29:59 +00001702 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00001703 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1704 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00001705
1706 // Make sure any conversions are pushed back into the call; this is
1707 // type safe since unordered compare builtins are declared as "_Bool
1708 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00001709 TheCall->setArg(0, OrigArg0.get());
1710 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00001711
John Wiegley01296292011-04-08 18:41:53 +00001712 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00001713 return false;
1714
Chris Lattner2da14fb2007-12-20 00:26:33 +00001715 // If the common type isn't a real floating type, then the arguments were
1716 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001717 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00001718 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001719 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00001720 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1721 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001722
Chris Lattner2da14fb2007-12-20 00:26:33 +00001723 return false;
1724}
1725
Benjamin Kramer634fc102010-02-15 22:42:31 +00001726/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1727/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001728/// to check everything. We expect the last argument to be a floating point
1729/// value.
1730bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1731 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001732 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001733 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001734 if (TheCall->getNumArgs() > NumArgs)
1735 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001736 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001737 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001738 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001739 (*(TheCall->arg_end()-1))->getLocEnd());
1740
Benjamin Kramer64aae502010-02-16 10:07:31 +00001741 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00001742
Eli Friedman7e4faac2009-08-31 20:06:00 +00001743 if (OrigArg->isTypeDependent())
1744 return false;
1745
Chris Lattner68784ef2010-05-06 05:50:07 +00001746 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00001747 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00001748 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001749 diag::err_typecheck_call_invalid_unary_fp)
1750 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001751
Chris Lattner68784ef2010-05-06 05:50:07 +00001752 // If this is an implicit conversion from float -> double, remove it.
1753 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1754 Expr *CastArg = Cast->getSubExpr();
1755 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1756 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1757 "promotion from float to double is the only expected cast here");
1758 Cast->setSubExpr(0);
Chris Lattner68784ef2010-05-06 05:50:07 +00001759 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00001760 }
1761 }
1762
Eli Friedman7e4faac2009-08-31 20:06:00 +00001763 return false;
1764}
1765
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001766/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1767// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00001768ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00001769 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001770 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00001771 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00001772 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1773 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001774
Nate Begemana0110022010-06-08 00:16:34 +00001775 // Determine which of the following types of shufflevector we're checking:
1776 // 1) unary, vector mask: (lhs, mask)
1777 // 2) binary, vector mask: (lhs, rhs, mask)
1778 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1779 QualType resType = TheCall->getArg(0)->getType();
1780 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00001781
Douglas Gregorc25f7662009-05-19 22:10:17 +00001782 if (!TheCall->getArg(0)->isTypeDependent() &&
1783 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00001784 QualType LHSType = TheCall->getArg(0)->getType();
1785 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00001786
Craig Topperbaca3892013-07-29 06:47:04 +00001787 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1788 return ExprError(Diag(TheCall->getLocStart(),
1789 diag::err_shufflevector_non_vector)
1790 << SourceRange(TheCall->getArg(0)->getLocStart(),
1791 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001792
Nate Begemana0110022010-06-08 00:16:34 +00001793 numElements = LHSType->getAs<VectorType>()->getNumElements();
1794 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00001795
Nate Begemana0110022010-06-08 00:16:34 +00001796 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1797 // with mask. If so, verify that RHS is an integer vector type with the
1798 // same number of elts as lhs.
1799 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00001800 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00001801 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00001802 return ExprError(Diag(TheCall->getLocStart(),
1803 diag::err_shufflevector_incompatible_vector)
1804 << SourceRange(TheCall->getArg(1)->getLocStart(),
1805 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001806 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00001807 return ExprError(Diag(TheCall->getLocStart(),
1808 diag::err_shufflevector_incompatible_vector)
1809 << SourceRange(TheCall->getArg(0)->getLocStart(),
1810 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00001811 } else if (numElements != numResElements) {
1812 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00001813 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001814 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001815 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001816 }
1817
1818 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001819 if (TheCall->getArg(i)->isTypeDependent() ||
1820 TheCall->getArg(i)->isValueDependent())
1821 continue;
1822
Nate Begemana0110022010-06-08 00:16:34 +00001823 llvm::APSInt Result(32);
1824 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1825 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001826 diag::err_shufflevector_nonconstant_argument)
1827 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001828
Craig Topper50ad5b72013-08-03 17:40:38 +00001829 // Allow -1 which will be translated to undef in the IR.
1830 if (Result.isSigned() && Result.isAllOnesValue())
1831 continue;
1832
Chris Lattner7ab824e2008-08-10 02:05:13 +00001833 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001834 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001835 diag::err_shufflevector_argument_too_large)
1836 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001837 }
1838
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001839 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001840
Chris Lattner7ab824e2008-08-10 02:05:13 +00001841 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001842 exprs.push_back(TheCall->getArg(i));
1843 TheCall->setArg(i, 0);
1844 }
1845
Benjamin Kramerc215e762012-08-24 11:54:20 +00001846 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek5a201952009-02-07 01:47:29 +00001847 TheCall->getCallee()->getLocStart(),
1848 TheCall->getRParenLoc()));
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001849}
Chris Lattner43be2e62007-12-19 23:59:04 +00001850
Hal Finkelc4d7c822013-09-18 03:29:45 +00001851/// SemaConvertVectorExpr - Handle __builtin_convertvector
1852ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1853 SourceLocation BuiltinLoc,
1854 SourceLocation RParenLoc) {
1855 ExprValueKind VK = VK_RValue;
1856 ExprObjectKind OK = OK_Ordinary;
1857 QualType DstTy = TInfo->getType();
1858 QualType SrcTy = E->getType();
1859
1860 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1861 return ExprError(Diag(BuiltinLoc,
1862 diag::err_convertvector_non_vector)
1863 << E->getSourceRange());
1864 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1865 return ExprError(Diag(BuiltinLoc,
1866 diag::err_convertvector_non_vector_type));
1867
1868 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1869 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1870 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1871 if (SrcElts != DstElts)
1872 return ExprError(Diag(BuiltinLoc,
1873 diag::err_convertvector_incompatible_vector)
1874 << E->getSourceRange());
1875 }
1876
1877 return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
1878 BuiltinLoc, RParenLoc));
1879
1880}
1881
Daniel Dunbarb7257262008-07-21 22:59:13 +00001882/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1883// This is declared to take (const void*, ...) and can take two
1884// optional constant int args.
1885bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00001886 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001887
Chris Lattner3b054132008-11-19 05:08:23 +00001888 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001889 return Diag(TheCall->getLocEnd(),
1890 diag::err_typecheck_call_too_many_args_at_most)
1891 << 0 /*function call*/ << 3 << NumArgs
1892 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001893
1894 // Argument 0 is checked for us and the remaining arguments must be
1895 // constant integers.
Chris Lattner3b054132008-11-19 05:08:23 +00001896 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbarb7257262008-07-21 22:59:13 +00001897 Expr *Arg = TheCall->getArg(i);
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001898
1899 // We can't check the value of a dependent argument.
1900 if (Arg->isTypeDependent() || Arg->isValueDependent())
1901 continue;
1902
Eli Friedman5efba262009-12-04 00:30:06 +00001903 llvm::APSInt Result;
Eric Christopher8d0c6212010-04-17 02:26:23 +00001904 if (SemaBuiltinConstantArg(TheCall, i, Result))
1905 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001906
Daniel Dunbarb7257262008-07-21 22:59:13 +00001907 // FIXME: gcc issues a warning and rewrites these to 0. These
1908 // seems especially odd for the third argument since the default
1909 // is 3.
Chris Lattner3b054132008-11-19 05:08:23 +00001910 if (i == 1) {
Eli Friedman5efba262009-12-04 00:30:06 +00001911 if (Result.getLimitedValue() > 1)
Chris Lattner3b054132008-11-19 05:08:23 +00001912 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001913 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001914 } else {
Eli Friedman5efba262009-12-04 00:30:06 +00001915 if (Result.getLimitedValue() > 3)
Chris Lattner3b054132008-11-19 05:08:23 +00001916 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001917 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001918 }
1919 }
1920
Chris Lattner3b054132008-11-19 05:08:23 +00001921 return false;
Daniel Dunbarb7257262008-07-21 22:59:13 +00001922}
1923
Eric Christopher8d0c6212010-04-17 02:26:23 +00001924/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1925/// TheCall is a constant expression.
1926bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1927 llvm::APSInt &Result) {
1928 Expr *Arg = TheCall->getArg(ArgNum);
1929 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1930 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1931
1932 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1933
1934 if (!Arg->isIntegerConstantExpr(Result, Context))
1935 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00001936 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00001937
Chris Lattnerd545ad12009-09-23 06:06:36 +00001938 return false;
1939}
1940
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001941/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1942/// int type). This simply type checks that type is one of the defined
1943/// constants (0-3).
Chris Lattner57540c52011-04-15 05:22:18 +00001944// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001945bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00001946 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001947
1948 // We can't check the value of a dependent argument.
1949 if (TheCall->getArg(1)->isTypeDependent() ||
1950 TheCall->getArg(1)->isValueDependent())
1951 return false;
1952
Eric Christopher8d0c6212010-04-17 02:26:23 +00001953 // Check constant-ness first.
1954 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1955 return true;
1956
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001957 Expr *Arg = TheCall->getArg(1);
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001958 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattner3b054132008-11-19 05:08:23 +00001959 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1960 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001961 }
1962
1963 return false;
1964}
1965
Eli Friedmanc97d0142009-05-03 06:04:26 +00001966/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00001967/// This checks that val is a constant 1.
1968bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1969 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00001970 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00001971
Eric Christopher8d0c6212010-04-17 02:26:23 +00001972 // TODO: This is less than ideal. Overload this to take a value.
1973 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1974 return true;
1975
1976 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00001977 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1978 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1979
1980 return false;
1981}
1982
Richard Smithd7293d72013-08-05 18:49:43 +00001983namespace {
1984enum StringLiteralCheckType {
1985 SLCT_NotALiteral,
1986 SLCT_UncheckedLiteral,
1987 SLCT_CheckedLiteral
1988};
1989}
1990
Richard Smith55ce3522012-06-25 20:30:08 +00001991// Determine if an expression is a string literal or constant string.
1992// If this function returns false on the arguments to a function expecting a
1993// format string, we will usually need to emit a warning.
1994// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00001995static StringLiteralCheckType
1996checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
1997 bool HasVAListArg, unsigned format_idx,
1998 unsigned firstDataArg, Sema::FormatStringType Type,
1999 Sema::VariadicCallType CallType, bool InFunctionCall,
2000 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002001 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002002 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002003 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002004
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002005 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002006
Richard Smithd7293d72013-08-05 18:49:43 +00002007 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002008 // Technically -Wformat-nonliteral does not warn about this case.
2009 // The behavior of printf and friends in this case is implementation
2010 // dependent. Ideally if the format string cannot be null then
2011 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002012 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002013
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002014 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002015 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002016 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002017 // The expression is a literal if both sub-expressions were, and it was
2018 // completely checked only if both sub-expressions were checked.
2019 const AbstractConditionalOperator *C =
2020 cast<AbstractConditionalOperator>(E);
2021 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002022 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002023 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002024 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002025 if (Left == SLCT_NotALiteral)
2026 return SLCT_NotALiteral;
2027 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002028 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002029 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002030 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002031 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002032 }
2033
2034 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002035 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2036 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002037 }
2038
John McCallc07a0c72011-02-17 10:25:35 +00002039 case Stmt::OpaqueValueExprClass:
2040 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2041 E = src;
2042 goto tryAgain;
2043 }
Richard Smith55ce3522012-06-25 20:30:08 +00002044 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002045
Ted Kremeneka8890832011-02-24 23:03:04 +00002046 case Stmt::PredefinedExprClass:
2047 // While __func__, etc., are technically not string literals, they
2048 // cannot contain format specifiers and thus are not a security
2049 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002050 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002051
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002052 case Stmt::DeclRefExprClass: {
2053 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002054
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002055 // As an exception, do not flag errors for variables binding to
2056 // const string literals.
2057 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2058 bool isConstant = false;
2059 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002060
Richard Smithd7293d72013-08-05 18:49:43 +00002061 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2062 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002063 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002064 isConstant = T.isConstant(S.Context) &&
2065 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002066 } else if (T->isObjCObjectPointerType()) {
2067 // In ObjC, there is usually no "const ObjectPointer" type,
2068 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002069 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002070 }
Mike Stump11289f42009-09-09 15:08:12 +00002071
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002072 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002073 if (const Expr *Init = VD->getAnyInitializer()) {
2074 // Look through initializers like const char c[] = { "foo" }
2075 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2076 if (InitList->isStringLiteralInit())
2077 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2078 }
Richard Smithd7293d72013-08-05 18:49:43 +00002079 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002080 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002081 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002082 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002083 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002084 }
Mike Stump11289f42009-09-09 15:08:12 +00002085
Anders Carlssonb012ca92009-06-28 19:55:58 +00002086 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2087 // special check to see if the format string is a function parameter
2088 // of the function calling the printf function. If the function
2089 // has an attribute indicating it is a printf-like function, then we
2090 // should suppress warnings concerning non-literals being used in a call
2091 // to a vprintf function. For example:
2092 //
2093 // void
2094 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2095 // va_list ap;
2096 // va_start(ap, fmt);
2097 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2098 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002099 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002100 if (HasVAListArg) {
2101 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2102 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2103 int PVIndex = PV->getFunctionScopeIndex() + 1;
2104 for (specific_attr_iterator<FormatAttr>
2105 i = ND->specific_attr_begin<FormatAttr>(),
2106 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
2107 FormatAttr *PVFormat = *i;
2108 // adjust for implicit parameter
2109 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2110 if (MD->isInstance())
2111 ++PVIndex;
2112 // We also check if the formats are compatible.
2113 // We can't pass a 'scanf' string to a 'printf' function.
2114 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002115 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002116 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002117 }
2118 }
2119 }
2120 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002121 }
Mike Stump11289f42009-09-09 15:08:12 +00002122
Richard Smith55ce3522012-06-25 20:30:08 +00002123 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002124 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002125
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002126 case Stmt::CallExprClass:
2127 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002128 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002129 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2130 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2131 unsigned ArgIndex = FA->getFormatIdx();
2132 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2133 if (MD->isInstance())
2134 --ArgIndex;
2135 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002136
Richard Smithd7293d72013-08-05 18:49:43 +00002137 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002138 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002139 Type, CallType, InFunctionCall,
2140 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002141 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2142 unsigned BuiltinID = FD->getBuiltinID();
2143 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2144 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2145 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002146 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002147 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002148 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002149 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002150 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002151 }
2152 }
Mike Stump11289f42009-09-09 15:08:12 +00002153
Richard Smith55ce3522012-06-25 20:30:08 +00002154 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002155 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002156 case Stmt::ObjCStringLiteralClass:
2157 case Stmt::StringLiteralClass: {
2158 const StringLiteral *StrE = NULL;
Mike Stump11289f42009-09-09 15:08:12 +00002159
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002160 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002161 StrE = ObjCFExpr->getString();
2162 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002163 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002164
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002165 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002166 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2167 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002168 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002169 }
Mike Stump11289f42009-09-09 15:08:12 +00002170
Richard Smith55ce3522012-06-25 20:30:08 +00002171 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002172 }
Mike Stump11289f42009-09-09 15:08:12 +00002173
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002174 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002175 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002176 }
2177}
2178
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002179Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002180 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002181 .Case("scanf", FST_Scanf)
2182 .Cases("printf", "printf0", FST_Printf)
2183 .Cases("NSString", "CFString", FST_NSString)
2184 .Case("strftime", FST_Strftime)
2185 .Case("strfmon", FST_Strfmon)
2186 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2187 .Default(FST_Unknown);
2188}
2189
Jordan Rose3e0ec582012-07-19 18:10:23 +00002190/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002191/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002192/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002193bool Sema::CheckFormatArguments(const FormatAttr *Format,
2194 ArrayRef<const Expr *> Args,
2195 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002196 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002197 SourceLocation Loc, SourceRange Range,
2198 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002199 FormatStringInfo FSI;
2200 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002201 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002202 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002203 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002204 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002205}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002206
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002207bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002208 bool HasVAListArg, unsigned format_idx,
2209 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002210 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002211 SourceLocation Loc, SourceRange Range,
2212 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002213 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002214 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002215 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002216 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002217 }
Mike Stump11289f42009-09-09 15:08:12 +00002218
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002219 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002220
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002221 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002222 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002223 // Dynamically generated format strings are difficult to
2224 // automatically vet at compile time. Requiring that format strings
2225 // are string literals: (1) permits the checking of format strings by
2226 // the compiler and thereby (2) can practically remove the source of
2227 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002228
Mike Stump11289f42009-09-09 15:08:12 +00002229 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002230 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002231 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002232 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002233 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002234 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2235 format_idx, firstDataArg, Type, CallType,
2236 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002237 if (CT != SLCT_NotALiteral)
2238 // Literal format string found, check done!
2239 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002240
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002241 // Strftime is particular as it always uses a single 'time' argument,
2242 // so it is safe to pass a non-literal string.
2243 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002244 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002245
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002246 // Do not emit diag when the string param is a macro expansion and the
2247 // format is either NSString or CFString. This is a hack to prevent
2248 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2249 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002250 if (Type == FST_NSString &&
2251 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002252 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002253
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002254 // If there are no arguments specified, warn with -Wformat-security, otherwise
2255 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002256 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002257 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002258 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002259 << OrigFormatExpr->getSourceRange();
2260 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002261 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002262 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002263 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002264 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002265}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002266
Ted Kremenekab278de2010-01-28 23:39:18 +00002267namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002268class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2269protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002270 Sema &S;
2271 const StringLiteral *FExpr;
2272 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002273 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002274 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002275 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002276 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002277 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002278 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002279 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002280 bool usesPositionalArgs;
2281 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002282 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002283 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002284 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002285public:
Ted Kremenek02087932010-07-16 02:11:22 +00002286 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002287 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002288 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002289 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002290 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002291 Sema::VariadicCallType callType,
2292 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002293 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002294 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2295 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002296 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002297 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002298 inFunctionCall(inFunctionCall), CallType(callType),
2299 CheckedVarArgs(CheckedVarArgs) {
2300 CoveredArgs.resize(numDataArgs);
2301 CoveredArgs.reset();
2302 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002303
Ted Kremenek019d2242010-01-29 01:50:07 +00002304 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002305
Ted Kremenek02087932010-07-16 02:11:22 +00002306 void HandleIncompleteSpecifier(const char *startSpecifier,
2307 unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002308
Jordan Rose92303592012-09-08 04:00:03 +00002309 void HandleInvalidLengthModifier(
2310 const analyze_format_string::FormatSpecifier &FS,
2311 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002312 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002313
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002314 void HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002315 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002316 const char *startSpecifier, unsigned specifierLen);
2317
2318 void HandleNonStandardConversionSpecifier(
2319 const analyze_format_string::ConversionSpecifier &CS,
2320 const char *startSpecifier, unsigned specifierLen);
2321
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002322 virtual void HandlePosition(const char *startPos, unsigned posLen);
2323
Ted Kremenekd1668192010-02-27 01:41:03 +00002324 virtual void HandleInvalidPosition(const char *startSpecifier,
2325 unsigned specifierLen,
Ted Kremenek02087932010-07-16 02:11:22 +00002326 analyze_format_string::PositionContext p);
Ted Kremenekd1668192010-02-27 01:41:03 +00002327
2328 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2329
Ted Kremenekab278de2010-01-28 23:39:18 +00002330 void HandleNullChar(const char *nullCharacter);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002331
Richard Trieu03cf7b72011-10-28 00:41:25 +00002332 template <typename Range>
2333 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2334 const Expr *ArgumentExpr,
2335 PartialDiagnostic PDiag,
2336 SourceLocation StringLoc,
2337 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002338 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002339
Ted Kremenek02087932010-07-16 02:11:22 +00002340protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002341 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2342 const char *startSpec,
2343 unsigned specifierLen,
2344 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002345
2346 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2347 const char *startSpec,
2348 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002349
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002350 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002351 CharSourceRange getSpecifierRange(const char *startSpecifier,
2352 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002353 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002354
Ted Kremenek5739de72010-01-29 01:06:55 +00002355 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002356
2357 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2358 const analyze_format_string::ConversionSpecifier &CS,
2359 const char *startSpecifier, unsigned specifierLen,
2360 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002361
2362 template <typename Range>
2363 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2364 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002365 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002366
2367 void CheckPositionalAndNonpositionalArgs(
2368 const analyze_format_string::FormatSpecifier *FS);
Ted Kremenekab278de2010-01-28 23:39:18 +00002369};
2370}
2371
Ted Kremenek02087932010-07-16 02:11:22 +00002372SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002373 return OrigFormatExpr->getSourceRange();
2374}
2375
Ted Kremenek02087932010-07-16 02:11:22 +00002376CharSourceRange CheckFormatHandler::
2377getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002378 SourceLocation Start = getLocationOfByte(startSpecifier);
2379 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2380
2381 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002382 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002383
2384 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002385}
2386
Ted Kremenek02087932010-07-16 02:11:22 +00002387SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002388 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002389}
2390
Ted Kremenek02087932010-07-16 02:11:22 +00002391void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2392 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002393 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2394 getLocationOfByte(startSpecifier),
2395 /*IsStringLocation*/true,
2396 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002397}
2398
Jordan Rose92303592012-09-08 04:00:03 +00002399void CheckFormatHandler::HandleInvalidLengthModifier(
2400 const analyze_format_string::FormatSpecifier &FS,
2401 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002402 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002403 using namespace analyze_format_string;
2404
2405 const LengthModifier &LM = FS.getLengthModifier();
2406 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2407
2408 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002409 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002410 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002411 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002412 getLocationOfByte(LM.getStart()),
2413 /*IsStringLocation*/true,
2414 getSpecifierRange(startSpecifier, specifierLen));
2415
2416 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2417 << FixedLM->toString()
2418 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2419
2420 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002421 FixItHint Hint;
2422 if (DiagID == diag::warn_format_nonsensical_length)
2423 Hint = FixItHint::CreateRemoval(LMRange);
2424
2425 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002426 getLocationOfByte(LM.getStart()),
2427 /*IsStringLocation*/true,
2428 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002429 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002430 }
2431}
2432
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002433void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002434 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002435 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002436 using namespace analyze_format_string;
2437
2438 const LengthModifier &LM = FS.getLengthModifier();
2439 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2440
2441 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002442 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002443 if (FixedLM) {
2444 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2445 << LM.toString() << 0,
2446 getLocationOfByte(LM.getStart()),
2447 /*IsStringLocation*/true,
2448 getSpecifierRange(startSpecifier, specifierLen));
2449
2450 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2451 << FixedLM->toString()
2452 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2453
2454 } else {
2455 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2456 << LM.toString() << 0,
2457 getLocationOfByte(LM.getStart()),
2458 /*IsStringLocation*/true,
2459 getSpecifierRange(startSpecifier, specifierLen));
2460 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002461}
2462
2463void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2464 const analyze_format_string::ConversionSpecifier &CS,
2465 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002466 using namespace analyze_format_string;
2467
2468 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002469 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002470 if (FixedCS) {
2471 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2472 << CS.toString() << /*conversion specifier*/1,
2473 getLocationOfByte(CS.getStart()),
2474 /*IsStringLocation*/true,
2475 getSpecifierRange(startSpecifier, specifierLen));
2476
2477 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2478 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2479 << FixedCS->toString()
2480 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2481 } else {
2482 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2483 << CS.toString() << /*conversion specifier*/1,
2484 getLocationOfByte(CS.getStart()),
2485 /*IsStringLocation*/true,
2486 getSpecifierRange(startSpecifier, specifierLen));
2487 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002488}
2489
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002490void CheckFormatHandler::HandlePosition(const char *startPos,
2491 unsigned posLen) {
2492 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2493 getLocationOfByte(startPos),
2494 /*IsStringLocation*/true,
2495 getSpecifierRange(startPos, posLen));
2496}
2497
Ted Kremenekd1668192010-02-27 01:41:03 +00002498void
Ted Kremenek02087932010-07-16 02:11:22 +00002499CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2500 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002501 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2502 << (unsigned) p,
2503 getLocationOfByte(startPos), /*IsStringLocation*/true,
2504 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002505}
2506
Ted Kremenek02087932010-07-16 02:11:22 +00002507void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002508 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002509 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2510 getLocationOfByte(startPos),
2511 /*IsStringLocation*/true,
2512 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002513}
2514
Ted Kremenek02087932010-07-16 02:11:22 +00002515void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002516 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002517 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002518 EmitFormatDiagnostic(
2519 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2520 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2521 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002522 }
Ted Kremenek02087932010-07-16 02:11:22 +00002523}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002524
Jordan Rose58bbe422012-07-19 18:10:08 +00002525// Note that this may return NULL if there was an error parsing or building
2526// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002527const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002528 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002529}
2530
2531void CheckFormatHandler::DoneProcessing() {
2532 // Does the number of data arguments exceed the number of
2533 // format conversions in the format string?
2534 if (!HasVAListArg) {
2535 // Find any arguments that weren't covered.
2536 CoveredArgs.flip();
2537 signed notCoveredArg = CoveredArgs.find_first();
2538 if (notCoveredArg >= 0) {
2539 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002540 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2541 SourceLocation Loc = E->getLocStart();
2542 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2543 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2544 Loc, /*IsStringLocation*/false,
2545 getFormatStringRange());
2546 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002547 }
Ted Kremenek02087932010-07-16 02:11:22 +00002548 }
2549 }
2550}
2551
Ted Kremenekce815422010-07-19 21:25:57 +00002552bool
2553CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2554 SourceLocation Loc,
2555 const char *startSpec,
2556 unsigned specifierLen,
2557 const char *csStart,
2558 unsigned csLen) {
2559
2560 bool keepGoing = true;
2561 if (argIndex < NumDataArgs) {
2562 // Consider the argument coverered, even though the specifier doesn't
2563 // make sense.
2564 CoveredArgs.set(argIndex);
2565 }
2566 else {
2567 // If argIndex exceeds the number of data arguments we
2568 // don't issue a warning because that is just a cascade of warnings (and
2569 // they may have intended '%%' anyway). We don't want to continue processing
2570 // the format string after this point, however, as we will like just get
2571 // gibberish when trying to match arguments.
2572 keepGoing = false;
2573 }
2574
Richard Trieu03cf7b72011-10-28 00:41:25 +00002575 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2576 << StringRef(csStart, csLen),
2577 Loc, /*IsStringLocation*/true,
2578 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00002579
2580 return keepGoing;
2581}
2582
Richard Trieu03cf7b72011-10-28 00:41:25 +00002583void
2584CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2585 const char *startSpec,
2586 unsigned specifierLen) {
2587 EmitFormatDiagnostic(
2588 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2589 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2590}
2591
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002592bool
2593CheckFormatHandler::CheckNumArgs(
2594 const analyze_format_string::FormatSpecifier &FS,
2595 const analyze_format_string::ConversionSpecifier &CS,
2596 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2597
2598 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002599 PartialDiagnostic PDiag = FS.usesPositionalArg()
2600 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2601 << (argIndex+1) << NumDataArgs)
2602 : S.PDiag(diag::warn_printf_insufficient_data_args);
2603 EmitFormatDiagnostic(
2604 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2605 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002606 return false;
2607 }
2608 return true;
2609}
2610
Richard Trieu03cf7b72011-10-28 00:41:25 +00002611template<typename Range>
2612void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2613 SourceLocation Loc,
2614 bool IsStringLocation,
2615 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002616 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002617 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002618 Loc, IsStringLocation, StringRange, FixIt);
2619}
2620
2621/// \brief If the format string is not within the funcion call, emit a note
2622/// so that the function call and string are in diagnostic messages.
2623///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002624/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00002625/// call and only one diagnostic message will be produced. Otherwise, an
2626/// extra note will be emitted pointing to location of the format string.
2627///
2628/// \param ArgumentExpr the expression that is passed as the format string
2629/// argument in the function call. Used for getting locations when two
2630/// diagnostics are emitted.
2631///
2632/// \param PDiag the callee should already have provided any strings for the
2633/// diagnostic message. This function only adds locations and fixits
2634/// to diagnostics.
2635///
2636/// \param Loc primary location for diagnostic. If two diagnostics are
2637/// required, one will be at Loc and a new SourceLocation will be created for
2638/// the other one.
2639///
2640/// \param IsStringLocation if true, Loc points to the format string should be
2641/// used for the note. Otherwise, Loc points to the argument list and will
2642/// be used with PDiag.
2643///
2644/// \param StringRange some or all of the string to highlight. This is
2645/// templated so it can accept either a CharSourceRange or a SourceRange.
2646///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002647/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002648template<typename Range>
2649void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2650 const Expr *ArgumentExpr,
2651 PartialDiagnostic PDiag,
2652 SourceLocation Loc,
2653 bool IsStringLocation,
2654 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002655 ArrayRef<FixItHint> FixIt) {
2656 if (InFunctionCall) {
2657 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2658 D << StringRange;
2659 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2660 I != E; ++I) {
2661 D << *I;
2662 }
2663 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002664 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2665 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00002666
2667 const Sema::SemaDiagnosticBuilder &Note =
2668 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2669 diag::note_format_string_defined);
2670
2671 Note << StringRange;
2672 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2673 I != E; ++I) {
2674 Note << *I;
2675 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00002676 }
2677}
2678
Ted Kremenek02087932010-07-16 02:11:22 +00002679//===--- CHECK: Printf format string checking ------------------------------===//
2680
2681namespace {
2682class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002683 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00002684public:
2685 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2686 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002687 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00002688 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002689 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002690 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002691 Sema::VariadicCallType CallType,
2692 llvm::SmallBitVector &CheckedVarArgs)
2693 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2694 numDataArgs, beg, hasVAListArg, Args,
2695 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2696 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00002697 {}
2698
Ted Kremenek02087932010-07-16 02:11:22 +00002699
2700 bool HandleInvalidPrintfConversionSpecifier(
2701 const analyze_printf::PrintfSpecifier &FS,
2702 const char *startSpecifier,
2703 unsigned specifierLen);
2704
2705 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2706 const char *startSpecifier,
2707 unsigned specifierLen);
Richard Smith55ce3522012-06-25 20:30:08 +00002708 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2709 const char *StartSpecifier,
2710 unsigned SpecifierLen,
2711 const Expr *E);
2712
Ted Kremenek02087932010-07-16 02:11:22 +00002713 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2714 const char *startSpecifier, unsigned specifierLen);
2715 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2716 const analyze_printf::OptionalAmount &Amt,
2717 unsigned type,
2718 const char *startSpecifier, unsigned specifierLen);
2719 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2720 const analyze_printf::OptionalFlag &flag,
2721 const char *startSpecifier, unsigned specifierLen);
2722 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2723 const analyze_printf::OptionalFlag &ignoredFlag,
2724 const analyze_printf::OptionalFlag &flag,
2725 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002726 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith55ce3522012-06-25 20:30:08 +00002727 const Expr *E, const CharSourceRange &CSR);
2728
Ted Kremenek02087932010-07-16 02:11:22 +00002729};
2730}
2731
2732bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2733 const analyze_printf::PrintfSpecifier &FS,
2734 const char *startSpecifier,
2735 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002736 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00002737 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00002738
Ted Kremenekce815422010-07-19 21:25:57 +00002739 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2740 getLocationOfByte(CS.getStart()),
2741 startSpecifier, specifierLen,
2742 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00002743}
2744
Ted Kremenek02087932010-07-16 02:11:22 +00002745bool CheckPrintfHandler::HandleAmount(
2746 const analyze_format_string::OptionalAmount &Amt,
2747 unsigned k, const char *startSpecifier,
2748 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002749
2750 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002751 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00002752 unsigned argIndex = Amt.getArgIndex();
2753 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002754 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2755 << k,
2756 getLocationOfByte(Amt.getStart()),
2757 /*IsStringLocation*/true,
2758 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002759 // Don't do any more checking. We will just emit
2760 // spurious errors.
2761 return false;
2762 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002763
Ted Kremenek5739de72010-01-29 01:06:55 +00002764 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00002765 // Although not in conformance with C99, we also allow the argument to be
2766 // an 'unsigned int' as that is a reasonably safe case. GCC also
2767 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00002768 CoveredArgs.set(argIndex);
2769 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00002770 if (!Arg)
2771 return false;
2772
Ted Kremenek5739de72010-01-29 01:06:55 +00002773 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002774
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002775 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2776 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002777
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002778 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002779 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002780 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00002781 << T << Arg->getSourceRange(),
2782 getLocationOfByte(Amt.getStart()),
2783 /*IsStringLocation*/true,
2784 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002785 // Don't do any more checking. We will just emit
2786 // spurious errors.
2787 return false;
2788 }
2789 }
2790 }
2791 return true;
2792}
Ted Kremenek5739de72010-01-29 01:06:55 +00002793
Tom Careb49ec692010-06-17 19:00:27 +00002794void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00002795 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002796 const analyze_printf::OptionalAmount &Amt,
2797 unsigned type,
2798 const char *startSpecifier,
2799 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002800 const analyze_printf::PrintfConversionSpecifier &CS =
2801 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00002802
Richard Trieu03cf7b72011-10-28 00:41:25 +00002803 FixItHint fixit =
2804 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2805 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2806 Amt.getConstantLength()))
2807 : FixItHint();
2808
2809 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2810 << type << CS.toString(),
2811 getLocationOfByte(Amt.getStart()),
2812 /*IsStringLocation*/true,
2813 getSpecifierRange(startSpecifier, specifierLen),
2814 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00002815}
2816
Ted Kremenek02087932010-07-16 02:11:22 +00002817void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002818 const analyze_printf::OptionalFlag &flag,
2819 const char *startSpecifier,
2820 unsigned specifierLen) {
2821 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002822 const analyze_printf::PrintfConversionSpecifier &CS =
2823 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00002824 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2825 << flag.toString() << CS.toString(),
2826 getLocationOfByte(flag.getPosition()),
2827 /*IsStringLocation*/true,
2828 getSpecifierRange(startSpecifier, specifierLen),
2829 FixItHint::CreateRemoval(
2830 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002831}
2832
2833void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00002834 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002835 const analyze_printf::OptionalFlag &ignoredFlag,
2836 const analyze_printf::OptionalFlag &flag,
2837 const char *startSpecifier,
2838 unsigned specifierLen) {
2839 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002840 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2841 << ignoredFlag.toString() << flag.toString(),
2842 getLocationOfByte(ignoredFlag.getPosition()),
2843 /*IsStringLocation*/true,
2844 getSpecifierRange(startSpecifier, specifierLen),
2845 FixItHint::CreateRemoval(
2846 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002847}
2848
Richard Smith55ce3522012-06-25 20:30:08 +00002849// Determines if the specified is a C++ class or struct containing
2850// a member with the specified name and kind (e.g. a CXXMethodDecl named
2851// "c_str()").
2852template<typename MemberKind>
2853static llvm::SmallPtrSet<MemberKind*, 1>
2854CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2855 const RecordType *RT = Ty->getAs<RecordType>();
2856 llvm::SmallPtrSet<MemberKind*, 1> Results;
2857
2858 if (!RT)
2859 return Results;
2860 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2861 if (!RD)
2862 return Results;
2863
2864 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2865 Sema::LookupMemberName);
2866
2867 // We just need to include all members of the right kind turned up by the
2868 // filter, at this point.
2869 if (S.LookupQualifiedName(R, RT->getDecl()))
2870 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2871 NamedDecl *decl = (*I)->getUnderlyingDecl();
2872 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2873 Results.insert(FK);
2874 }
2875 return Results;
2876}
2877
2878// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002879// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00002880// Returns true when a c_str() conversion method is found.
2881bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002882 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith55ce3522012-06-25 20:30:08 +00002883 const CharSourceRange &CSR) {
2884 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2885
2886 MethodSet Results =
2887 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2888
2889 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2890 MI != ME; ++MI) {
2891 const CXXMethodDecl *Method = *MI;
2892 if (Method->getNumParams() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00002893 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00002894 // FIXME: Suggest parens if the expression needs them.
2895 SourceLocation EndLoc =
2896 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2897 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2898 << "c_str()"
2899 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2900 return true;
2901 }
2902 }
2903
2904 return false;
2905}
2906
Ted Kremenekab278de2010-01-28 23:39:18 +00002907bool
Ted Kremenek02087932010-07-16 02:11:22 +00002908CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00002909 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00002910 const char *startSpecifier,
2911 unsigned specifierLen) {
2912
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002913 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00002914 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002915 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00002916
Ted Kremenek6cd69422010-07-19 22:01:06 +00002917 if (FS.consumesDataArgument()) {
2918 if (atFirstArg) {
2919 atFirstArg = false;
2920 usesPositionalArgs = FS.usesPositionalArg();
2921 }
2922 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002923 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2924 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00002925 return false;
2926 }
Ted Kremenek5739de72010-01-29 01:06:55 +00002927 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002928
Ted Kremenekd1668192010-02-27 01:41:03 +00002929 // First check if the field width, precision, and conversion specifier
2930 // have matching data arguments.
2931 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2932 startSpecifier, specifierLen)) {
2933 return false;
2934 }
2935
2936 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2937 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002938 return false;
2939 }
2940
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002941 if (!CS.consumesDataArgument()) {
2942 // FIXME: Technically specifying a precision or field width here
2943 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00002944 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002945 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002946
Ted Kremenek4a49d982010-02-26 19:18:41 +00002947 // Consume the argument.
2948 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00002949 if (argIndex < NumDataArgs) {
2950 // The check to see if the argIndex is valid will come later.
2951 // We set the bit here because we may exit early from this
2952 // function if we encounter some other error.
2953 CoveredArgs.set(argIndex);
2954 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00002955
2956 // Check for using an Objective-C specific conversion specifier
2957 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002958 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00002959 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2960 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00002961 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002962
Tom Careb49ec692010-06-17 19:00:27 +00002963 // Check for invalid use of field width
2964 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00002965 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00002966 startSpecifier, specifierLen);
2967 }
2968
2969 // Check for invalid use of precision
2970 if (!FS.hasValidPrecision()) {
2971 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2972 startSpecifier, specifierLen);
2973 }
2974
2975 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00002976 if (!FS.hasValidThousandsGroupingPrefix())
2977 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00002978 if (!FS.hasValidLeadingZeros())
2979 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2980 if (!FS.hasValidPlusPrefix())
2981 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00002982 if (!FS.hasValidSpacePrefix())
2983 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00002984 if (!FS.hasValidAlternativeForm())
2985 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2986 if (!FS.hasValidLeftJustified())
2987 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2988
2989 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00002990 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2991 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2992 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00002993 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2994 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2995 startSpecifier, specifierLen);
2996
2997 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00002998 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00002999 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3000 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003001 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003002 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003003 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003004 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3005 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003006
Jordan Rose92303592012-09-08 04:00:03 +00003007 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3008 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3009
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003010 // The remaining checks depend on the data arguments.
3011 if (HasVAListArg)
3012 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003013
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003014 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003015 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003016
Jordan Rose58bbe422012-07-19 18:10:08 +00003017 const Expr *Arg = getDataArg(argIndex);
3018 if (!Arg)
3019 return true;
3020
3021 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003022}
3023
Jordan Roseaee34382012-09-05 22:56:26 +00003024static bool requiresParensToAddCast(const Expr *E) {
3025 // FIXME: We should have a general way to reason about operator
3026 // precedence and whether parens are actually needed here.
3027 // Take care of a few common cases where they aren't.
3028 const Expr *Inside = E->IgnoreImpCasts();
3029 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3030 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3031
3032 switch (Inside->getStmtClass()) {
3033 case Stmt::ArraySubscriptExprClass:
3034 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003035 case Stmt::CharacterLiteralClass:
3036 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003037 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003038 case Stmt::FloatingLiteralClass:
3039 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003040 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003041 case Stmt::ObjCArrayLiteralClass:
3042 case Stmt::ObjCBoolLiteralExprClass:
3043 case Stmt::ObjCBoxedExprClass:
3044 case Stmt::ObjCDictionaryLiteralClass:
3045 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003046 case Stmt::ObjCIvarRefExprClass:
3047 case Stmt::ObjCMessageExprClass:
3048 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003049 case Stmt::ObjCStringLiteralClass:
3050 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003051 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003052 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003053 case Stmt::UnaryOperatorClass:
3054 return false;
3055 default:
3056 return true;
3057 }
3058}
3059
Richard Smith55ce3522012-06-25 20:30:08 +00003060bool
3061CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3062 const char *StartSpecifier,
3063 unsigned SpecifierLen,
3064 const Expr *E) {
3065 using namespace analyze_format_string;
3066 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003067 // Now type check the data expression that matches the
3068 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003069 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3070 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003071 if (!AT.isValid())
3072 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003073
Jordan Rose598ec092012-12-05 18:44:40 +00003074 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003075 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3076 ExprTy = TET->getUnderlyingExpr()->getType();
3077 }
3078
Jordan Rose598ec092012-12-05 18:44:40 +00003079 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003080 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003081
Jordan Rose22b74712012-09-05 22:56:19 +00003082 // Look through argument promotions for our error message's reported type.
3083 // This includes the integral and floating promotions, but excludes array
3084 // and function pointer decay; seeing that an argument intended to be a
3085 // string has type 'char [6]' is probably more confusing than 'char *'.
3086 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3087 if (ICE->getCastKind() == CK_IntegralCast ||
3088 ICE->getCastKind() == CK_FloatingCast) {
3089 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003090 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003091
3092 // Check if we didn't match because of an implicit cast from a 'char'
3093 // or 'short' to an 'int'. This is done because printf is a varargs
3094 // function.
3095 if (ICE->getType() == S.Context.IntTy ||
3096 ICE->getType() == S.Context.UnsignedIntTy) {
3097 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003098 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003099 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003100 }
Jordan Rose98709982012-06-04 22:48:57 +00003101 }
Jordan Rose598ec092012-12-05 18:44:40 +00003102 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3103 // Special case for 'a', which has type 'int' in C.
3104 // Note, however, that we do /not/ want to treat multibyte constants like
3105 // 'MooV' as characters! This form is deprecated but still exists.
3106 if (ExprTy == S.Context.IntTy)
3107 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3108 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003109 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003110
Jordan Rose0e5badd2012-12-05 18:44:49 +00003111 // %C in an Objective-C context prints a unichar, not a wchar_t.
3112 // If the argument is an integer of some kind, believe the %C and suggest
3113 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003114 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003115 if (ObjCContext &&
3116 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3117 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3118 !ExprTy->isCharType()) {
3119 // 'unichar' is defined as a typedef of unsigned short, but we should
3120 // prefer using the typedef if it is visible.
3121 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003122
3123 // While we are here, check if the value is an IntegerLiteral that happens
3124 // to be within the valid range.
3125 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3126 const llvm::APInt &V = IL->getValue();
3127 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3128 return true;
3129 }
3130
Jordan Rose0e5badd2012-12-05 18:44:49 +00003131 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3132 Sema::LookupOrdinaryName);
3133 if (S.LookupName(Result, S.getCurScope())) {
3134 NamedDecl *ND = Result.getFoundDecl();
3135 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3136 if (TD->getUnderlyingType() == IntendedTy)
3137 IntendedTy = S.Context.getTypedefType(TD);
3138 }
3139 }
3140 }
3141
3142 // Special-case some of Darwin's platform-independence types by suggesting
3143 // casts to primitive types that are known to be large enough.
3144 bool ShouldNotPrintDirectly = false;
Jordan Roseaee34382012-09-05 22:56:26 +00003145 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003146 // Use a 'while' to peel off layers of typedefs.
3147 QualType TyTy = IntendedTy;
3148 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseaee34382012-09-05 22:56:26 +00003149 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose0e5badd2012-12-05 18:44:49 +00003150 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseaee34382012-09-05 22:56:26 +00003151 .Case("NSInteger", S.Context.LongTy)
3152 .Case("NSUInteger", S.Context.UnsignedLongTy)
3153 .Case("SInt32", S.Context.IntTy)
3154 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose0e5badd2012-12-05 18:44:49 +00003155 .Default(QualType());
3156
3157 if (!CastTy.isNull()) {
3158 ShouldNotPrintDirectly = true;
3159 IntendedTy = CastTy;
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003160 break;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003161 }
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003162 TyTy = UserTy->desugar();
Jordan Roseaee34382012-09-05 22:56:26 +00003163 }
3164 }
3165
Jordan Rose22b74712012-09-05 22:56:19 +00003166 // We may be able to offer a FixItHint if it is a supported type.
3167 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003168 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003169 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003170
Jordan Rose22b74712012-09-05 22:56:19 +00003171 if (success) {
3172 // Get the fix string from the fixed format specifier
3173 SmallString<16> buf;
3174 llvm::raw_svector_ostream os(buf);
3175 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003176
Jordan Roseaee34382012-09-05 22:56:26 +00003177 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3178
Jordan Rose0e5badd2012-12-05 18:44:49 +00003179 if (IntendedTy == ExprTy) {
3180 // In this case, the specifier is wrong and should be changed to match
3181 // the argument.
3182 EmitFormatDiagnostic(
3183 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3184 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3185 << E->getSourceRange(),
3186 E->getLocStart(),
3187 /*IsStringLocation*/false,
3188 SpecRange,
3189 FixItHint::CreateReplacement(SpecRange, os.str()));
3190
3191 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003192 // The canonical type for formatting this value is different from the
3193 // actual type of the expression. (This occurs, for example, with Darwin's
3194 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3195 // should be printed as 'long' for 64-bit compatibility.)
3196 // Rather than emitting a normal format/argument mismatch, we want to
3197 // add a cast to the recommended type (and correct the format string
3198 // if necessary).
3199 SmallString<16> CastBuf;
3200 llvm::raw_svector_ostream CastFix(CastBuf);
3201 CastFix << "(";
3202 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3203 CastFix << ")";
3204
3205 SmallVector<FixItHint,4> Hints;
3206 if (!AT.matchesType(S.Context, IntendedTy))
3207 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3208
3209 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3210 // If there's already a cast present, just replace it.
3211 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3212 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3213
3214 } else if (!requiresParensToAddCast(E)) {
3215 // If the expression has high enough precedence,
3216 // just write the C-style cast.
3217 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3218 CastFix.str()));
3219 } else {
3220 // Otherwise, add parens around the expression as well as the cast.
3221 CastFix << "(";
3222 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3223 CastFix.str()));
3224
3225 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3226 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3227 }
3228
Jordan Rose0e5badd2012-12-05 18:44:49 +00003229 if (ShouldNotPrintDirectly) {
3230 // The expression has a type that should not be printed directly.
3231 // We extract the name from the typedef because we don't want to show
3232 // the underlying type in the diagnostic.
3233 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseaee34382012-09-05 22:56:26 +00003234
Jordan Rose0e5badd2012-12-05 18:44:49 +00003235 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3236 << Name << IntendedTy
3237 << E->getSourceRange(),
3238 E->getLocStart(), /*IsStringLocation=*/false,
3239 SpecRange, Hints);
3240 } else {
3241 // In this case, the expression could be printed using a different
3242 // specifier, but we've decided that the specifier is probably correct
3243 // and we should cast instead. Just use the normal warning message.
3244 EmitFormatDiagnostic(
3245 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3246 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3247 << E->getSourceRange(),
3248 E->getLocStart(), /*IsStringLocation*/false,
3249 SpecRange, Hints);
3250 }
Jordan Roseaee34382012-09-05 22:56:26 +00003251 }
Jordan Rose22b74712012-09-05 22:56:19 +00003252 } else {
3253 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3254 SpecifierLen);
3255 // Since the warning for passing non-POD types to variadic functions
3256 // was deferred until now, we emit a warning for non-POD
3257 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003258 switch (S.isValidVarArgType(ExprTy)) {
3259 case Sema::VAK_Valid:
3260 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003261 EmitFormatDiagnostic(
Richard Smithd7293d72013-08-05 18:49:43 +00003262 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3263 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3264 << CSR
3265 << E->getSourceRange(),
3266 E->getLocStart(), /*IsStringLocation*/false, CSR);
3267 break;
3268
3269 case Sema::VAK_Undefined:
3270 EmitFormatDiagnostic(
3271 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003272 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003273 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003274 << CallType
3275 << AT.getRepresentativeTypeName(S.Context)
3276 << CSR
3277 << E->getSourceRange(),
3278 E->getLocStart(), /*IsStringLocation*/false, CSR);
Jordan Rose22b74712012-09-05 22:56:19 +00003279 checkForCStrMembers(AT, E, CSR);
Richard Smithd7293d72013-08-05 18:49:43 +00003280 break;
3281
3282 case Sema::VAK_Invalid:
3283 if (ExprTy->isObjCObjectType())
3284 EmitFormatDiagnostic(
3285 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3286 << S.getLangOpts().CPlusPlus11
3287 << ExprTy
3288 << CallType
3289 << AT.getRepresentativeTypeName(S.Context)
3290 << CSR
3291 << E->getSourceRange(),
3292 E->getLocStart(), /*IsStringLocation*/false, CSR);
3293 else
3294 // FIXME: If this is an initializer list, suggest removing the braces
3295 // or inserting a cast to the target type.
3296 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3297 << isa<InitListExpr>(E) << ExprTy << CallType
3298 << AT.getRepresentativeTypeName(S.Context)
3299 << E->getSourceRange();
3300 break;
3301 }
3302
3303 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3304 "format string specifier index out of range");
3305 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003306 }
3307
Ted Kremenekab278de2010-01-28 23:39:18 +00003308 return true;
3309}
3310
Ted Kremenek02087932010-07-16 02:11:22 +00003311//===--- CHECK: Scanf format string checking ------------------------------===//
3312
3313namespace {
3314class CheckScanfHandler : public CheckFormatHandler {
3315public:
3316 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3317 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003318 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003319 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003320 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003321 Sema::VariadicCallType CallType,
3322 llvm::SmallBitVector &CheckedVarArgs)
3323 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3324 numDataArgs, beg, hasVAListArg,
3325 Args, formatIdx, inFunctionCall, CallType,
3326 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003327 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003328
3329 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3330 const char *startSpecifier,
3331 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003332
3333 bool HandleInvalidScanfConversionSpecifier(
3334 const analyze_scanf::ScanfSpecifier &FS,
3335 const char *startSpecifier,
3336 unsigned specifierLen);
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003337
3338 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek02087932010-07-16 02:11:22 +00003339};
Ted Kremenek019d2242010-01-29 01:50:07 +00003340}
Ted Kremenekab278de2010-01-28 23:39:18 +00003341
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003342void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3343 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003344 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3345 getLocationOfByte(end), /*IsStringLocation*/true,
3346 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003347}
3348
Ted Kremenekce815422010-07-19 21:25:57 +00003349bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3350 const analyze_scanf::ScanfSpecifier &FS,
3351 const char *startSpecifier,
3352 unsigned specifierLen) {
3353
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003354 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003355 FS.getConversionSpecifier();
3356
3357 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3358 getLocationOfByte(CS.getStart()),
3359 startSpecifier, specifierLen,
3360 CS.getStart(), CS.getLength());
3361}
3362
Ted Kremenek02087932010-07-16 02:11:22 +00003363bool CheckScanfHandler::HandleScanfSpecifier(
3364 const analyze_scanf::ScanfSpecifier &FS,
3365 const char *startSpecifier,
3366 unsigned specifierLen) {
3367
3368 using namespace analyze_scanf;
3369 using namespace analyze_format_string;
3370
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003371 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003372
Ted Kremenek6cd69422010-07-19 22:01:06 +00003373 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3374 // be used to decide if we are using positional arguments consistently.
3375 if (FS.consumesDataArgument()) {
3376 if (atFirstArg) {
3377 atFirstArg = false;
3378 usesPositionalArgs = FS.usesPositionalArg();
3379 }
3380 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003381 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3382 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003383 return false;
3384 }
Ted Kremenek02087932010-07-16 02:11:22 +00003385 }
3386
3387 // Check if the field with is non-zero.
3388 const OptionalAmount &Amt = FS.getFieldWidth();
3389 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3390 if (Amt.getConstantAmount() == 0) {
3391 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3392 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003393 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3394 getLocationOfByte(Amt.getStart()),
3395 /*IsStringLocation*/true, R,
3396 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003397 }
3398 }
3399
3400 if (!FS.consumesDataArgument()) {
3401 // FIXME: Technically specifying a precision or field width here
3402 // makes no sense. Worth issuing a warning at some point.
3403 return true;
3404 }
3405
3406 // Consume the argument.
3407 unsigned argIndex = FS.getArgIndex();
3408 if (argIndex < NumDataArgs) {
3409 // The check to see if the argIndex is valid will come later.
3410 // We set the bit here because we may exit early from this
3411 // function if we encounter some other error.
3412 CoveredArgs.set(argIndex);
3413 }
3414
Ted Kremenek4407ea42010-07-20 20:04:47 +00003415 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003416 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003417 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3418 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003419 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003420 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003421 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003422 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3423 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003424
Jordan Rose92303592012-09-08 04:00:03 +00003425 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3426 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3427
Ted Kremenek02087932010-07-16 02:11:22 +00003428 // The remaining checks depend on the data arguments.
3429 if (HasVAListArg)
3430 return true;
3431
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003432 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003433 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003434
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003435 // Check that the argument type matches the format specifier.
3436 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003437 if (!Ex)
3438 return true;
3439
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003440 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3441 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003442 ScanfSpecifier fixedFS = FS;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003443 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgd99d6882012-02-15 09:59:46 +00003444 S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003445
3446 if (success) {
3447 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003448 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003449 llvm::raw_svector_ostream os(buf);
3450 fixedFS.toString(os);
3451
3452 EmitFormatDiagnostic(
3453 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003454 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003455 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003456 Ex->getLocStart(),
3457 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003458 getSpecifierRange(startSpecifier, specifierLen),
3459 FixItHint::CreateReplacement(
3460 getSpecifierRange(startSpecifier, specifierLen),
3461 os.str()));
3462 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003463 EmitFormatDiagnostic(
3464 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003465 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003466 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003467 Ex->getLocStart(),
3468 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003469 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003470 }
3471 }
3472
Ted Kremenek02087932010-07-16 02:11:22 +00003473 return true;
3474}
3475
3476void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003477 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003478 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003479 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003480 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003481 bool inFunctionCall, VariadicCallType CallType,
3482 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003483
Ted Kremenekab278de2010-01-28 23:39:18 +00003484 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003485 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003486 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003487 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003488 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3489 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003490 return;
3491 }
Ted Kremenek02087932010-07-16 02:11:22 +00003492
Ted Kremenekab278de2010-01-28 23:39:18 +00003493 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003494 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003495 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003496 // Account for cases where the string literal is truncated in a declaration.
3497 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3498 assert(T && "String literal not of constant array type!");
3499 size_t TypeSize = T->getSize().getZExtValue();
3500 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003501 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003502
3503 // Emit a warning if the string literal is truncated and does not contain an
3504 // embedded null character.
3505 if (TypeSize <= StrRef.size() &&
3506 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3507 CheckFormatHandler::EmitFormatDiagnostic(
3508 *this, inFunctionCall, Args[format_idx],
3509 PDiag(diag::warn_printf_format_string_not_null_terminated),
3510 FExpr->getLocStart(),
3511 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3512 return;
3513 }
3514
Ted Kremenekab278de2010-01-28 23:39:18 +00003515 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00003516 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003517 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003518 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003519 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3520 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003521 return;
3522 }
Ted Kremenek02087932010-07-16 02:11:22 +00003523
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003524 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00003525 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003526 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003527 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003528 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003529
Hans Wennborg23926bd2011-12-15 10:25:47 +00003530 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003531 getLangOpts(),
3532 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003533 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003534 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003535 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003536 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003537 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003538
Hans Wennborg23926bd2011-12-15 10:25:47 +00003539 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003540 getLangOpts(),
3541 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003542 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003543 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00003544}
3545
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003546//===--- CHECK: Standard memory functions ---------------------------------===//
3547
Nico Weber0e6daef2013-12-26 23:38:39 +00003548/// \brief Takes the expression passed to the size_t parameter of functions
3549/// such as memcmp, strncat, etc and warns if it's a comparison.
3550///
3551/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
3552static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
3553 IdentifierInfo *FnName,
3554 SourceLocation FnLoc,
3555 SourceLocation RParenLoc) {
3556 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
3557 if (!Size)
3558 return false;
3559
3560 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
3561 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
3562 return false;
3563
3564 Preprocessor &PP = S.getPreprocessor();
3565 SourceRange SizeRange = Size->getSourceRange();
3566 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
3567 << SizeRange << FnName;
3568 S.Diag(FnLoc, diag::warn_memsize_comparison_paren_note)
3569 << FnName
3570 << FixItHint::CreateInsertion(
3571 PP.getLocForEndOfToken(Size->getLHS()->getLocEnd()),
3572 ")")
3573 << FixItHint::CreateRemoval(RParenLoc);
3574 S.Diag(SizeRange.getBegin(), diag::warn_memsize_comparison_cast_note)
3575 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
3576 << FixItHint::CreateInsertion(
3577 PP.getLocForEndOfToken(SizeRange.getEnd()), ")");
3578
3579 return true;
3580}
3581
Douglas Gregora74926b2011-05-03 20:05:22 +00003582/// \brief Determine whether the given type is a dynamic class type (e.g.,
3583/// whether it has a vtable).
3584static bool isDynamicClassType(QualType T) {
3585 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3586 if (CXXRecordDecl *Definition = Record->getDefinition())
3587 if (Definition->isDynamicClass())
3588 return true;
3589
3590 return false;
3591}
3592
Chandler Carruth889ed862011-06-21 23:04:20 +00003593/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003594/// otherwise returns NULL.
3595static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00003596 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003597 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3598 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3599 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00003600
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003601 return 0;
3602}
3603
Chandler Carruth889ed862011-06-21 23:04:20 +00003604/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003605static QualType getSizeOfArgType(const Expr* E) {
3606 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3607 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3608 if (SizeOf->getKind() == clang::UETT_SizeOf)
3609 return SizeOf->getTypeOfArgument();
3610
3611 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00003612}
3613
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003614/// \brief Check for dangerous or invalid arguments to memset().
3615///
Chandler Carruthac687262011-06-03 06:23:57 +00003616/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00003617/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3618/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003619///
3620/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00003621void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00003622 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00003623 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00003624 assert(BId != 0);
3625
Ted Kremenekb5fabb22011-04-28 01:38:02 +00003626 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00003627 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00003628 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00003629 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00003630 return;
3631
Anna Zaks22122702012-01-17 00:37:07 +00003632 unsigned LastArg = (BId == Builtin::BImemset ||
3633 BId == Builtin::BIstrndup ? 1 : 2);
3634 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00003635 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003636
Nico Weber0e6daef2013-12-26 23:38:39 +00003637 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
3638 Call->getLocStart(), Call->getRParenLoc()))
3639 return;
3640
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003641 // We have special checking when the length is a sizeof expression.
3642 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3643 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3644 llvm::FoldingSetNodeID SizeOfArgID;
3645
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003646 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3647 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00003648 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003649
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003650 QualType DestTy = Dest->getType();
3651 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3652 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00003653
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003654 // Never warn about void type pointers. This can be used to suppress
3655 // false positives.
3656 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003657 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003658
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003659 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3660 // actually comparing the expressions for equality. Because computing the
3661 // expression IDs can be expensive, we only do this if the diagnostic is
3662 // enabled.
3663 if (SizeOfArg &&
3664 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3665 SizeOfArg->getExprLoc())) {
3666 // We only compute IDs for expressions if the warning is enabled, and
3667 // cache the sizeof arg's ID.
3668 if (SizeOfArgID == llvm::FoldingSetNodeID())
3669 SizeOfArg->Profile(SizeOfArgID, Context, true);
3670 llvm::FoldingSetNodeID DestID;
3671 Dest->Profile(DestID, Context, true);
3672 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00003673 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3674 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003675 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00003676 StringRef ReadableName = FnName->getName();
3677
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003678 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00003679 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003680 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00003681 if (!PointeeTy->isIncompleteType() &&
3682 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003683 ActionIdx = 2; // If the pointee's size is sizeof(char),
3684 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00003685
3686 // If the function is defined as a builtin macro, do not show macro
3687 // expansion.
3688 SourceLocation SL = SizeOfArg->getExprLoc();
3689 SourceRange DSR = Dest->getSourceRange();
3690 SourceRange SSR = SizeOfArg->getSourceRange();
3691 SourceManager &SM = PP.getSourceManager();
3692
3693 if (SM.isMacroArgExpansion(SL)) {
3694 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3695 SL = SM.getSpellingLoc(SL);
3696 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3697 SM.getSpellingLoc(DSR.getEnd()));
3698 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3699 SM.getSpellingLoc(SSR.getEnd()));
3700 }
3701
Anna Zaksd08d9152012-05-30 23:14:52 +00003702 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003703 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00003704 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00003705 << PointeeTy
3706 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00003707 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00003708 << SSR);
3709 DiagRuntimeBehavior(SL, SizeOfArg,
3710 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3711 << ActionIdx
3712 << SSR);
3713
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003714 break;
3715 }
3716 }
3717
3718 // Also check for cases where the sizeof argument is the exact same
3719 // type as the memory argument, and where it points to a user-defined
3720 // record type.
3721 if (SizeOfArgTy != QualType()) {
3722 if (PointeeTy->isRecordType() &&
3723 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3724 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3725 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3726 << FnName << SizeOfArgTy << ArgIdx
3727 << PointeeTy << Dest->getSourceRange()
3728 << LenExpr->getSourceRange());
3729 break;
3730 }
Nico Weberc5e73862011-06-14 16:14:58 +00003731 }
3732
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003733 // Always complain about dynamic classes.
Anna Zaks22122702012-01-17 00:37:07 +00003734 if (isDynamicClassType(PointeeTy)) {
3735
3736 unsigned OperationType = 0;
3737 // "overwritten" if we're warning about the destination for any call
3738 // but memcmp; otherwise a verb appropriate to the call.
3739 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3740 if (BId == Builtin::BImemcpy)
3741 OperationType = 1;
3742 else if(BId == Builtin::BImemmove)
3743 OperationType = 2;
3744 else if (BId == Builtin::BImemcmp)
3745 OperationType = 3;
3746 }
3747
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00003748 DiagRuntimeBehavior(
3749 Dest->getExprLoc(), Dest,
3750 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00003751 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaks201d4892012-01-13 21:52:01 +00003752 << FnName << PointeeTy
Anna Zaks22122702012-01-17 00:37:07 +00003753 << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00003754 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00003755 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3756 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00003757 DiagRuntimeBehavior(
3758 Dest->getExprLoc(), Dest,
3759 PDiag(diag::warn_arc_object_memaccess)
3760 << ArgIdx << FnName << PointeeTy
3761 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00003762 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003763 continue;
John McCall31168b02011-06-15 23:02:42 +00003764
3765 DiagRuntimeBehavior(
3766 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00003767 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003768 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3769 break;
3770 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003771 }
3772}
3773
Ted Kremenek6865f772011-08-18 20:55:45 +00003774// A little helper routine: ignore addition and subtraction of integer literals.
3775// This intentionally does not ignore all integer constant expressions because
3776// we don't want to remove sizeof().
3777static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3778 Ex = Ex->IgnoreParenCasts();
3779
3780 for (;;) {
3781 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3782 if (!BO || !BO->isAdditiveOp())
3783 break;
3784
3785 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3786 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3787
3788 if (isa<IntegerLiteral>(RHS))
3789 Ex = LHS;
3790 else if (isa<IntegerLiteral>(LHS))
3791 Ex = RHS;
3792 else
3793 break;
3794 }
3795
3796 return Ex;
3797}
3798
Anna Zaks13b08572012-08-08 21:42:23 +00003799static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3800 ASTContext &Context) {
3801 // Only handle constant-sized or VLAs, but not flexible members.
3802 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3803 // Only issue the FIXIT for arrays of size > 1.
3804 if (CAT->getSize().getSExtValue() <= 1)
3805 return false;
3806 } else if (!Ty->isVariableArrayType()) {
3807 return false;
3808 }
3809 return true;
3810}
3811
Ted Kremenek6865f772011-08-18 20:55:45 +00003812// Warn if the user has made the 'size' argument to strlcpy or strlcat
3813// be the size of the source, instead of the destination.
3814void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3815 IdentifierInfo *FnName) {
3816
3817 // Don't crash if the user has the wrong number of arguments
3818 if (Call->getNumArgs() != 3)
3819 return;
3820
3821 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3822 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3823 const Expr *CompareWithSrc = NULL;
Nico Weber0e6daef2013-12-26 23:38:39 +00003824
3825 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
3826 Call->getLocStart(), Call->getRParenLoc()))
3827 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00003828
3829 // Look for 'strlcpy(dst, x, sizeof(x))'
3830 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3831 CompareWithSrc = Ex;
3832 else {
3833 // Look for 'strlcpy(dst, x, strlen(x))'
3834 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00003835 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
3836 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00003837 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3838 }
3839 }
3840
3841 if (!CompareWithSrc)
3842 return;
3843
3844 // Determine if the argument to sizeof/strlen is equal to the source
3845 // argument. In principle there's all kinds of things you could do
3846 // here, for instance creating an == expression and evaluating it with
3847 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3848 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3849 if (!SrcArgDRE)
3850 return;
3851
3852 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3853 if (!CompareWithSrcDRE ||
3854 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3855 return;
3856
3857 const Expr *OriginalSizeArg = Call->getArg(2);
3858 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3859 << OriginalSizeArg->getSourceRange() << FnName;
3860
3861 // Output a FIXIT hint if the destination is an array (rather than a
3862 // pointer to an array). This could be enhanced to handle some
3863 // pointers if we know the actual size, like if DstArg is 'array+2'
3864 // we could say 'sizeof(array)-2'.
3865 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00003866 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00003867 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00003868
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003869 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00003870 llvm::raw_svector_ostream OS(sizeString);
3871 OS << "sizeof(";
Richard Smith235341b2012-08-16 03:56:14 +00003872 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00003873 OS << ")";
3874
3875 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3876 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3877 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00003878}
3879
Anna Zaks314cd092012-02-01 19:08:57 +00003880/// Check if two expressions refer to the same declaration.
3881static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3882 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3883 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3884 return D1->getDecl() == D2->getDecl();
3885 return false;
3886}
3887
3888static const Expr *getStrlenExprArg(const Expr *E) {
3889 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3890 const FunctionDecl *FD = CE->getDirectCallee();
3891 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3892 return 0;
3893 return CE->getArg(0)->IgnoreParenCasts();
3894 }
3895 return 0;
3896}
3897
3898// Warn on anti-patterns as the 'size' argument to strncat.
3899// The correct size argument should look like following:
3900// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3901void Sema::CheckStrncatArguments(const CallExpr *CE,
3902 IdentifierInfo *FnName) {
3903 // Don't crash if the user has the wrong number of arguments.
3904 if (CE->getNumArgs() < 3)
3905 return;
3906 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3907 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3908 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3909
Nico Weber0e6daef2013-12-26 23:38:39 +00003910 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
3911 CE->getRParenLoc()))
3912 return;
3913
Anna Zaks314cd092012-02-01 19:08:57 +00003914 // Identify common expressions, which are wrongly used as the size argument
3915 // to strncat and may lead to buffer overflows.
3916 unsigned PatternType = 0;
3917 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3918 // - sizeof(dst)
3919 if (referToTheSameDecl(SizeOfArg, DstArg))
3920 PatternType = 1;
3921 // - sizeof(src)
3922 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3923 PatternType = 2;
3924 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3925 if (BE->getOpcode() == BO_Sub) {
3926 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3927 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3928 // - sizeof(dst) - strlen(dst)
3929 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3930 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3931 PatternType = 1;
3932 // - sizeof(src) - (anything)
3933 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3934 PatternType = 2;
3935 }
3936 }
3937
3938 if (PatternType == 0)
3939 return;
3940
Anna Zaks5069aa32012-02-03 01:27:37 +00003941 // Generate the diagnostic.
3942 SourceLocation SL = LenArg->getLocStart();
3943 SourceRange SR = LenArg->getSourceRange();
3944 SourceManager &SM = PP.getSourceManager();
3945
3946 // If the function is defined as a builtin macro, do not show macro expansion.
3947 if (SM.isMacroArgExpansion(SL)) {
3948 SL = SM.getSpellingLoc(SL);
3949 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3950 SM.getSpellingLoc(SR.getEnd()));
3951 }
3952
Anna Zaks13b08572012-08-08 21:42:23 +00003953 // Check if the destination is an array (rather than a pointer to an array).
3954 QualType DstTy = DstArg->getType();
3955 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3956 Context);
3957 if (!isKnownSizeArray) {
3958 if (PatternType == 1)
3959 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3960 else
3961 Diag(SL, diag::warn_strncat_src_size) << SR;
3962 return;
3963 }
3964
Anna Zaks314cd092012-02-01 19:08:57 +00003965 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00003966 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00003967 else
Anna Zaks5069aa32012-02-03 01:27:37 +00003968 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00003969
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003970 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00003971 llvm::raw_svector_ostream OS(sizeString);
3972 OS << "sizeof(";
Richard Smith235341b2012-08-16 03:56:14 +00003973 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00003974 OS << ") - ";
3975 OS << "strlen(";
Richard Smith235341b2012-08-16 03:56:14 +00003976 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00003977 OS << ") - 1";
3978
Anna Zaks5069aa32012-02-03 01:27:37 +00003979 Diag(SL, diag::note_strncat_wrong_size)
3980 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00003981}
3982
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003983//===--- CHECK: Return Address of Stack Variable --------------------------===//
3984
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00003985static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3986 Decl *ParentDecl);
3987static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3988 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003989
3990/// CheckReturnStackAddr - Check if a return statement returns the address
3991/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003992static void
3993CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
3994 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00003995
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00003996 Expr *stackE = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003997 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00003998
3999 // Perform checking for returned stack addresses, local blocks,
4000 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004001 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004002 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004003 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stump12b8ce12009-08-04 21:02:39 +00004004 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004005 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004006 }
4007
4008 if (stackE == 0)
4009 return; // Nothing suspicious was found.
4010
4011 SourceLocation diagLoc;
4012 SourceRange diagRange;
4013 if (refVars.empty()) {
4014 diagLoc = stackE->getLocStart();
4015 diagRange = stackE->getSourceRange();
4016 } else {
4017 // We followed through a reference variable. 'stackE' contains the
4018 // problematic expression but we will warn at the return statement pointing
4019 // at the reference variable. We will later display the "trail" of
4020 // reference variables using notes.
4021 diagLoc = refVars[0]->getLocStart();
4022 diagRange = refVars[0]->getSourceRange();
4023 }
4024
4025 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004026 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004027 : diag::warn_ret_stack_addr)
4028 << DR->getDecl()->getDeclName() << diagRange;
4029 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004030 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004031 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004032 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004033 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004034 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4035 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004036 << diagRange;
4037 }
4038
4039 // Display the "trail" of reference variables that we followed until we
4040 // found the problematic expression using notes.
4041 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4042 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4043 // If this var binds to another reference var, show the range of the next
4044 // var, otherwise the var binds to the problematic expression, in which case
4045 // show the range of the expression.
4046 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4047 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004048 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4049 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004050 }
4051}
4052
4053/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4054/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004055/// to a location on the stack, a local block, an address of a label, or a
4056/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004057/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004058/// encounter a subexpression that (1) clearly does not lead to one of the
4059/// above problematic expressions (2) is something we cannot determine leads to
4060/// a problematic expression based on such local checking.
4061///
4062/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4063/// the expression that they point to. Such variables are added to the
4064/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004065///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004066/// EvalAddr processes expressions that are pointers that are used as
4067/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004068/// At the base case of the recursion is a check for the above problematic
4069/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004070///
4071/// This implementation handles:
4072///
4073/// * pointer-to-pointer casts
4074/// * implicit conversions from array references to pointers
4075/// * taking the address of fields
4076/// * arbitrary interplay between "&" and "*" operators
4077/// * pointer arithmetic from an address of a stack variable
4078/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004079static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4080 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004081 if (E->isTypeDependent())
Craig Topper47005942013-08-02 05:10:31 +00004082 return NULL;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004083
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004084 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00004085 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004086 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004087 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00004088 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00004089
Peter Collingbourne91147592011-04-15 00:35:48 +00004090 E = E->IgnoreParens();
4091
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004092 // Our "symbolic interpreter" is just a dispatch off the currently
4093 // viewed AST node. We then recursively traverse the AST by calling
4094 // EvalAddr and EvalVal appropriately.
4095 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004096 case Stmt::DeclRefExprClass: {
4097 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4098
Richard Smith40f08eb2014-01-30 22:05:38 +00004099 // If we leave the immediate function, the lifetime isn't about to end.
4100 if (DR->refersToEnclosingLocal())
4101 return 0;
4102
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004103 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4104 // If this is a reference variable, follow through to the expression that
4105 // it points to.
4106 if (V->hasLocalStorage() &&
4107 V->getType()->isReferenceType() && V->hasInit()) {
4108 // Add the reference variable to the "trail".
4109 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004110 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004111 }
4112
4113 return NULL;
4114 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004115
Chris Lattner934edb22007-12-28 05:31:15 +00004116 case Stmt::UnaryOperatorClass: {
4117 // The only unary operator that make sense to handle here
4118 // is AddrOf. All others don't make sense as pointers.
4119 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004120
John McCalle3027922010-08-25 11:45:40 +00004121 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004122 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004123 else
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004124 return NULL;
4125 }
Mike Stump11289f42009-09-09 15:08:12 +00004126
Chris Lattner934edb22007-12-28 05:31:15 +00004127 case Stmt::BinaryOperatorClass: {
4128 // Handle pointer arithmetic. All other binary operators are not valid
4129 // in this context.
4130 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00004131 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00004132
John McCalle3027922010-08-25 11:45:40 +00004133 if (op != BO_Add && op != BO_Sub)
Chris Lattner934edb22007-12-28 05:31:15 +00004134 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00004135
Chris Lattner934edb22007-12-28 05:31:15 +00004136 Expr *Base = B->getLHS();
4137
4138 // Determine which argument is the real pointer base. It could be
4139 // the RHS argument instead of the LHS.
4140 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00004141
Chris Lattner934edb22007-12-28 05:31:15 +00004142 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004143 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004144 }
Steve Naroff2752a172008-09-10 19:17:48 +00004145
Chris Lattner934edb22007-12-28 05:31:15 +00004146 // For conditional operators we need to see if either the LHS or RHS are
4147 // valid DeclRefExpr*s. If one of them is valid, we return it.
4148 case Stmt::ConditionalOperatorClass: {
4149 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004150
Chris Lattner934edb22007-12-28 05:31:15 +00004151 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004152 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4153 if (Expr *LHSExpr = C->getLHS()) {
4154 // In C++, we can have a throw-expression, which has 'void' type.
4155 if (!LHSExpr->getType()->isVoidType())
4156 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004157 return LHS;
4158 }
Chris Lattner934edb22007-12-28 05:31:15 +00004159
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004160 // In C++, we can have a throw-expression, which has 'void' type.
4161 if (C->getRHS()->getType()->isVoidType())
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004162 return 0;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004163
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004164 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004165 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004166
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004167 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00004168 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004169 return E; // local block.
4170 return NULL;
4171
4172 case Stmt::AddrLabelExprClass:
4173 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00004174
John McCall28fc7092011-11-10 05:35:25 +00004175 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004176 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4177 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004178
Ted Kremenekc3b4c522008-08-07 00:49:01 +00004179 // For casts, we need to handle conversions from arrays to
4180 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00004181 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00004182 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00004183 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00004184 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00004185 case Stmt::CXXStaticCastExprClass:
4186 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00004187 case Stmt::CXXConstCastExprClass:
4188 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00004189 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4190 switch (cast<CastExpr>(E)->getCastKind()) {
4191 case CK_BitCast:
4192 case CK_LValueToRValue:
4193 case CK_NoOp:
4194 case CK_BaseToDerived:
4195 case CK_DerivedToBase:
4196 case CK_UncheckedDerivedToBase:
4197 case CK_Dynamic:
4198 case CK_CPointerToObjCPointerCast:
4199 case CK_BlockPointerToObjCPointerCast:
4200 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004201 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004202
4203 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004204 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004205
4206 default:
4207 return 0;
4208 }
Chris Lattner934edb22007-12-28 05:31:15 +00004209 }
Mike Stump11289f42009-09-09 15:08:12 +00004210
Douglas Gregorfe314812011-06-21 17:03:29 +00004211 case Stmt::MaterializeTemporaryExprClass:
4212 if (Expr *Result = EvalAddr(
4213 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004214 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004215 return Result;
4216
4217 return E;
4218
Chris Lattner934edb22007-12-28 05:31:15 +00004219 // Everything else: we simply don't reason about them.
4220 default:
4221 return NULL;
4222 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004223}
Mike Stump11289f42009-09-09 15:08:12 +00004224
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004225
4226/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4227/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004228static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4229 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004230do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004231 // We should only be called for evaluating non-pointer expressions, or
4232 // expressions with a pointer type that are not used as references but instead
4233 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00004234
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004235 // Our "symbolic interpreter" is just a dispatch off the currently
4236 // viewed AST node. We then recursively traverse the AST by calling
4237 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00004238
4239 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004240 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004241 case Stmt::ImplicitCastExprClass: {
4242 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00004243 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004244 E = IE->getSubExpr();
4245 continue;
4246 }
4247 return NULL;
4248 }
4249
John McCall28fc7092011-11-10 05:35:25 +00004250 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004251 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004252
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004253 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004254 // When we hit a DeclRefExpr we are looking at code that refers to a
4255 // variable's name. If it's not a reference variable we check if it has
4256 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004257 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004258
Richard Smith40f08eb2014-01-30 22:05:38 +00004259 // If we leave the immediate function, the lifetime isn't about to end.
4260 if (DR->refersToEnclosingLocal())
4261 return 0;
4262
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004263 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4264 // Check if it refers to itself, e.g. "int& i = i;".
4265 if (V == ParentDecl)
4266 return DR;
4267
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004268 if (V->hasLocalStorage()) {
4269 if (!V->getType()->isReferenceType())
4270 return DR;
4271
4272 // Reference variable, follow through to the expression that
4273 // it points to.
4274 if (V->hasInit()) {
4275 // Add the reference variable to the "trail".
4276 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004277 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004278 }
4279 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004280 }
Mike Stump11289f42009-09-09 15:08:12 +00004281
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004282 return NULL;
4283 }
Mike Stump11289f42009-09-09 15:08:12 +00004284
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004285 case Stmt::UnaryOperatorClass: {
4286 // The only unary operator that make sense to handle here
4287 // is Deref. All others don't resolve to a "name." This includes
4288 // handling all sorts of rvalues passed to a unary operator.
4289 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004290
John McCalle3027922010-08-25 11:45:40 +00004291 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004292 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004293
4294 return NULL;
4295 }
Mike Stump11289f42009-09-09 15:08:12 +00004296
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004297 case Stmt::ArraySubscriptExprClass: {
4298 // Array subscripts are potential references to data on the stack. We
4299 // retrieve the DeclRefExpr* for the array variable if it indeed
4300 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004301 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004302 }
Mike Stump11289f42009-09-09 15:08:12 +00004303
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004304 case Stmt::ConditionalOperatorClass: {
4305 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004306 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004307 ConditionalOperator *C = cast<ConditionalOperator>(E);
4308
Anders Carlsson801c5c72007-11-30 19:04:31 +00004309 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004310 if (Expr *LHSExpr = C->getLHS()) {
4311 // In C++, we can have a throw-expression, which has 'void' type.
4312 if (!LHSExpr->getType()->isVoidType())
4313 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
4314 return LHS;
4315 }
4316
4317 // In C++, we can have a throw-expression, which has 'void' type.
4318 if (C->getRHS()->getType()->isVoidType())
4319 return 0;
Anders Carlsson801c5c72007-11-30 19:04:31 +00004320
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004321 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004322 }
Mike Stump11289f42009-09-09 15:08:12 +00004323
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004324 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00004325 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004326 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004327
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004328 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004329 if (M->isArrow())
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004330 return NULL;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004331
4332 // Check whether the member type is itself a reference, in which case
4333 // we're not going to refer to the member, but to what the member refers to.
4334 if (M->getMemberDecl()->getType()->isReferenceType())
4335 return NULL;
4336
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004337 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004338 }
Mike Stump11289f42009-09-09 15:08:12 +00004339
Douglas Gregorfe314812011-06-21 17:03:29 +00004340 case Stmt::MaterializeTemporaryExprClass:
4341 if (Expr *Result = EvalVal(
4342 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004343 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004344 return Result;
4345
4346 return E;
4347
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004348 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004349 // Check that we don't return or take the address of a reference to a
4350 // temporary. This is only useful in C++.
4351 if (!E->isTypeDependent() && E->isRValue())
4352 return E;
4353
4354 // Everything else: we simply don't reason about them.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004355 return NULL;
4356 }
Ted Kremenekb7861562010-08-04 20:01:07 +00004357} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004358}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004359
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004360void
4361Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
4362 SourceLocation ReturnLoc,
4363 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00004364 const AttrVec *Attrs,
4365 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004366 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
4367
4368 // Check if the return value is null but should not be.
4369 if (Attrs)
4370 for (specific_attr_iterator<ReturnsNonNullAttr>
4371 I = specific_attr_iterator<ReturnsNonNullAttr>(Attrs->begin()),
4372 E = specific_attr_iterator<ReturnsNonNullAttr>(Attrs->end());
4373 I != E; ++I) {
4374 if (CheckNonNullExpr(*this, RetValExp))
4375 Diag(ReturnLoc, diag::warn_null_ret)
4376 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
4377 break;
4378 }
Artyom Skrobov9f213442014-01-24 11:10:39 +00004379
4380 // C++11 [basic.stc.dynamic.allocation]p4:
4381 // If an allocation function declared with a non-throwing
4382 // exception-specification fails to allocate storage, it shall return
4383 // a null pointer. Any other allocation function that fails to allocate
4384 // storage shall indicate failure only by throwing an exception [...]
4385 if (FD) {
4386 OverloadedOperatorKind Op = FD->getOverloadedOperator();
4387 if (Op == OO_New || Op == OO_Array_New) {
4388 const FunctionProtoType *Proto
4389 = FD->getType()->castAs<FunctionProtoType>();
4390 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
4391 CheckNonNullExpr(*this, RetValExp))
4392 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
4393 << FD << getLangOpts().CPlusPlus11;
4394 }
4395 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004396}
4397
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004398//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4399
4400/// Check for comparisons of floating point operands using != and ==.
4401/// Issue a warning if these are no self-comparisons, as they are not likely
4402/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00004403void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00004404 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4405 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004406
4407 // Special case: check for x == x (which is OK).
4408 // Do not emit warnings for such cases.
4409 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4410 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4411 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00004412 return;
Mike Stump11289f42009-09-09 15:08:12 +00004413
4414
Ted Kremenekeda40e22007-11-29 00:59:04 +00004415 // Special case: check for comparisons against literals that can be exactly
4416 // represented by APFloat. In such cases, do not emit a warning. This
4417 // is a heuristic: often comparison against such literals are used to
4418 // detect if a value in a variable has not changed. This clearly can
4419 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00004420 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4421 if (FLL->isExact())
4422 return;
4423 } else
4424 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4425 if (FLR->isExact())
4426 return;
Mike Stump11289f42009-09-09 15:08:12 +00004427
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004428 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00004429 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004430 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004431 return;
Mike Stump11289f42009-09-09 15:08:12 +00004432
David Blaikie1f4ff152012-07-16 20:47:22 +00004433 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004434 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004435 return;
Mike Stump11289f42009-09-09 15:08:12 +00004436
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004437 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00004438 Diag(Loc, diag::warn_floatingpoint_eq)
4439 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004440}
John McCallca01b222010-01-04 23:21:16 +00004441
John McCall70aa5392010-01-06 05:24:50 +00004442//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4443//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00004444
John McCall70aa5392010-01-06 05:24:50 +00004445namespace {
John McCallca01b222010-01-04 23:21:16 +00004446
John McCall70aa5392010-01-06 05:24:50 +00004447/// Structure recording the 'active' range of an integer-valued
4448/// expression.
4449struct IntRange {
4450 /// The number of bits active in the int.
4451 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00004452
John McCall70aa5392010-01-06 05:24:50 +00004453 /// True if the int is known not to have negative values.
4454 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00004455
John McCall70aa5392010-01-06 05:24:50 +00004456 IntRange(unsigned Width, bool NonNegative)
4457 : Width(Width), NonNegative(NonNegative)
4458 {}
John McCallca01b222010-01-04 23:21:16 +00004459
John McCall817d4af2010-11-10 23:38:19 +00004460 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00004461 static IntRange forBoolType() {
4462 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00004463 }
4464
John McCall817d4af2010-11-10 23:38:19 +00004465 /// Returns the range of an opaque value of the given integral type.
4466 static IntRange forValueOfType(ASTContext &C, QualType T) {
4467 return forValueOfCanonicalType(C,
4468 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00004469 }
4470
John McCall817d4af2010-11-10 23:38:19 +00004471 /// Returns the range of an opaque value of a canonical integral type.
4472 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00004473 assert(T->isCanonicalUnqualified());
4474
4475 if (const VectorType *VT = dyn_cast<VectorType>(T))
4476 T = VT->getElementType().getTypePtr();
4477 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4478 T = CT->getElementType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00004479
David Majnemer6a426652013-06-07 22:07:20 +00004480 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00004481 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00004482 EnumDecl *Enum = ET->getDecl();
4483 if (!Enum->isCompleteDefinition())
4484 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00004485
David Majnemer6a426652013-06-07 22:07:20 +00004486 unsigned NumPositive = Enum->getNumPositiveBits();
4487 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00004488
David Majnemer6a426652013-06-07 22:07:20 +00004489 if (NumNegative == 0)
4490 return IntRange(NumPositive, true/*NonNegative*/);
4491 else
4492 return IntRange(std::max(NumPositive + 1, NumNegative),
4493 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00004494 }
John McCall70aa5392010-01-06 05:24:50 +00004495
4496 const BuiltinType *BT = cast<BuiltinType>(T);
4497 assert(BT->isInteger());
4498
4499 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4500 }
4501
John McCall817d4af2010-11-10 23:38:19 +00004502 /// Returns the "target" range of a canonical integral type, i.e.
4503 /// the range of values expressible in the type.
4504 ///
4505 /// This matches forValueOfCanonicalType except that enums have the
4506 /// full range of their type, not the range of their enumerators.
4507 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4508 assert(T->isCanonicalUnqualified());
4509
4510 if (const VectorType *VT = dyn_cast<VectorType>(T))
4511 T = VT->getElementType().getTypePtr();
4512 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4513 T = CT->getElementType().getTypePtr();
4514 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00004515 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00004516
4517 const BuiltinType *BT = cast<BuiltinType>(T);
4518 assert(BT->isInteger());
4519
4520 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4521 }
4522
4523 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00004524 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00004525 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00004526 L.NonNegative && R.NonNegative);
4527 }
4528
John McCall817d4af2010-11-10 23:38:19 +00004529 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00004530 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00004531 return IntRange(std::min(L.Width, R.Width),
4532 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00004533 }
4534};
4535
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004536static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4537 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004538 if (value.isSigned() && value.isNegative())
4539 return IntRange(value.getMinSignedBits(), false);
4540
4541 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00004542 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004543
4544 // isNonNegative() just checks the sign bit without considering
4545 // signedness.
4546 return IntRange(value.getActiveBits(), true);
4547}
4548
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004549static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4550 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004551 if (result.isInt())
4552 return GetValueRange(C, result.getInt(), MaxWidth);
4553
4554 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00004555 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4556 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4557 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4558 R = IntRange::join(R, El);
4559 }
John McCall70aa5392010-01-06 05:24:50 +00004560 return R;
4561 }
4562
4563 if (result.isComplexInt()) {
4564 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4565 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4566 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00004567 }
4568
4569 // This can happen with lossless casts to intptr_t of "based" lvalues.
4570 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00004571 // FIXME: The only reason we need to pass the type in here is to get
4572 // the sign right on this one case. It would be nice if APValue
4573 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004574 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00004575 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00004576}
John McCall70aa5392010-01-06 05:24:50 +00004577
Eli Friedmane6d33952013-07-08 20:20:06 +00004578static QualType GetExprType(Expr *E) {
4579 QualType Ty = E->getType();
4580 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4581 Ty = AtomicRHS->getValueType();
4582 return Ty;
4583}
4584
John McCall70aa5392010-01-06 05:24:50 +00004585/// Pseudo-evaluate the given integer expression, estimating the
4586/// range of values it might take.
4587///
4588/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004589static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004590 E = E->IgnoreParens();
4591
4592 // Try a full evaluation first.
4593 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00004594 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00004595 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004596
4597 // I think we only want to look through implicit casts here; if the
4598 // user has an explicit widening cast, we should treat the value as
4599 // being of the new, wider type.
4600 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00004601 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00004602 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4603
Eli Friedmane6d33952013-07-08 20:20:06 +00004604 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00004605
John McCalle3027922010-08-25 11:45:40 +00004606 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00004607
John McCall70aa5392010-01-06 05:24:50 +00004608 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00004609 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00004610 return OutputTypeRange;
4611
4612 IntRange SubRange
4613 = GetExprRange(C, CE->getSubExpr(),
4614 std::min(MaxWidth, OutputTypeRange.Width));
4615
4616 // Bail out if the subexpr's range is as wide as the cast type.
4617 if (SubRange.Width >= OutputTypeRange.Width)
4618 return OutputTypeRange;
4619
4620 // Otherwise, we take the smaller width, and we're non-negative if
4621 // either the output type or the subexpr is.
4622 return IntRange(SubRange.Width,
4623 SubRange.NonNegative || OutputTypeRange.NonNegative);
4624 }
4625
4626 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4627 // If we can fold the condition, just take that operand.
4628 bool CondResult;
4629 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4630 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4631 : CO->getFalseExpr(),
4632 MaxWidth);
4633
4634 // Otherwise, conservatively merge.
4635 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4636 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4637 return IntRange::join(L, R);
4638 }
4639
4640 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4641 switch (BO->getOpcode()) {
4642
4643 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00004644 case BO_LAnd:
4645 case BO_LOr:
4646 case BO_LT:
4647 case BO_GT:
4648 case BO_LE:
4649 case BO_GE:
4650 case BO_EQ:
4651 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00004652 return IntRange::forBoolType();
4653
John McCallc3688382011-07-13 06:35:24 +00004654 // The type of the assignments is the type of the LHS, so the RHS
4655 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00004656 case BO_MulAssign:
4657 case BO_DivAssign:
4658 case BO_RemAssign:
4659 case BO_AddAssign:
4660 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00004661 case BO_XorAssign:
4662 case BO_OrAssign:
4663 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00004664 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00004665
John McCallc3688382011-07-13 06:35:24 +00004666 // Simple assignments just pass through the RHS, which will have
4667 // been coerced to the LHS type.
4668 case BO_Assign:
4669 // TODO: bitfields?
4670 return GetExprRange(C, BO->getRHS(), MaxWidth);
4671
John McCall70aa5392010-01-06 05:24:50 +00004672 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00004673 case BO_PtrMemD:
4674 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00004675 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00004676
John McCall2ce81ad2010-01-06 22:07:33 +00004677 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00004678 case BO_And:
4679 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00004680 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4681 GetExprRange(C, BO->getRHS(), MaxWidth));
4682
John McCall70aa5392010-01-06 05:24:50 +00004683 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00004684 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00004685 // ...except that we want to treat '1 << (blah)' as logically
4686 // positive. It's an important idiom.
4687 if (IntegerLiteral *I
4688 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4689 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00004690 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00004691 return IntRange(R.Width, /*NonNegative*/ true);
4692 }
4693 }
4694 // fallthrough
4695
John McCalle3027922010-08-25 11:45:40 +00004696 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00004697 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00004698
John McCall2ce81ad2010-01-06 22:07:33 +00004699 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00004700 case BO_Shr:
4701 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00004702 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4703
4704 // If the shift amount is a positive constant, drop the width by
4705 // that much.
4706 llvm::APSInt shift;
4707 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4708 shift.isNonNegative()) {
4709 unsigned zext = shift.getZExtValue();
4710 if (zext >= L.Width)
4711 L.Width = (L.NonNegative ? 0 : 1);
4712 else
4713 L.Width -= zext;
4714 }
4715
4716 return L;
4717 }
4718
4719 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00004720 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00004721 return GetExprRange(C, BO->getRHS(), MaxWidth);
4722
John McCall2ce81ad2010-01-06 22:07:33 +00004723 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00004724 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00004725 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00004726 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00004727 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004728
John McCall51431812011-07-14 22:39:48 +00004729 // The width of a division result is mostly determined by the size
4730 // of the LHS.
4731 case BO_Div: {
4732 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00004733 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00004734 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4735
4736 // If the divisor is constant, use that.
4737 llvm::APSInt divisor;
4738 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4739 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4740 if (log2 >= L.Width)
4741 L.Width = (L.NonNegative ? 0 : 1);
4742 else
4743 L.Width = std::min(L.Width - log2, MaxWidth);
4744 return L;
4745 }
4746
4747 // Otherwise, just use the LHS's width.
4748 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4749 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4750 }
4751
4752 // The result of a remainder can't be larger than the result of
4753 // either side.
4754 case BO_Rem: {
4755 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00004756 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00004757 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4758 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4759
4760 IntRange meet = IntRange::meet(L, R);
4761 meet.Width = std::min(meet.Width, MaxWidth);
4762 return meet;
4763 }
4764
4765 // The default behavior is okay for these.
4766 case BO_Mul:
4767 case BO_Add:
4768 case BO_Xor:
4769 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00004770 break;
4771 }
4772
John McCall51431812011-07-14 22:39:48 +00004773 // The default case is to treat the operation as if it were closed
4774 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00004775 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4776 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4777 return IntRange::join(L, R);
4778 }
4779
4780 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4781 switch (UO->getOpcode()) {
4782 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00004783 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00004784 return IntRange::forBoolType();
4785
4786 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00004787 case UO_Deref:
4788 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00004789 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00004790
4791 default:
4792 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4793 }
4794 }
4795
Ted Kremeneka553fbf2013-10-14 18:55:27 +00004796 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
4797 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
4798
John McCalld25db7e2013-05-06 21:39:12 +00004799 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00004800 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00004801 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00004802
Eli Friedmane6d33952013-07-08 20:20:06 +00004803 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00004804}
John McCall263a48b2010-01-04 23:31:57 +00004805
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004806static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00004807 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00004808}
4809
John McCall263a48b2010-01-04 23:31:57 +00004810/// Checks whether the given value, which currently has the given
4811/// source semantics, has the same value when coerced through the
4812/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004813static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4814 const llvm::fltSemantics &Src,
4815 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00004816 llvm::APFloat truncated = value;
4817
4818 bool ignored;
4819 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4820 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4821
4822 return truncated.bitwiseIsEqual(value);
4823}
4824
4825/// Checks whether the given value, which currently has the given
4826/// source semantics, has the same value when coerced through the
4827/// target semantics.
4828///
4829/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004830static bool IsSameFloatAfterCast(const APValue &value,
4831 const llvm::fltSemantics &Src,
4832 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00004833 if (value.isFloat())
4834 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4835
4836 if (value.isVector()) {
4837 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4838 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4839 return false;
4840 return true;
4841 }
4842
4843 assert(value.isComplexFloat());
4844 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4845 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4846}
4847
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004848static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00004849
Ted Kremenek6274be42010-09-23 21:43:44 +00004850static bool IsZero(Sema &S, Expr *E) {
4851 // Suppress cases where we are comparing against an enum constant.
4852 if (const DeclRefExpr *DR =
4853 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4854 if (isa<EnumConstantDecl>(DR->getDecl()))
4855 return false;
4856
4857 // Suppress cases where the '0' value is expanded from a macro.
4858 if (E->getLocStart().isMacroID())
4859 return false;
4860
John McCallcc7e5bf2010-05-06 08:58:33 +00004861 llvm::APSInt Value;
4862 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4863}
4864
John McCall2551c1b2010-10-06 00:25:24 +00004865static bool HasEnumType(Expr *E) {
4866 // Strip off implicit integral promotions.
4867 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00004868 if (ICE->getCastKind() != CK_IntegralCast &&
4869 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00004870 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00004871 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00004872 }
4873
4874 return E->getType()->isEnumeralType();
4875}
4876
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004877static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00004878 // Disable warning in template instantiations.
4879 if (!S.ActiveTemplateInstantiations.empty())
4880 return;
4881
John McCalle3027922010-08-25 11:45:40 +00004882 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00004883 if (E->isValueDependent())
4884 return;
4885
John McCalle3027922010-08-25 11:45:40 +00004886 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004887 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00004888 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00004889 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004890 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004891 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00004892 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00004893 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004894 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004895 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00004896 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00004897 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004898 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004899 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00004900 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00004901 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4902 }
4903}
4904
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004905static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004906 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004907 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004908 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00004909 // Disable warning in template instantiations.
4910 if (!S.ActiveTemplateInstantiations.empty())
4911 return;
4912
Richard Trieu560910c2012-11-14 22:50:24 +00004913 // 0 values are handled later by CheckTrivialUnsignedComparison().
4914 if (Value == 0)
4915 return;
4916
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004917 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004918 QualType OtherT = Other->getType();
4919 QualType ConstantT = Constant->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00004920 QualType CommonT = E->getLHS()->getType();
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004921 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004922 return;
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004923 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004924 && "comparison with non-integer type");
Richard Trieu560910c2012-11-14 22:50:24 +00004925
4926 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu560910c2012-11-14 22:50:24 +00004927 bool CommonSigned = CommonT->isSignedIntegerType();
4928
4929 bool EqualityOnly = false;
4930
4931 // TODO: Investigate using GetExprRange() to get tighter bounds on
4932 // on the bit ranges.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004933 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu560910c2012-11-14 22:50:24 +00004934 unsigned OtherWidth = OtherRange.Width;
4935
4936 if (CommonSigned) {
4937 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedman5ac98752012-11-30 23:09:29 +00004938 if (!OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00004939 // Check that the constant is representable in type OtherT.
4940 if (ConstantSigned) {
4941 if (OtherWidth >= Value.getMinSignedBits())
4942 return;
4943 } else { // !ConstantSigned
4944 if (OtherWidth >= Value.getActiveBits() + 1)
4945 return;
4946 }
4947 } else { // !OtherSigned
4948 // Check that the constant is representable in type OtherT.
4949 // Negative values are out of range.
4950 if (ConstantSigned) {
4951 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4952 return;
4953 } else { // !ConstantSigned
4954 if (OtherWidth >= Value.getActiveBits())
4955 return;
4956 }
4957 }
4958 } else { // !CommonSigned
Eli Friedman5ac98752012-11-30 23:09:29 +00004959 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00004960 if (OtherWidth >= Value.getActiveBits())
4961 return;
Eli Friedman5ac98752012-11-30 23:09:29 +00004962 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu560910c2012-11-14 22:50:24 +00004963 // Check to see if the constant is representable in OtherT.
4964 if (OtherWidth > Value.getActiveBits())
4965 return;
4966 // Check to see if the constant is equivalent to a negative value
4967 // cast to CommonT.
4968 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu03c3a2f2012-11-15 03:43:50 +00004969 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu560910c2012-11-14 22:50:24 +00004970 return;
4971 // The constant value rests between values that OtherT can represent after
4972 // conversion. Relational comparison still works, but equality
4973 // comparisons will be tautological.
4974 EqualityOnly = true;
4975 } else { // OtherSigned && ConstantSigned
4976 assert(0 && "Two signed types converted to unsigned types.");
4977 }
4978 }
4979
4980 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4981
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004982 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00004983 if (op == BO_EQ || op == BO_NE) {
4984 IsTrue = op == BO_NE;
4985 } else if (EqualityOnly) {
4986 return;
4987 } else if (RhsConstant) {
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004988 if (op == BO_GT || op == BO_GE)
Richard Trieu560910c2012-11-14 22:50:24 +00004989 IsTrue = !PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004990 else // op == BO_LT || op == BO_LE
Richard Trieu560910c2012-11-14 22:50:24 +00004991 IsTrue = PositiveConstant;
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004992 } else {
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004993 if (op == BO_LT || op == BO_LE)
Richard Trieu560910c2012-11-14 22:50:24 +00004994 IsTrue = !PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004995 else // op == BO_GT || op == BO_GE
Richard Trieu560910c2012-11-14 22:50:24 +00004996 IsTrue = PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004997 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00004998
4999 // If this is a comparison to an enum constant, include that
5000 // constant in the diagnostic.
5001 const EnumConstantDecl *ED = 0;
5002 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5003 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5004
5005 SmallString<64> PrettySourceValue;
5006 llvm::raw_svector_ostream OS(PrettySourceValue);
5007 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00005008 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005009 else
5010 OS << Value;
5011
Richard Trieuc38786b2014-01-10 04:38:09 +00005012 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5013 S.PDiag(diag::warn_out_of_range_compare)
5014 << OS.str() << OtherT << IsTrue
5015 << E->getLHS()->getSourceRange()
5016 << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005017}
5018
John McCallcc7e5bf2010-05-06 08:58:33 +00005019/// Analyze the operands of the given comparison. Implements the
5020/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005021static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00005022 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5023 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00005024}
John McCall263a48b2010-01-04 23:31:57 +00005025
John McCallca01b222010-01-04 23:21:16 +00005026/// \brief Implements -Wsign-compare.
5027///
Richard Trieu82402a02011-09-15 21:56:47 +00005028/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005029static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005030 // The type the comparison is being performed in.
5031 QualType T = E->getLHS()->getType();
5032 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5033 && "comparison with mismatched types");
Fariborz Jahanian282071e2012-09-18 17:46:26 +00005034 if (E->isValueDependent())
5035 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005036
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005037 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5038 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005039
5040 bool IsComparisonConstant = false;
5041
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005042 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005043 // of 'true' or 'false'.
5044 if (T->isIntegralType(S.Context)) {
5045 llvm::APSInt RHSValue;
5046 bool IsRHSIntegralLiteral =
5047 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5048 llvm::APSInt LHSValue;
5049 bool IsLHSIntegralLiteral =
5050 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5051 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5052 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5053 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5054 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5055 else
5056 IsComparisonConstant =
5057 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005058 } else if (!T->hasUnsignedIntegerRepresentation())
5059 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005060
John McCallcc7e5bf2010-05-06 08:58:33 +00005061 // We don't do anything special if this isn't an unsigned integral
5062 // comparison: we're only interested in integral comparisons, and
5063 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00005064 //
5065 // We also don't care about value-dependent expressions or expressions
5066 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005067 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00005068 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005069
John McCallcc7e5bf2010-05-06 08:58:33 +00005070 // Check to see if one of the (unmodified) operands is of different
5071 // signedness.
5072 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00005073 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5074 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00005075 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00005076 signedOperand = LHS;
5077 unsignedOperand = RHS;
5078 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5079 signedOperand = RHS;
5080 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00005081 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00005082 CheckTrivialUnsignedComparison(S, E);
5083 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005084 }
5085
John McCallcc7e5bf2010-05-06 08:58:33 +00005086 // Otherwise, calculate the effective range of the signed operand.
5087 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00005088
John McCallcc7e5bf2010-05-06 08:58:33 +00005089 // Go ahead and analyze implicit conversions in the operands. Note
5090 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00005091 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5092 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00005093
John McCallcc7e5bf2010-05-06 08:58:33 +00005094 // If the signed range is non-negative, -Wsign-compare won't fire,
5095 // but we should still check for comparisons which are always true
5096 // or false.
5097 if (signedRange.NonNegative)
5098 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005099
5100 // For (in)equality comparisons, if the unsigned operand is a
5101 // constant which cannot collide with a overflowed signed operand,
5102 // then reinterpreting the signed operand as unsigned will not
5103 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00005104 if (E->isEqualityOp()) {
5105 unsigned comparisonWidth = S.Context.getIntWidth(T);
5106 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00005107
John McCallcc7e5bf2010-05-06 08:58:33 +00005108 // We should never be unable to prove that the unsigned operand is
5109 // non-negative.
5110 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5111
5112 if (unsignedRange.Width < comparisonWidth)
5113 return;
5114 }
5115
Douglas Gregorbfb4a212012-05-01 01:53:49 +00005116 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5117 S.PDiag(diag::warn_mixed_sign_comparison)
5118 << LHS->getType() << RHS->getType()
5119 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00005120}
5121
John McCall1f425642010-11-11 03:21:53 +00005122/// Analyzes an attempt to assign the given value to a bitfield.
5123///
5124/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005125static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5126 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00005127 assert(Bitfield->isBitField());
5128 if (Bitfield->isInvalidDecl())
5129 return false;
5130
John McCalldeebbcf2010-11-11 05:33:51 +00005131 // White-list bool bitfields.
5132 if (Bitfield->getType()->isBooleanType())
5133 return false;
5134
Douglas Gregor789adec2011-02-04 13:09:01 +00005135 // Ignore value- or type-dependent expressions.
5136 if (Bitfield->getBitWidth()->isValueDependent() ||
5137 Bitfield->getBitWidth()->isTypeDependent() ||
5138 Init->isValueDependent() ||
5139 Init->isTypeDependent())
5140 return false;
5141
John McCall1f425642010-11-11 03:21:53 +00005142 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5143
Richard Smith5fab0c92011-12-28 19:48:30 +00005144 llvm::APSInt Value;
5145 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00005146 return false;
5147
John McCall1f425642010-11-11 03:21:53 +00005148 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00005149 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00005150
5151 if (OriginalWidth <= FieldWidth)
5152 return false;
5153
Eli Friedmanc267a322012-01-26 23:11:39 +00005154 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005155 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00005156 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00005157
Eli Friedmanc267a322012-01-26 23:11:39 +00005158 // Check whether the stored value is equal to the original value.
5159 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00005160 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00005161 return false;
5162
Eli Friedmanc267a322012-01-26 23:11:39 +00005163 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00005164 // therefore don't strictly fit into a signed bitfield of width 1.
5165 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00005166 return false;
5167
John McCall1f425642010-11-11 03:21:53 +00005168 std::string PrettyValue = Value.toString(10);
5169 std::string PrettyTrunc = TruncatedValue.toString(10);
5170
5171 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5172 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5173 << Init->getSourceRange();
5174
5175 return true;
5176}
5177
John McCalld2a53122010-11-09 23:24:47 +00005178/// Analyze the given simple or compound assignment for warning-worthy
5179/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005180static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00005181 // Just recurse on the LHS.
5182 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5183
5184 // We want to recurse on the RHS as normal unless we're assigning to
5185 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00005186 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005187 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00005188 E->getOperatorLoc())) {
5189 // Recurse, ignoring any implicit conversions on the RHS.
5190 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5191 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00005192 }
5193 }
5194
5195 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5196}
5197
John McCall263a48b2010-01-04 23:31:57 +00005198/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005199static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005200 SourceLocation CContext, unsigned diag,
5201 bool pruneControlFlow = false) {
5202 if (pruneControlFlow) {
5203 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5204 S.PDiag(diag)
5205 << SourceType << T << E->getSourceRange()
5206 << SourceRange(CContext));
5207 return;
5208 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00005209 S.Diag(E->getExprLoc(), diag)
5210 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5211}
5212
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005213/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005214static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005215 SourceLocation CContext, unsigned diag,
5216 bool pruneControlFlow = false) {
5217 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005218}
5219
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005220/// Diagnose an implicit cast from a literal expression. Does not warn when the
5221/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00005222void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5223 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005224 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00005225 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005226 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00005227 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5228 T->hasUnsignedIntegerRepresentation());
5229 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00005230 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005231 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00005232 return;
5233
Eli Friedman07185912013-08-29 23:44:43 +00005234 // FIXME: Force the precision of the source value down so we don't print
5235 // digits which are usually useless (we don't really care here if we
5236 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5237 // would automatically print the shortest representation, but it's a bit
5238 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00005239 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00005240 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5241 precision = (precision * 59 + 195) / 196;
5242 Value.toString(PrettySourceValue, precision);
5243
David Blaikie9b88cc02012-05-15 17:18:27 +00005244 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00005245 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5246 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5247 else
David Blaikie9b88cc02012-05-15 17:18:27 +00005248 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00005249
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005250 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00005251 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5252 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00005253}
5254
John McCall18a2c2c2010-11-09 22:22:12 +00005255std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5256 if (!Range.Width) return "0";
5257
5258 llvm::APSInt ValueInRange = Value;
5259 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00005260 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00005261 return ValueInRange.toString(10);
5262}
5263
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005264static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5265 if (!isa<ImplicitCastExpr>(Ex))
5266 return false;
5267
5268 Expr *InnerE = Ex->IgnoreParenImpCasts();
5269 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5270 const Type *Source =
5271 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5272 if (Target->isDependentType())
5273 return false;
5274
5275 const BuiltinType *FloatCandidateBT =
5276 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5277 const Type *BoolCandidateType = ToBool ? Target : Source;
5278
5279 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5280 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5281}
5282
5283void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5284 SourceLocation CC) {
5285 unsigned NumArgs = TheCall->getNumArgs();
5286 for (unsigned i = 0; i < NumArgs; ++i) {
5287 Expr *CurrA = TheCall->getArg(i);
5288 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5289 continue;
5290
5291 bool IsSwapped = ((i > 0) &&
5292 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5293 IsSwapped |= ((i < (NumArgs - 1)) &&
5294 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5295 if (IsSwapped) {
5296 // Warn on this floating-point to bool conversion.
5297 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5298 CurrA->getType(), CC,
5299 diag::warn_impcast_floating_point_to_bool);
5300 }
5301 }
5302}
5303
John McCallcc7e5bf2010-05-06 08:58:33 +00005304void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005305 SourceLocation CC, bool *ICContext = 0) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005306 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00005307
John McCallcc7e5bf2010-05-06 08:58:33 +00005308 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5309 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5310 if (Source == Target) return;
5311 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00005312
Chandler Carruthc22845a2011-07-26 05:40:03 +00005313 // If the conversion context location is invalid don't complain. We also
5314 // don't want to emit a warning if the issue occurs from the expansion of
5315 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5316 // delay this check as long as possible. Once we detect we are in that
5317 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005318 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00005319 return;
5320
Richard Trieu021baa32011-09-23 20:10:00 +00005321 // Diagnose implicit casts to bool.
5322 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5323 if (isa<StringLiteral>(E))
5324 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00005325 // and expressions, for instance, assert(0 && "error here"), are
5326 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00005327 return DiagnoseImpCast(S, E, T, CC,
5328 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00005329 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
5330 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
5331 // This covers the literal expressions that evaluate to Objective-C
5332 // objects.
5333 return DiagnoseImpCast(S, E, T, CC,
5334 diag::warn_impcast_objective_c_literal_to_bool);
5335 }
Lang Hamesdf5c1212011-12-05 20:49:50 +00005336 if (Source->isFunctionType()) {
5337 // Warn on function to bool. Checks free functions and static member
5338 // functions. Weakly imported functions are excluded from the check,
5339 // since it's common to test their value to check whether the linker
5340 // found a definition for them.
5341 ValueDecl *D = 0;
5342 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
5343 D = R->getDecl();
5344 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
5345 D = M->getMemberDecl();
5346 }
5347
5348 if (D && !D->isWeak()) {
Richard Trieu5f623222011-12-06 04:48:01 +00005349 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
5350 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
5351 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie10eb4b62011-12-09 21:42:37 +00005352 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
5353 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
5354 QualType ReturnType;
5355 UnresolvedSet<4> NonTemplateOverloads;
David Blaikiee5323aa2013-06-21 23:54:45 +00005356 S.tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
David Blaikie10eb4b62011-12-09 21:42:37 +00005357 if (!ReturnType.isNull()
5358 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
5359 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
5360 << FixItHint::CreateInsertion(
5361 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu5f623222011-12-06 04:48:01 +00005362 return;
5363 }
Lang Hamesdf5c1212011-12-05 20:49:50 +00005364 }
5365 }
Richard Trieu021baa32011-09-23 20:10:00 +00005366 }
John McCall263a48b2010-01-04 23:31:57 +00005367
5368 // Strip vector types.
5369 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005370 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005371 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005372 return;
John McCallacf0ee52010-10-08 02:01:28 +00005373 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005374 }
Chris Lattneree7286f2011-06-14 04:51:15 +00005375
5376 // If the vector cast is cast between two vectors of the same size, it is
5377 // a bitcast, not a conversion.
5378 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5379 return;
John McCall263a48b2010-01-04 23:31:57 +00005380
5381 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5382 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5383 }
5384
5385 // Strip complex types.
5386 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005387 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005388 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005389 return;
5390
John McCallacf0ee52010-10-08 02:01:28 +00005391 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005392 }
John McCall263a48b2010-01-04 23:31:57 +00005393
5394 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5395 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5396 }
5397
5398 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5399 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5400
5401 // If the source is floating point...
5402 if (SourceBT && SourceBT->isFloatingPoint()) {
5403 // ...and the target is floating point...
5404 if (TargetBT && TargetBT->isFloatingPoint()) {
5405 // ...then warn if we're dropping FP rank.
5406
5407 // Builtin FP kinds are ordered by increasing FP rank.
5408 if (SourceBT->getKind() > TargetBT->getKind()) {
5409 // Don't warn about float constants that are precisely
5410 // representable in the target type.
5411 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005412 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00005413 // Value might be a float, a float vector, or a float complex.
5414 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00005415 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5416 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00005417 return;
5418 }
5419
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005420 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005421 return;
5422
John McCallacf0ee52010-10-08 02:01:28 +00005423 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00005424 }
5425 return;
5426 }
5427
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005428 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00005429 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005430 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005431 return;
5432
Chandler Carruth22c7a792011-02-17 11:05:49 +00005433 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00005434 // We also want to warn on, e.g., "int i = -1.234"
5435 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5436 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5437 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5438
Chandler Carruth016ef402011-04-10 08:36:24 +00005439 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5440 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00005441 } else {
5442 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5443 }
5444 }
John McCall263a48b2010-01-04 23:31:57 +00005445
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005446 // If the target is bool, warn if expr is a function or method call.
5447 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5448 isa<CallExpr>(E)) {
5449 // Check last argument of function call to see if it is an
5450 // implicit cast from a type matching the type the result
5451 // is being cast to.
5452 CallExpr *CEx = cast<CallExpr>(E);
5453 unsigned NumArgs = CEx->getNumArgs();
5454 if (NumArgs > 0) {
5455 Expr *LastA = CEx->getArg(NumArgs - 1);
5456 Expr *InnerE = LastA->IgnoreParenImpCasts();
5457 const Type *InnerType =
5458 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5459 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5460 // Warn on this floating-point to bool conversion
5461 DiagnoseImpCast(S, E, T, CC,
5462 diag::warn_impcast_floating_point_to_bool);
5463 }
5464 }
5465 }
John McCall263a48b2010-01-04 23:31:57 +00005466 return;
5467 }
5468
Richard Trieubeaf3452011-05-29 19:59:02 +00005469 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikie9366d2b2012-06-19 21:19:06 +00005470 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiea1edff02012-11-08 00:41:20 +00005471 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikiebcd4b552013-02-16 00:56:22 +00005472 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieae12b182012-03-16 20:30:12 +00005473 SourceLocation Loc = E->getSourceRange().getBegin();
5474 if (Loc.isMacroID())
5475 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie18e9ac72012-05-15 21:57:38 +00005476 if (!Loc.isMacroID() || CC.isMacroID())
5477 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5478 << T << clang::SourceRange(CC)
Richard Smithf7ec86a2013-09-20 00:27:40 +00005479 << FixItHint::CreateReplacement(Loc,
5480 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieubeaf3452011-05-29 19:59:02 +00005481 }
5482
David Blaikie9366d2b2012-06-19 21:19:06 +00005483 if (!Source->isIntegerType() || !Target->isIntegerType())
5484 return;
5485
David Blaikie7555b6a2012-05-15 16:56:36 +00005486 // TODO: remove this early return once the false positives for constant->bool
5487 // in templates, macros, etc, are reduced or removed.
5488 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5489 return;
5490
John McCallcc7e5bf2010-05-06 08:58:33 +00005491 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00005492 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00005493
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005494 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00005495 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005496 // TODO: this should happen for bitfield stores, too.
5497 llvm::APSInt Value(32);
5498 if (E->isIntegerConstantExpr(Value, S.Context)) {
5499 if (S.SourceMgr.isInSystemMacro(CC))
5500 return;
5501
John McCall18a2c2c2010-11-09 22:22:12 +00005502 std::string PrettySourceValue = Value.toString(10);
5503 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005504
Ted Kremenek33ba9952011-10-22 02:37:33 +00005505 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5506 S.PDiag(diag::warn_impcast_integer_precision_constant)
5507 << PrettySourceValue << PrettyTargetValue
5508 << E->getType() << T << E->getSourceRange()
5509 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00005510 return;
5511 }
5512
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005513 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5514 if (S.SourceMgr.isInSystemMacro(CC))
5515 return;
5516
David Blaikie9455da02012-04-12 22:40:54 +00005517 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00005518 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5519 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00005520 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00005521 }
5522
5523 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5524 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5525 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005526
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005527 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005528 return;
5529
John McCallcc7e5bf2010-05-06 08:58:33 +00005530 unsigned DiagID = diag::warn_impcast_integer_sign;
5531
5532 // Traditionally, gcc has warned about this under -Wsign-compare.
5533 // We also want to warn about it in -Wconversion.
5534 // So if -Wconversion is off, use a completely identical diagnostic
5535 // in the sign-compare group.
5536 // The conditional-checking code will
5537 if (ICContext) {
5538 DiagID = diag::warn_impcast_integer_sign_conditional;
5539 *ICContext = true;
5540 }
5541
John McCallacf0ee52010-10-08 02:01:28 +00005542 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00005543 }
5544
Douglas Gregora78f1932011-02-22 02:45:07 +00005545 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00005546 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5547 // type, to give us better diagnostics.
5548 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005549 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00005550 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5551 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5552 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5553 SourceType = S.Context.getTypeDeclType(Enum);
5554 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5555 }
5556 }
5557
Douglas Gregora78f1932011-02-22 02:45:07 +00005558 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5559 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00005560 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5561 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005562 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005563 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005564 return;
5565
Douglas Gregor364f7db2011-03-12 00:14:31 +00005566 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00005567 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005568 }
Douglas Gregora78f1932011-02-22 02:45:07 +00005569
John McCall263a48b2010-01-04 23:31:57 +00005570 return;
5571}
5572
David Blaikie18e9ac72012-05-15 21:57:38 +00005573void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5574 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00005575
5576void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00005577 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005578 E = E->IgnoreParenImpCasts();
5579
5580 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00005581 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00005582
John McCallacf0ee52010-10-08 02:01:28 +00005583 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005584 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00005585 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00005586 return;
5587}
5588
David Blaikie18e9ac72012-05-15 21:57:38 +00005589void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5590 SourceLocation CC, QualType T) {
John McCallacf0ee52010-10-08 02:01:28 +00005591 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005592
5593 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00005594 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5595 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00005596
5597 // If -Wconversion would have warned about either of the candidates
5598 // for a signedness conversion to the context type...
5599 if (!Suspicious) return;
5600
5601 // ...but it's currently ignored...
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005602 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5603 CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00005604 return;
5605
John McCallcc7e5bf2010-05-06 08:58:33 +00005606 // ...then check whether it would have warned about either of the
5607 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00005608 if (E->getType() == T) return;
5609
5610 Suspicious = false;
5611 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5612 E->getType(), CC, &Suspicious);
5613 if (!Suspicious)
5614 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00005615 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00005616}
5617
5618/// AnalyzeImplicitConversions - Find and report any interesting
5619/// implicit conversions in the given expression. There are a couple
5620/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00005621void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005622 QualType T = OrigE->getType();
5623 Expr *E = OrigE->IgnoreParenImpCasts();
5624
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00005625 if (E->isTypeDependent() || E->isValueDependent())
5626 return;
5627
John McCallcc7e5bf2010-05-06 08:58:33 +00005628 // For conditional operators, we analyze the arguments as if they
5629 // were being fed directly into the output.
5630 if (isa<ConditionalOperator>(E)) {
5631 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00005632 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00005633 return;
5634 }
5635
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005636 // Check implicit argument conversions for function calls.
5637 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5638 CheckImplicitArgumentConversions(S, Call, CC);
5639
John McCallcc7e5bf2010-05-06 08:58:33 +00005640 // Go ahead and check any implicit conversions we might have skipped.
5641 // The non-canonical typecheck is just an optimization;
5642 // CheckImplicitConversion will filter out dead implicit conversions.
5643 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00005644 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005645
5646 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00005647
5648 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00005649 if (POE->getResultExpr())
5650 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00005651 }
5652
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00005653 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5654 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5655
John McCallcc7e5bf2010-05-06 08:58:33 +00005656 // Skip past explicit casts.
5657 if (isa<ExplicitCastExpr>(E)) {
5658 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00005659 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005660 }
5661
John McCalld2a53122010-11-09 23:24:47 +00005662 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5663 // Do a somewhat different check with comparison operators.
5664 if (BO->isComparisonOp())
5665 return AnalyzeComparison(S, BO);
5666
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005667 // And with simple assignments.
5668 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00005669 return AnalyzeAssignment(S, BO);
5670 }
John McCallcc7e5bf2010-05-06 08:58:33 +00005671
5672 // These break the otherwise-useful invariant below. Fortunately,
5673 // we don't really need to recurse into them, because any internal
5674 // expressions should have been analyzed already when they were
5675 // built into statements.
5676 if (isa<StmtExpr>(E)) return;
5677
5678 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00005679 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00005680
5681 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00005682 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00005683 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00005684 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00005685 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00005686 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00005687 if (!ChildExpr)
5688 continue;
5689
Richard Trieu955231d2014-01-25 01:10:35 +00005690 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00005691 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00005692 // Ignore checking string literals that are in logical and operators.
5693 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00005694 continue;
5695 AnalyzeImplicitConversions(S, ChildExpr, CC);
5696 }
John McCallcc7e5bf2010-05-06 08:58:33 +00005697}
5698
5699} // end anonymous namespace
5700
5701/// Diagnoses "dangerous" implicit conversions within the given
5702/// expression (which is a full expression). Implements -Wconversion
5703/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00005704///
5705/// \param CC the "context" location of the implicit conversion, i.e.
5706/// the most location of the syntactic entity requiring the implicit
5707/// conversion
5708void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005709 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00005710 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00005711 return;
5712
5713 // Don't diagnose for value- or type-dependent expressions.
5714 if (E->isTypeDependent() || E->isValueDependent())
5715 return;
5716
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00005717 // Check for array bounds violations in cases where the check isn't triggered
5718 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5719 // ArraySubscriptExpr is on the RHS of a variable initialization.
5720 CheckArrayAccess(E);
5721
John McCallacf0ee52010-10-08 02:01:28 +00005722 // This is not the right CC for (e.g.) a variable initialization.
5723 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005724}
5725
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00005726/// Diagnose when expression is an integer constant expression and its evaluation
5727/// results in integer overflow
5728void Sema::CheckForIntOverflow (Expr *E) {
Richard Smithe9ff7702013-11-05 22:23:30 +00005729 if (isa<BinaryOperator>(E->IgnoreParens()))
5730 E->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00005731}
5732
Richard Smithc406cb72013-01-17 01:17:56 +00005733namespace {
5734/// \brief Visitor for expressions which looks for unsequenced operations on the
5735/// same object.
5736class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00005737 typedef EvaluatedExprVisitor<SequenceChecker> Base;
5738
Richard Smithc406cb72013-01-17 01:17:56 +00005739 /// \brief A tree of sequenced regions within an expression. Two regions are
5740 /// unsequenced if one is an ancestor or a descendent of the other. When we
5741 /// finish processing an expression with sequencing, such as a comma
5742 /// expression, we fold its tree nodes into its parent, since they are
5743 /// unsequenced with respect to nodes we will visit later.
5744 class SequenceTree {
5745 struct Value {
5746 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5747 unsigned Parent : 31;
5748 bool Merged : 1;
5749 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005750 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00005751
5752 public:
5753 /// \brief A region within an expression which may be sequenced with respect
5754 /// to some other region.
5755 class Seq {
5756 explicit Seq(unsigned N) : Index(N) {}
5757 unsigned Index;
5758 friend class SequenceTree;
5759 public:
5760 Seq() : Index(0) {}
5761 };
5762
5763 SequenceTree() { Values.push_back(Value(0)); }
5764 Seq root() const { return Seq(0); }
5765
5766 /// \brief Create a new sequence of operations, which is an unsequenced
5767 /// subset of \p Parent. This sequence of operations is sequenced with
5768 /// respect to other children of \p Parent.
5769 Seq allocate(Seq Parent) {
5770 Values.push_back(Value(Parent.Index));
5771 return Seq(Values.size() - 1);
5772 }
5773
5774 /// \brief Merge a sequence of operations into its parent.
5775 void merge(Seq S) {
5776 Values[S.Index].Merged = true;
5777 }
5778
5779 /// \brief Determine whether two operations are unsequenced. This operation
5780 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5781 /// should have been merged into its parent as appropriate.
5782 bool isUnsequenced(Seq Cur, Seq Old) {
5783 unsigned C = representative(Cur.Index);
5784 unsigned Target = representative(Old.Index);
5785 while (C >= Target) {
5786 if (C == Target)
5787 return true;
5788 C = Values[C].Parent;
5789 }
5790 return false;
5791 }
5792
5793 private:
5794 /// \brief Pick a representative for a sequence.
5795 unsigned representative(unsigned K) {
5796 if (Values[K].Merged)
5797 // Perform path compression as we go.
5798 return Values[K].Parent = representative(Values[K].Parent);
5799 return K;
5800 }
5801 };
5802
5803 /// An object for which we can track unsequenced uses.
5804 typedef NamedDecl *Object;
5805
5806 /// Different flavors of object usage which we track. We only track the
5807 /// least-sequenced usage of each kind.
5808 enum UsageKind {
5809 /// A read of an object. Multiple unsequenced reads are OK.
5810 UK_Use,
5811 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00005812 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00005813 UK_ModAsValue,
5814 /// A modification of an object which is not sequenced before the value
5815 /// computation of the expression, such as n++.
5816 UK_ModAsSideEffect,
5817
5818 UK_Count = UK_ModAsSideEffect + 1
5819 };
5820
5821 struct Usage {
5822 Usage() : Use(0), Seq() {}
5823 Expr *Use;
5824 SequenceTree::Seq Seq;
5825 };
5826
5827 struct UsageInfo {
5828 UsageInfo() : Diagnosed(false) {}
5829 Usage Uses[UK_Count];
5830 /// Have we issued a diagnostic for this variable already?
5831 bool Diagnosed;
5832 };
5833 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5834
5835 Sema &SemaRef;
5836 /// Sequenced regions within the expression.
5837 SequenceTree Tree;
5838 /// Declaration modifications and references which we have seen.
5839 UsageInfoMap UsageMap;
5840 /// The region we are currently within.
5841 SequenceTree::Seq Region;
5842 /// Filled in with declarations which were modified as a side-effect
5843 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005844 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00005845 /// Expressions to check later. We defer checking these to reduce
5846 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005847 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00005848
5849 /// RAII object wrapping the visitation of a sequenced subexpression of an
5850 /// expression. At the end of this process, the side-effects of the evaluation
5851 /// become sequenced with respect to the value computation of the result, so
5852 /// we downgrade any UK_ModAsSideEffect within the evaluation to
5853 /// UK_ModAsValue.
5854 struct SequencedSubexpression {
5855 SequencedSubexpression(SequenceChecker &Self)
5856 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5857 Self.ModAsSideEffect = &ModAsSideEffect;
5858 }
5859 ~SequencedSubexpression() {
5860 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5861 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5862 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5863 Self.addUsage(U, ModAsSideEffect[I].first,
5864 ModAsSideEffect[I].second.Use, UK_ModAsValue);
5865 }
5866 Self.ModAsSideEffect = OldModAsSideEffect;
5867 }
5868
5869 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005870 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5871 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00005872 };
5873
Richard Smith40238f02013-06-20 22:21:56 +00005874 /// RAII object wrapping the visitation of a subexpression which we might
5875 /// choose to evaluate as a constant. If any subexpression is evaluated and
5876 /// found to be non-constant, this allows us to suppress the evaluation of
5877 /// the outer expression.
5878 class EvaluationTracker {
5879 public:
5880 EvaluationTracker(SequenceChecker &Self)
5881 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
5882 Self.EvalTracker = this;
5883 }
5884 ~EvaluationTracker() {
5885 Self.EvalTracker = Prev;
5886 if (Prev)
5887 Prev->EvalOK &= EvalOK;
5888 }
5889
5890 bool evaluate(const Expr *E, bool &Result) {
5891 if (!EvalOK || E->isValueDependent())
5892 return false;
5893 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
5894 return EvalOK;
5895 }
5896
5897 private:
5898 SequenceChecker &Self;
5899 EvaluationTracker *Prev;
5900 bool EvalOK;
5901 } *EvalTracker;
5902
Richard Smithc406cb72013-01-17 01:17:56 +00005903 /// \brief Find the object which is produced by the specified expression,
5904 /// if any.
5905 Object getObject(Expr *E, bool Mod) const {
5906 E = E->IgnoreParenCasts();
5907 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5908 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5909 return getObject(UO->getSubExpr(), Mod);
5910 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5911 if (BO->getOpcode() == BO_Comma)
5912 return getObject(BO->getRHS(), Mod);
5913 if (Mod && BO->isAssignmentOp())
5914 return getObject(BO->getLHS(), Mod);
5915 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5916 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5917 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5918 return ME->getMemberDecl();
5919 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5920 // FIXME: If this is a reference, map through to its value.
5921 return DRE->getDecl();
5922 return 0;
5923 }
5924
5925 /// \brief Note that an object was modified or used by an expression.
5926 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5927 Usage &U = UI.Uses[UK];
5928 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5929 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5930 ModAsSideEffect->push_back(std::make_pair(O, U));
5931 U.Use = Ref;
5932 U.Seq = Region;
5933 }
5934 }
5935 /// \brief Check whether a modification or use conflicts with a prior usage.
5936 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5937 bool IsModMod) {
5938 if (UI.Diagnosed)
5939 return;
5940
5941 const Usage &U = UI.Uses[OtherKind];
5942 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5943 return;
5944
5945 Expr *Mod = U.Use;
5946 Expr *ModOrUse = Ref;
5947 if (OtherKind == UK_Use)
5948 std::swap(Mod, ModOrUse);
5949
5950 SemaRef.Diag(Mod->getExprLoc(),
5951 IsModMod ? diag::warn_unsequenced_mod_mod
5952 : diag::warn_unsequenced_mod_use)
5953 << O << SourceRange(ModOrUse->getExprLoc());
5954 UI.Diagnosed = true;
5955 }
5956
5957 void notePreUse(Object O, Expr *Use) {
5958 UsageInfo &U = UsageMap[O];
5959 // Uses conflict with other modifications.
5960 checkUsage(O, U, Use, UK_ModAsValue, false);
5961 }
5962 void notePostUse(Object O, Expr *Use) {
5963 UsageInfo &U = UsageMap[O];
5964 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5965 addUsage(U, O, Use, UK_Use);
5966 }
5967
5968 void notePreMod(Object O, Expr *Mod) {
5969 UsageInfo &U = UsageMap[O];
5970 // Modifications conflict with other modifications and with uses.
5971 checkUsage(O, U, Mod, UK_ModAsValue, true);
5972 checkUsage(O, U, Mod, UK_Use, false);
5973 }
5974 void notePostMod(Object O, Expr *Use, UsageKind UK) {
5975 UsageInfo &U = UsageMap[O];
5976 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5977 addUsage(U, O, Use, UK);
5978 }
5979
5980public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005981 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
5982 : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
5983 WorkList(WorkList), EvalTracker(0) {
Richard Smithc406cb72013-01-17 01:17:56 +00005984 Visit(E);
5985 }
5986
5987 void VisitStmt(Stmt *S) {
5988 // Skip all statements which aren't expressions for now.
5989 }
5990
5991 void VisitExpr(Expr *E) {
5992 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00005993 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00005994 }
5995
5996 void VisitCastExpr(CastExpr *E) {
5997 Object O = Object();
5998 if (E->getCastKind() == CK_LValueToRValue)
5999 O = getObject(E->getSubExpr(), false);
6000
6001 if (O)
6002 notePreUse(O, E);
6003 VisitExpr(E);
6004 if (O)
6005 notePostUse(O, E);
6006 }
6007
6008 void VisitBinComma(BinaryOperator *BO) {
6009 // C++11 [expr.comma]p1:
6010 // Every value computation and side effect associated with the left
6011 // expression is sequenced before every value computation and side
6012 // effect associated with the right expression.
6013 SequenceTree::Seq LHS = Tree.allocate(Region);
6014 SequenceTree::Seq RHS = Tree.allocate(Region);
6015 SequenceTree::Seq OldRegion = Region;
6016
6017 {
6018 SequencedSubexpression SeqLHS(*this);
6019 Region = LHS;
6020 Visit(BO->getLHS());
6021 }
6022
6023 Region = RHS;
6024 Visit(BO->getRHS());
6025
6026 Region = OldRegion;
6027
6028 // Forget that LHS and RHS are sequenced. They are both unsequenced
6029 // with respect to other stuff.
6030 Tree.merge(LHS);
6031 Tree.merge(RHS);
6032 }
6033
6034 void VisitBinAssign(BinaryOperator *BO) {
6035 // The modification is sequenced after the value computation of the LHS
6036 // and RHS, so check it before inspecting the operands and update the
6037 // map afterwards.
6038 Object O = getObject(BO->getLHS(), true);
6039 if (!O)
6040 return VisitExpr(BO);
6041
6042 notePreMod(O, BO);
6043
6044 // C++11 [expr.ass]p7:
6045 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
6046 // only once.
6047 //
6048 // Therefore, for a compound assignment operator, O is considered used
6049 // everywhere except within the evaluation of E1 itself.
6050 if (isa<CompoundAssignOperator>(BO))
6051 notePreUse(O, BO);
6052
6053 Visit(BO->getLHS());
6054
6055 if (isa<CompoundAssignOperator>(BO))
6056 notePostUse(O, BO);
6057
6058 Visit(BO->getRHS());
6059
Richard Smith83e37bee2013-06-26 23:16:51 +00006060 // C++11 [expr.ass]p1:
6061 // the assignment is sequenced [...] before the value computation of the
6062 // assignment expression.
6063 // C11 6.5.16/3 has no such rule.
6064 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6065 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006066 }
6067 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6068 VisitBinAssign(CAO);
6069 }
6070
6071 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6072 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6073 void VisitUnaryPreIncDec(UnaryOperator *UO) {
6074 Object O = getObject(UO->getSubExpr(), true);
6075 if (!O)
6076 return VisitExpr(UO);
6077
6078 notePreMod(O, UO);
6079 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00006080 // C++11 [expr.pre.incr]p1:
6081 // the expression ++x is equivalent to x+=1
6082 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6083 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006084 }
6085
6086 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6087 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6088 void VisitUnaryPostIncDec(UnaryOperator *UO) {
6089 Object O = getObject(UO->getSubExpr(), true);
6090 if (!O)
6091 return VisitExpr(UO);
6092
6093 notePreMod(O, UO);
6094 Visit(UO->getSubExpr());
6095 notePostMod(O, UO, UK_ModAsSideEffect);
6096 }
6097
6098 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6099 void VisitBinLOr(BinaryOperator *BO) {
6100 // The side-effects of the LHS of an '&&' are sequenced before the
6101 // value computation of the RHS, and hence before the value computation
6102 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6103 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00006104 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006105 {
6106 SequencedSubexpression Sequenced(*this);
6107 Visit(BO->getLHS());
6108 }
6109
6110 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006111 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006112 if (!Result)
6113 Visit(BO->getRHS());
6114 } else {
6115 // Check for unsequenced operations in the RHS, treating it as an
6116 // entirely separate evaluation.
6117 //
6118 // FIXME: If there are operations in the RHS which are unsequenced
6119 // with respect to operations outside the RHS, and those operations
6120 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00006121 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006122 }
Richard Smithc406cb72013-01-17 01:17:56 +00006123 }
6124 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00006125 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006126 {
6127 SequencedSubexpression Sequenced(*this);
6128 Visit(BO->getLHS());
6129 }
6130
6131 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006132 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006133 if (Result)
6134 Visit(BO->getRHS());
6135 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00006136 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006137 }
Richard Smithc406cb72013-01-17 01:17:56 +00006138 }
6139
6140 // Only visit the condition, unless we can be sure which subexpression will
6141 // be chosen.
6142 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00006143 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00006144 {
6145 SequencedSubexpression Sequenced(*this);
6146 Visit(CO->getCond());
6147 }
Richard Smithc406cb72013-01-17 01:17:56 +00006148
6149 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006150 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00006151 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006152 else {
Richard Smithd33f5202013-01-17 23:18:09 +00006153 WorkList.push_back(CO->getTrueExpr());
6154 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006155 }
Richard Smithc406cb72013-01-17 01:17:56 +00006156 }
6157
Richard Smithe3dbfe02013-06-30 10:40:20 +00006158 void VisitCallExpr(CallExpr *CE) {
6159 // C++11 [intro.execution]p15:
6160 // When calling a function [...], every value computation and side effect
6161 // associated with any argument expression, or with the postfix expression
6162 // designating the called function, is sequenced before execution of every
6163 // expression or statement in the body of the function [and thus before
6164 // the value computation of its result].
6165 SequencedSubexpression Sequenced(*this);
6166 Base::VisitCallExpr(CE);
6167
6168 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6169 }
6170
Richard Smithc406cb72013-01-17 01:17:56 +00006171 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006172 // This is a call, so all subexpressions are sequenced before the result.
6173 SequencedSubexpression Sequenced(*this);
6174
Richard Smithc406cb72013-01-17 01:17:56 +00006175 if (!CCE->isListInitialization())
6176 return VisitExpr(CCE);
6177
6178 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006179 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006180 SequenceTree::Seq Parent = Region;
6181 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6182 E = CCE->arg_end();
6183 I != E; ++I) {
6184 Region = Tree.allocate(Parent);
6185 Elts.push_back(Region);
6186 Visit(*I);
6187 }
6188
6189 // Forget that the initializers are sequenced.
6190 Region = Parent;
6191 for (unsigned I = 0; I < Elts.size(); ++I)
6192 Tree.merge(Elts[I]);
6193 }
6194
6195 void VisitInitListExpr(InitListExpr *ILE) {
6196 if (!SemaRef.getLangOpts().CPlusPlus11)
6197 return VisitExpr(ILE);
6198
6199 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006200 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006201 SequenceTree::Seq Parent = Region;
6202 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6203 Expr *E = ILE->getInit(I);
6204 if (!E) continue;
6205 Region = Tree.allocate(Parent);
6206 Elts.push_back(Region);
6207 Visit(E);
6208 }
6209
6210 // Forget that the initializers are sequenced.
6211 Region = Parent;
6212 for (unsigned I = 0; I < Elts.size(); ++I)
6213 Tree.merge(Elts[I]);
6214 }
6215};
6216}
6217
6218void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006219 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00006220 WorkList.push_back(E);
6221 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00006222 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00006223 SequenceChecker(*this, Item, WorkList);
6224 }
Richard Smithc406cb72013-01-17 01:17:56 +00006225}
6226
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006227void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6228 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006229 CheckImplicitConversions(E, CheckLoc);
6230 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006231 if (!IsConstexpr && !E->isValueDependent())
6232 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006233}
6234
John McCall1f425642010-11-11 03:21:53 +00006235void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6236 FieldDecl *BitField,
6237 Expr *Init) {
6238 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6239}
6240
Mike Stump0c2ec772010-01-21 03:59:47 +00006241/// CheckParmsForFunctionDef - Check that the parameters of the given
6242/// function are appropriate for the definition of a function. This
6243/// takes care of any checks that cannot be performed on the
6244/// declaration itself, e.g., that the types of each of the function
6245/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00006246bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6247 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00006248 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006249 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00006250 for (; P != PEnd; ++P) {
6251 ParmVarDecl *Param = *P;
6252
Mike Stump0c2ec772010-01-21 03:59:47 +00006253 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6254 // function declarator that is part of a function definition of
6255 // that function shall not have incomplete type.
6256 //
6257 // This is also C++ [dcl.fct]p6.
6258 if (!Param->isInvalidDecl() &&
6259 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006260 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006261 Param->setInvalidDecl();
6262 HasInvalidParm = true;
6263 }
6264
6265 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6266 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00006267 if (CheckParameterNames &&
6268 Param->getIdentifier() == 0 &&
Mike Stump0c2ec772010-01-21 03:59:47 +00006269 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006270 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00006271 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00006272
6273 // C99 6.7.5.3p12:
6274 // If the function declarator is not part of a definition of that
6275 // function, parameters may have incomplete type and may use the [*]
6276 // notation in their sequences of declarator specifiers to specify
6277 // variable length array types.
6278 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006279 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00006280 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00006281 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00006282 // information is added for it.
6283 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006284 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00006285 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006286 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00006287 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006288
6289 // MSVC destroys objects passed by value in the callee. Therefore a
6290 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006291 // object's destructor. However, we don't perform any direct access check
6292 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00006293 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
6294 .getCXXABI()
6295 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00006296 if (!Param->isInvalidDecl()) {
6297 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
6298 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
6299 if (!ClassDecl->isInvalidDecl() &&
6300 !ClassDecl->hasIrrelevantDestructor() &&
6301 !ClassDecl->isDependentContext()) {
6302 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6303 MarkFunctionReferenced(Param->getLocation(), Destructor);
6304 DiagnoseUseOfDecl(Destructor, Param->getLocation());
6305 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006306 }
6307 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006308 }
Mike Stump0c2ec772010-01-21 03:59:47 +00006309 }
6310
6311 return HasInvalidParm;
6312}
John McCall2b5c1b22010-08-12 21:44:57 +00006313
6314/// CheckCastAlign - Implements -Wcast-align, which warns when a
6315/// pointer cast increases the alignment requirements.
6316void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6317 // This is actually a lot of work to potentially be doing on every
6318 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00006319 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6320 TRange.getBegin())
David Blaikie9c902b52011-09-25 23:23:43 +00006321 == DiagnosticsEngine::Ignored)
John McCall2b5c1b22010-08-12 21:44:57 +00006322 return;
6323
6324 // Ignore dependent types.
6325 if (T->isDependentType() || Op->getType()->isDependentType())
6326 return;
6327
6328 // Require that the destination be a pointer type.
6329 const PointerType *DestPtr = T->getAs<PointerType>();
6330 if (!DestPtr) return;
6331
6332 // If the destination has alignment 1, we're done.
6333 QualType DestPointee = DestPtr->getPointeeType();
6334 if (DestPointee->isIncompleteType()) return;
6335 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6336 if (DestAlign.isOne()) return;
6337
6338 // Require that the source be a pointer type.
6339 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6340 if (!SrcPtr) return;
6341 QualType SrcPointee = SrcPtr->getPointeeType();
6342
6343 // Whitelist casts from cv void*. We already implicitly
6344 // whitelisted casts to cv void*, since they have alignment 1.
6345 // Also whitelist casts involving incomplete types, which implicitly
6346 // includes 'void'.
6347 if (SrcPointee->isIncompleteType()) return;
6348
6349 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6350 if (SrcAlign >= DestAlign) return;
6351
6352 Diag(TRange.getBegin(), diag::warn_cast_align)
6353 << Op->getType() << T
6354 << static_cast<unsigned>(SrcAlign.getQuantity())
6355 << static_cast<unsigned>(DestAlign.getQuantity())
6356 << TRange << Op->getSourceRange();
6357}
6358
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006359static const Type* getElementType(const Expr *BaseExpr) {
6360 const Type* EltType = BaseExpr->getType().getTypePtr();
6361 if (EltType->isAnyPointerType())
6362 return EltType->getPointeeType().getTypePtr();
6363 else if (EltType->isArrayType())
6364 return EltType->getBaseElementTypeUnsafe();
6365 return EltType;
6366}
6367
Chandler Carruth28389f02011-08-05 09:10:50 +00006368/// \brief Check whether this array fits the idiom of a size-one tail padded
6369/// array member of a struct.
6370///
6371/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6372/// commonly used to emulate flexible arrays in C89 code.
6373static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6374 const NamedDecl *ND) {
6375 if (Size != 1 || !ND) return false;
6376
6377 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6378 if (!FD) return false;
6379
6380 // Don't consider sizes resulting from macro expansions or template argument
6381 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00006382
6383 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006384 while (TInfo) {
6385 TypeLoc TL = TInfo->getTypeLoc();
6386 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00006387 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6388 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006389 TInfo = TDL->getTypeSourceInfo();
6390 continue;
6391 }
David Blaikie6adc78e2013-02-18 22:06:02 +00006392 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6393 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00006394 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6395 return false;
6396 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006397 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00006398 }
Chandler Carruth28389f02011-08-05 09:10:50 +00006399
6400 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00006401 if (!RD) return false;
6402 if (RD->isUnion()) return false;
6403 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6404 if (!CRD->isStandardLayout()) return false;
6405 }
Chandler Carruth28389f02011-08-05 09:10:50 +00006406
Benjamin Kramer8c543672011-08-06 03:04:42 +00006407 // See if this is the last field decl in the record.
6408 const Decl *D = FD;
6409 while ((D = D->getNextDeclInContext()))
6410 if (isa<FieldDecl>(D))
6411 return false;
6412 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00006413}
6414
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006415void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006416 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00006417 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006418 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006419 if (IndexExpr->isValueDependent())
6420 return;
6421
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00006422 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006423 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006424 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006425 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006426 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00006427 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00006428
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006429 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006430 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00006431 return;
Richard Smith13f67182011-12-16 19:31:14 +00006432 if (IndexNegated)
6433 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00006434
Chandler Carruth126b1552011-08-05 08:07:29 +00006435 const NamedDecl *ND = NULL;
Chandler Carruth126b1552011-08-05 08:07:29 +00006436 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6437 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00006438 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00006439 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00006440
Ted Kremeneke4b316c2011-02-23 23:06:04 +00006441 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006442 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00006443 if (!size.isStrictlyPositive())
6444 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006445
6446 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00006447 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006448 // Make sure we're comparing apples to apples when comparing index to size
6449 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6450 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00006451 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00006452 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006453 if (ptrarith_typesize != array_typesize) {
6454 // There's a cast to a different size type involved
6455 uint64_t ratio = array_typesize / ptrarith_typesize;
6456 // TODO: Be smarter about handling cases where array_typesize is not a
6457 // multiple of ptrarith_typesize
6458 if (ptrarith_typesize * ratio == array_typesize)
6459 size *= llvm::APInt(size.getBitWidth(), ratio);
6460 }
6461 }
6462
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006463 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006464 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006465 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006466 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006467
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006468 // For array subscripting the index must be less than size, but for pointer
6469 // arithmetic also allow the index (offset) to be equal to size since
6470 // computing the next address after the end of the array is legal and
6471 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006472 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00006473 return;
6474
6475 // Also don't warn for arrays of size 1 which are members of some
6476 // structure. These are often used to approximate flexible arrays in C89
6477 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006478 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00006479 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006480
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006481 // Suppress the warning if the subscript expression (as identified by the
6482 // ']' location) and the index expression are both from macro expansions
6483 // within a system header.
6484 if (ASE) {
6485 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6486 ASE->getRBracketLoc());
6487 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6488 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6489 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00006490 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006491 return;
6492 }
6493 }
6494
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006495 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006496 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006497 DiagID = diag::warn_array_index_exceeds_bounds;
6498
6499 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6500 PDiag(DiagID) << index.toString(10, true)
6501 << size.toString(10, true)
6502 << (unsigned)size.getLimitedValue(~0U)
6503 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006504 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006505 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006506 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006507 DiagID = diag::warn_ptr_arith_precedes_bounds;
6508 if (index.isNegative()) index = -index;
6509 }
6510
6511 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6512 PDiag(DiagID) << index.toString(10, true)
6513 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00006514 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00006515
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00006516 if (!ND) {
6517 // Try harder to find a NamedDecl to point at in the note.
6518 while (const ArraySubscriptExpr *ASE =
6519 dyn_cast<ArraySubscriptExpr>(BaseExpr))
6520 BaseExpr = ASE->getBase()->IgnoreParenCasts();
6521 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6522 ND = dyn_cast<NamedDecl>(DRE->getDecl());
6523 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6524 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6525 }
6526
Chandler Carruth1af88f12011-02-17 21:10:52 +00006527 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006528 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6529 PDiag(diag::note_array_index_out_of_bounds)
6530 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00006531}
6532
Ted Kremenekdf26df72011-03-01 18:41:00 +00006533void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006534 int AllowOnePastEnd = 0;
6535 while (expr) {
6536 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00006537 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006538 case Stmt::ArraySubscriptExprClass: {
6539 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006540 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006541 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00006542 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006543 }
6544 case Stmt::UnaryOperatorClass: {
6545 // Only unwrap the * and & unary operators
6546 const UnaryOperator *UO = cast<UnaryOperator>(expr);
6547 expr = UO->getSubExpr();
6548 switch (UO->getOpcode()) {
6549 case UO_AddrOf:
6550 AllowOnePastEnd++;
6551 break;
6552 case UO_Deref:
6553 AllowOnePastEnd--;
6554 break;
6555 default:
6556 return;
6557 }
6558 break;
6559 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00006560 case Stmt::ConditionalOperatorClass: {
6561 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
6562 if (const Expr *lhs = cond->getLHS())
6563 CheckArrayAccess(lhs);
6564 if (const Expr *rhs = cond->getRHS())
6565 CheckArrayAccess(rhs);
6566 return;
6567 }
6568 default:
6569 return;
6570 }
Peter Collingbourne91147592011-04-15 00:35:48 +00006571 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00006572}
John McCall31168b02011-06-15 23:02:42 +00006573
6574//===--- CHECK: Objective-C retain cycles ----------------------------------//
6575
6576namespace {
6577 struct RetainCycleOwner {
6578 RetainCycleOwner() : Variable(0), Indirect(false) {}
6579 VarDecl *Variable;
6580 SourceRange Range;
6581 SourceLocation Loc;
6582 bool Indirect;
6583
6584 void setLocsFrom(Expr *e) {
6585 Loc = e->getExprLoc();
6586 Range = e->getSourceRange();
6587 }
6588 };
6589}
6590
6591/// Consider whether capturing the given variable can possibly lead to
6592/// a retain cycle.
6593static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00006594 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00006595 // lifetime. In MRR, it's captured strongly if the variable is
6596 // __block and has an appropriate type.
6597 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6598 return false;
6599
6600 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00006601 if (ref)
6602 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00006603 return true;
6604}
6605
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006606static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00006607 while (true) {
6608 e = e->IgnoreParens();
6609 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6610 switch (cast->getCastKind()) {
6611 case CK_BitCast:
6612 case CK_LValueBitCast:
6613 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00006614 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00006615 e = cast->getSubExpr();
6616 continue;
6617
John McCall31168b02011-06-15 23:02:42 +00006618 default:
6619 return false;
6620 }
6621 }
6622
6623 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6624 ObjCIvarDecl *ivar = ref->getDecl();
6625 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6626 return false;
6627
6628 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006629 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00006630 return false;
6631
6632 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6633 owner.Indirect = true;
6634 return true;
6635 }
6636
6637 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6638 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6639 if (!var) return false;
6640 return considerVariable(var, ref, owner);
6641 }
6642
John McCall31168b02011-06-15 23:02:42 +00006643 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6644 if (member->isArrow()) return false;
6645
6646 // Don't count this as an indirect ownership.
6647 e = member->getBase();
6648 continue;
6649 }
6650
John McCallfe96e0b2011-11-06 09:01:30 +00006651 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6652 // Only pay attention to pseudo-objects on property references.
6653 ObjCPropertyRefExpr *pre
6654 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6655 ->IgnoreParens());
6656 if (!pre) return false;
6657 if (pre->isImplicitProperty()) return false;
6658 ObjCPropertyDecl *property = pre->getExplicitProperty();
6659 if (!property->isRetaining() &&
6660 !(property->getPropertyIvarDecl() &&
6661 property->getPropertyIvarDecl()->getType()
6662 .getObjCLifetime() == Qualifiers::OCL_Strong))
6663 return false;
6664
6665 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006666 if (pre->isSuperReceiver()) {
6667 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6668 if (!owner.Variable)
6669 return false;
6670 owner.Loc = pre->getLocation();
6671 owner.Range = pre->getSourceRange();
6672 return true;
6673 }
John McCallfe96e0b2011-11-06 09:01:30 +00006674 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6675 ->getSourceExpr());
6676 continue;
6677 }
6678
John McCall31168b02011-06-15 23:02:42 +00006679 // Array ivars?
6680
6681 return false;
6682 }
6683}
6684
6685namespace {
6686 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6687 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6688 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6689 Variable(variable), Capturer(0) {}
6690
6691 VarDecl *Variable;
6692 Expr *Capturer;
6693
6694 void VisitDeclRefExpr(DeclRefExpr *ref) {
6695 if (ref->getDecl() == Variable && !Capturer)
6696 Capturer = ref;
6697 }
6698
John McCall31168b02011-06-15 23:02:42 +00006699 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6700 if (Capturer) return;
6701 Visit(ref->getBase());
6702 if (Capturer && ref->isFreeIvar())
6703 Capturer = ref;
6704 }
6705
6706 void VisitBlockExpr(BlockExpr *block) {
6707 // Look inside nested blocks
6708 if (block->getBlockDecl()->capturesVariable(Variable))
6709 Visit(block->getBlockDecl()->getBody());
6710 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00006711
6712 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6713 if (Capturer) return;
6714 if (OVE->getSourceExpr())
6715 Visit(OVE->getSourceExpr());
6716 }
John McCall31168b02011-06-15 23:02:42 +00006717 };
6718}
6719
6720/// Check whether the given argument is a block which captures a
6721/// variable.
6722static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6723 assert(owner.Variable && owner.Loc.isValid());
6724
6725 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00006726
6727 // Look through [^{...} copy] and Block_copy(^{...}).
6728 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6729 Selector Cmd = ME->getSelector();
6730 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6731 e = ME->getInstanceReceiver();
6732 if (!e)
6733 return 0;
6734 e = e->IgnoreParenCasts();
6735 }
6736 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6737 if (CE->getNumArgs() == 1) {
6738 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00006739 if (Fn) {
6740 const IdentifierInfo *FnI = Fn->getIdentifier();
6741 if (FnI && FnI->isStr("_Block_copy")) {
6742 e = CE->getArg(0)->IgnoreParenCasts();
6743 }
6744 }
Jordan Rose67e887c2012-09-17 17:54:30 +00006745 }
6746 }
6747
John McCall31168b02011-06-15 23:02:42 +00006748 BlockExpr *block = dyn_cast<BlockExpr>(e);
6749 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6750 return 0;
6751
6752 FindCaptureVisitor visitor(S.Context, owner.Variable);
6753 visitor.Visit(block->getBlockDecl()->getBody());
6754 return visitor.Capturer;
6755}
6756
6757static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6758 RetainCycleOwner &owner) {
6759 assert(capturer);
6760 assert(owner.Variable && owner.Loc.isValid());
6761
6762 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6763 << owner.Variable << capturer->getSourceRange();
6764 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6765 << owner.Indirect << owner.Range;
6766}
6767
6768/// Check for a keyword selector that starts with the word 'add' or
6769/// 'set'.
6770static bool isSetterLikeSelector(Selector sel) {
6771 if (sel.isUnarySelector()) return false;
6772
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006773 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00006774 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00006775 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00006776 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00006777 else if (str.startswith("add")) {
6778 // Specially whitelist 'addOperationWithBlock:'.
6779 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6780 return false;
6781 str = str.substr(3);
6782 }
John McCall31168b02011-06-15 23:02:42 +00006783 else
6784 return false;
6785
6786 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00006787 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00006788}
6789
6790/// Check a message send to see if it's likely to cause a retain cycle.
6791void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6792 // Only check instance methods whose selector looks like a setter.
6793 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6794 return;
6795
6796 // Try to find a variable that the receiver is strongly owned by.
6797 RetainCycleOwner owner;
6798 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006799 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00006800 return;
6801 } else {
6802 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6803 owner.Variable = getCurMethodDecl()->getSelfDecl();
6804 owner.Loc = msg->getSuperLoc();
6805 owner.Range = msg->getSuperLoc();
6806 }
6807
6808 // Check whether the receiver is captured by any of the arguments.
6809 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6810 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6811 return diagnoseRetainCycle(*this, capturer, owner);
6812}
6813
6814/// Check a property assign to see if it's likely to cause a retain cycle.
6815void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6816 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006817 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00006818 return;
6819
6820 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6821 diagnoseRetainCycle(*this, capturer, owner);
6822}
6823
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00006824void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6825 RetainCycleOwner Owner;
6826 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6827 return;
6828
6829 // Because we don't have an expression for the variable, we have to set the
6830 // location explicitly here.
6831 Owner.Loc = Var->getLocation();
6832 Owner.Range = Var->getSourceRange();
6833
6834 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6835 diagnoseRetainCycle(*this, Capturer, Owner);
6836}
6837
Ted Kremenek9304da92012-12-21 08:04:28 +00006838static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6839 Expr *RHS, bool isProperty) {
6840 // Check if RHS is an Objective-C object literal, which also can get
6841 // immediately zapped in a weak reference. Note that we explicitly
6842 // allow ObjCStringLiterals, since those are designed to never really die.
6843 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00006844
Ted Kremenek64873352012-12-21 22:46:35 +00006845 // This enum needs to match with the 'select' in
6846 // warn_objc_arc_literal_assign (off-by-1).
6847 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6848 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6849 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00006850
6851 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00006852 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00006853 << (isProperty ? 0 : 1)
6854 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00006855
6856 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00006857}
6858
Ted Kremenekc1f014a2012-12-21 19:45:30 +00006859static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6860 Qualifiers::ObjCLifetime LT,
6861 Expr *RHS, bool isProperty) {
6862 // Strip off any implicit cast added to get to the one ARC-specific.
6863 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6864 if (cast->getCastKind() == CK_ARCConsumeObject) {
6865 S.Diag(Loc, diag::warn_arc_retained_assign)
6866 << (LT == Qualifiers::OCL_ExplicitNone)
6867 << (isProperty ? 0 : 1)
6868 << RHS->getSourceRange();
6869 return true;
6870 }
6871 RHS = cast->getSubExpr();
6872 }
6873
6874 if (LT == Qualifiers::OCL_Weak &&
6875 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6876 return true;
6877
6878 return false;
6879}
6880
Ted Kremenekb36234d2012-12-21 08:04:20 +00006881bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6882 QualType LHS, Expr *RHS) {
6883 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6884
6885 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6886 return false;
6887
6888 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6889 return true;
6890
6891 return false;
6892}
6893
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006894void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6895 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006896 QualType LHSType;
6897 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00006898 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006899 ObjCPropertyRefExpr *PRE
6900 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6901 if (PRE && !PRE->isImplicitProperty()) {
6902 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6903 if (PD)
6904 LHSType = PD->getType();
6905 }
6906
6907 if (LHSType.isNull())
6908 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00006909
6910 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6911
6912 if (LT == Qualifiers::OCL_Weak) {
6913 DiagnosticsEngine::Level Level =
6914 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6915 if (Level != DiagnosticsEngine::Ignored)
6916 getCurFunction()->markSafeWeakUse(LHS);
6917 }
6918
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006919 if (checkUnsafeAssigns(Loc, LHSType, RHS))
6920 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00006921
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006922 // FIXME. Check for other life times.
6923 if (LT != Qualifiers::OCL_None)
6924 return;
6925
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006926 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006927 if (PRE->isImplicitProperty())
6928 return;
6929 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6930 if (!PD)
6931 return;
6932
Bill Wendling44426052012-12-20 19:22:21 +00006933 unsigned Attributes = PD->getPropertyAttributes();
6934 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006935 // when 'assign' attribute was not explicitly specified
6936 // by user, ignore it and rely on property type itself
6937 // for lifetime info.
6938 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6939 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6940 LHSType->isObjCRetainableType())
6941 return;
6942
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006943 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00006944 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006945 Diag(Loc, diag::warn_arc_retained_property_assign)
6946 << RHS->getSourceRange();
6947 return;
6948 }
6949 RHS = cast->getSubExpr();
6950 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006951 }
Bill Wendling44426052012-12-20 19:22:21 +00006952 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00006953 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6954 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00006955 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006956 }
6957}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00006958
6959//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6960
6961namespace {
6962bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6963 SourceLocation StmtLoc,
6964 const NullStmt *Body) {
6965 // Do not warn if the body is a macro that expands to nothing, e.g:
6966 //
6967 // #define CALL(x)
6968 // if (condition)
6969 // CALL(0);
6970 //
6971 if (Body->hasLeadingEmptyMacro())
6972 return false;
6973
6974 // Get line numbers of statement and body.
6975 bool StmtLineInvalid;
6976 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6977 &StmtLineInvalid);
6978 if (StmtLineInvalid)
6979 return false;
6980
6981 bool BodyLineInvalid;
6982 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
6983 &BodyLineInvalid);
6984 if (BodyLineInvalid)
6985 return false;
6986
6987 // Warn if null statement and body are on the same line.
6988 if (StmtLine != BodyLine)
6989 return false;
6990
6991 return true;
6992}
6993} // Unnamed namespace
6994
6995void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
6996 const Stmt *Body,
6997 unsigned DiagID) {
6998 // Since this is a syntactic check, don't emit diagnostic for template
6999 // instantiations, this just adds noise.
7000 if (CurrentInstantiationScope)
7001 return;
7002
7003 // The body should be a null statement.
7004 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7005 if (!NBody)
7006 return;
7007
7008 // Do the usual checks.
7009 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7010 return;
7011
7012 Diag(NBody->getSemiLoc(), DiagID);
7013 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7014}
7015
7016void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
7017 const Stmt *PossibleBody) {
7018 assert(!CurrentInstantiationScope); // Ensured by caller
7019
7020 SourceLocation StmtLoc;
7021 const Stmt *Body;
7022 unsigned DiagID;
7023 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
7024 StmtLoc = FS->getRParenLoc();
7025 Body = FS->getBody();
7026 DiagID = diag::warn_empty_for_body;
7027 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
7028 StmtLoc = WS->getCond()->getSourceRange().getEnd();
7029 Body = WS->getBody();
7030 DiagID = diag::warn_empty_while_body;
7031 } else
7032 return; // Neither `for' nor `while'.
7033
7034 // The body should be a null statement.
7035 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7036 if (!NBody)
7037 return;
7038
7039 // Skip expensive checks if diagnostic is disabled.
7040 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
7041 DiagnosticsEngine::Ignored)
7042 return;
7043
7044 // Do the usual checks.
7045 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7046 return;
7047
7048 // `for(...);' and `while(...);' are popular idioms, so in order to keep
7049 // noise level low, emit diagnostics only if for/while is followed by a
7050 // CompoundStmt, e.g.:
7051 // for (int i = 0; i < n; i++);
7052 // {
7053 // a(i);
7054 // }
7055 // or if for/while is followed by a statement with more indentation
7056 // than for/while itself:
7057 // for (int i = 0; i < n; i++);
7058 // a(i);
7059 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
7060 if (!ProbableTypo) {
7061 bool BodyColInvalid;
7062 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
7063 PossibleBody->getLocStart(),
7064 &BodyColInvalid);
7065 if (BodyColInvalid)
7066 return;
7067
7068 bool StmtColInvalid;
7069 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7070 S->getLocStart(),
7071 &StmtColInvalid);
7072 if (StmtColInvalid)
7073 return;
7074
7075 if (BodyCol > StmtCol)
7076 ProbableTypo = true;
7077 }
7078
7079 if (ProbableTypo) {
7080 Diag(NBody->getSemiLoc(), DiagID);
7081 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7082 }
7083}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007084
7085//===--- Layout compatibility ----------------------------------------------//
7086
7087namespace {
7088
7089bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7090
7091/// \brief Check if two enumeration types are layout-compatible.
7092bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7093 // C++11 [dcl.enum] p8:
7094 // Two enumeration types are layout-compatible if they have the same
7095 // underlying type.
7096 return ED1->isComplete() && ED2->isComplete() &&
7097 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7098}
7099
7100/// \brief Check if two fields are layout-compatible.
7101bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7102 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7103 return false;
7104
7105 if (Field1->isBitField() != Field2->isBitField())
7106 return false;
7107
7108 if (Field1->isBitField()) {
7109 // Make sure that the bit-fields are the same length.
7110 unsigned Bits1 = Field1->getBitWidthValue(C);
7111 unsigned Bits2 = Field2->getBitWidthValue(C);
7112
7113 if (Bits1 != Bits2)
7114 return false;
7115 }
7116
7117 return true;
7118}
7119
7120/// \brief Check if two standard-layout structs are layout-compatible.
7121/// (C++11 [class.mem] p17)
7122bool isLayoutCompatibleStruct(ASTContext &C,
7123 RecordDecl *RD1,
7124 RecordDecl *RD2) {
7125 // If both records are C++ classes, check that base classes match.
7126 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7127 // If one of records is a CXXRecordDecl we are in C++ mode,
7128 // thus the other one is a CXXRecordDecl, too.
7129 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7130 // Check number of base classes.
7131 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7132 return false;
7133
7134 // Check the base classes.
7135 for (CXXRecordDecl::base_class_const_iterator
7136 Base1 = D1CXX->bases_begin(),
7137 BaseEnd1 = D1CXX->bases_end(),
7138 Base2 = D2CXX->bases_begin();
7139 Base1 != BaseEnd1;
7140 ++Base1, ++Base2) {
7141 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7142 return false;
7143 }
7144 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7145 // If only RD2 is a C++ class, it should have zero base classes.
7146 if (D2CXX->getNumBases() > 0)
7147 return false;
7148 }
7149
7150 // Check the fields.
7151 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7152 Field2End = RD2->field_end(),
7153 Field1 = RD1->field_begin(),
7154 Field1End = RD1->field_end();
7155 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7156 if (!isLayoutCompatible(C, *Field1, *Field2))
7157 return false;
7158 }
7159 if (Field1 != Field1End || Field2 != Field2End)
7160 return false;
7161
7162 return true;
7163}
7164
7165/// \brief Check if two standard-layout unions are layout-compatible.
7166/// (C++11 [class.mem] p18)
7167bool isLayoutCompatibleUnion(ASTContext &C,
7168 RecordDecl *RD1,
7169 RecordDecl *RD2) {
7170 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
7171 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
7172 Field2End = RD2->field_end();
7173 Field2 != Field2End; ++Field2) {
7174 UnmatchedFields.insert(*Field2);
7175 }
7176
7177 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
7178 Field1End = RD1->field_end();
7179 Field1 != Field1End; ++Field1) {
7180 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7181 I = UnmatchedFields.begin(),
7182 E = UnmatchedFields.end();
7183
7184 for ( ; I != E; ++I) {
7185 if (isLayoutCompatible(C, *Field1, *I)) {
7186 bool Result = UnmatchedFields.erase(*I);
7187 (void) Result;
7188 assert(Result);
7189 break;
7190 }
7191 }
7192 if (I == E)
7193 return false;
7194 }
7195
7196 return UnmatchedFields.empty();
7197}
7198
7199bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7200 if (RD1->isUnion() != RD2->isUnion())
7201 return false;
7202
7203 if (RD1->isUnion())
7204 return isLayoutCompatibleUnion(C, RD1, RD2);
7205 else
7206 return isLayoutCompatibleStruct(C, RD1, RD2);
7207}
7208
7209/// \brief Check if two types are layout-compatible in C++11 sense.
7210bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7211 if (T1.isNull() || T2.isNull())
7212 return false;
7213
7214 // C++11 [basic.types] p11:
7215 // If two types T1 and T2 are the same type, then T1 and T2 are
7216 // layout-compatible types.
7217 if (C.hasSameType(T1, T2))
7218 return true;
7219
7220 T1 = T1.getCanonicalType().getUnqualifiedType();
7221 T2 = T2.getCanonicalType().getUnqualifiedType();
7222
7223 const Type::TypeClass TC1 = T1->getTypeClass();
7224 const Type::TypeClass TC2 = T2->getTypeClass();
7225
7226 if (TC1 != TC2)
7227 return false;
7228
7229 if (TC1 == Type::Enum) {
7230 return isLayoutCompatible(C,
7231 cast<EnumType>(T1)->getDecl(),
7232 cast<EnumType>(T2)->getDecl());
7233 } else if (TC1 == Type::Record) {
7234 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7235 return false;
7236
7237 return isLayoutCompatible(C,
7238 cast<RecordType>(T1)->getDecl(),
7239 cast<RecordType>(T2)->getDecl());
7240 }
7241
7242 return false;
7243}
7244}
7245
7246//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7247
7248namespace {
7249/// \brief Given a type tag expression find the type tag itself.
7250///
7251/// \param TypeExpr Type tag expression, as it appears in user's code.
7252///
7253/// \param VD Declaration of an identifier that appears in a type tag.
7254///
7255/// \param MagicValue Type tag magic value.
7256bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7257 const ValueDecl **VD, uint64_t *MagicValue) {
7258 while(true) {
7259 if (!TypeExpr)
7260 return false;
7261
7262 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7263
7264 switch (TypeExpr->getStmtClass()) {
7265 case Stmt::UnaryOperatorClass: {
7266 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7267 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7268 TypeExpr = UO->getSubExpr();
7269 continue;
7270 }
7271 return false;
7272 }
7273
7274 case Stmt::DeclRefExprClass: {
7275 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7276 *VD = DRE->getDecl();
7277 return true;
7278 }
7279
7280 case Stmt::IntegerLiteralClass: {
7281 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7282 llvm::APInt MagicValueAPInt = IL->getValue();
7283 if (MagicValueAPInt.getActiveBits() <= 64) {
7284 *MagicValue = MagicValueAPInt.getZExtValue();
7285 return true;
7286 } else
7287 return false;
7288 }
7289
7290 case Stmt::BinaryConditionalOperatorClass:
7291 case Stmt::ConditionalOperatorClass: {
7292 const AbstractConditionalOperator *ACO =
7293 cast<AbstractConditionalOperator>(TypeExpr);
7294 bool Result;
7295 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7296 if (Result)
7297 TypeExpr = ACO->getTrueExpr();
7298 else
7299 TypeExpr = ACO->getFalseExpr();
7300 continue;
7301 }
7302 return false;
7303 }
7304
7305 case Stmt::BinaryOperatorClass: {
7306 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7307 if (BO->getOpcode() == BO_Comma) {
7308 TypeExpr = BO->getRHS();
7309 continue;
7310 }
7311 return false;
7312 }
7313
7314 default:
7315 return false;
7316 }
7317 }
7318}
7319
7320/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7321///
7322/// \param TypeExpr Expression that specifies a type tag.
7323///
7324/// \param MagicValues Registered magic values.
7325///
7326/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7327/// kind.
7328///
7329/// \param TypeInfo Information about the corresponding C type.
7330///
7331/// \returns true if the corresponding C type was found.
7332bool GetMatchingCType(
7333 const IdentifierInfo *ArgumentKind,
7334 const Expr *TypeExpr, const ASTContext &Ctx,
7335 const llvm::DenseMap<Sema::TypeTagMagicValue,
7336 Sema::TypeTagData> *MagicValues,
7337 bool &FoundWrongKind,
7338 Sema::TypeTagData &TypeInfo) {
7339 FoundWrongKind = false;
7340
7341 // Variable declaration that has type_tag_for_datatype attribute.
7342 const ValueDecl *VD = NULL;
7343
7344 uint64_t MagicValue;
7345
7346 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7347 return false;
7348
7349 if (VD) {
7350 for (specific_attr_iterator<TypeTagForDatatypeAttr>
7351 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
7352 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
7353 I != E; ++I) {
7354 if (I->getArgumentKind() != ArgumentKind) {
7355 FoundWrongKind = true;
7356 return false;
7357 }
7358 TypeInfo.Type = I->getMatchingCType();
7359 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7360 TypeInfo.MustBeNull = I->getMustBeNull();
7361 return true;
7362 }
7363 return false;
7364 }
7365
7366 if (!MagicValues)
7367 return false;
7368
7369 llvm::DenseMap<Sema::TypeTagMagicValue,
7370 Sema::TypeTagData>::const_iterator I =
7371 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7372 if (I == MagicValues->end())
7373 return false;
7374
7375 TypeInfo = I->second;
7376 return true;
7377}
7378} // unnamed namespace
7379
7380void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7381 uint64_t MagicValue, QualType Type,
7382 bool LayoutCompatible,
7383 bool MustBeNull) {
7384 if (!TypeTagForDatatypeMagicValues)
7385 TypeTagForDatatypeMagicValues.reset(
7386 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7387
7388 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7389 (*TypeTagForDatatypeMagicValues)[Magic] =
7390 TypeTagData(Type, LayoutCompatible, MustBeNull);
7391}
7392
7393namespace {
7394bool IsSameCharType(QualType T1, QualType T2) {
7395 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7396 if (!BT1)
7397 return false;
7398
7399 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7400 if (!BT2)
7401 return false;
7402
7403 BuiltinType::Kind T1Kind = BT1->getKind();
7404 BuiltinType::Kind T2Kind = BT2->getKind();
7405
7406 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
7407 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
7408 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7409 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7410}
7411} // unnamed namespace
7412
7413void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7414 const Expr * const *ExprArgs) {
7415 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7416 bool IsPointerAttr = Attr->getIsPointer();
7417
7418 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7419 bool FoundWrongKind;
7420 TypeTagData TypeInfo;
7421 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7422 TypeTagForDatatypeMagicValues.get(),
7423 FoundWrongKind, TypeInfo)) {
7424 if (FoundWrongKind)
7425 Diag(TypeTagExpr->getExprLoc(),
7426 diag::warn_type_tag_for_datatype_wrong_kind)
7427 << TypeTagExpr->getSourceRange();
7428 return;
7429 }
7430
7431 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7432 if (IsPointerAttr) {
7433 // Skip implicit cast of pointer to `void *' (as a function argument).
7434 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00007435 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00007436 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007437 ArgumentExpr = ICE->getSubExpr();
7438 }
7439 QualType ArgumentType = ArgumentExpr->getType();
7440
7441 // Passing a `void*' pointer shouldn't trigger a warning.
7442 if (IsPointerAttr && ArgumentType->isVoidPointerType())
7443 return;
7444
7445 if (TypeInfo.MustBeNull) {
7446 // Type tag with matching void type requires a null pointer.
7447 if (!ArgumentExpr->isNullPointerConstant(Context,
7448 Expr::NPC_ValueDependentIsNotNull)) {
7449 Diag(ArgumentExpr->getExprLoc(),
7450 diag::warn_type_safety_null_pointer_required)
7451 << ArgumentKind->getName()
7452 << ArgumentExpr->getSourceRange()
7453 << TypeTagExpr->getSourceRange();
7454 }
7455 return;
7456 }
7457
7458 QualType RequiredType = TypeInfo.Type;
7459 if (IsPointerAttr)
7460 RequiredType = Context.getPointerType(RequiredType);
7461
7462 bool mismatch = false;
7463 if (!TypeInfo.LayoutCompatible) {
7464 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7465
7466 // C++11 [basic.fundamental] p1:
7467 // Plain char, signed char, and unsigned char are three distinct types.
7468 //
7469 // But we treat plain `char' as equivalent to `signed char' or `unsigned
7470 // char' depending on the current char signedness mode.
7471 if (mismatch)
7472 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7473 RequiredType->getPointeeType())) ||
7474 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7475 mismatch = false;
7476 } else
7477 if (IsPointerAttr)
7478 mismatch = !isLayoutCompatible(Context,
7479 ArgumentType->getPointeeType(),
7480 RequiredType->getPointeeType());
7481 else
7482 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7483
7484 if (mismatch)
7485 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00007486 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007487 << TypeInfo.LayoutCompatible << RequiredType
7488 << ArgumentExpr->getSourceRange()
7489 << TypeTagExpr->getSourceRange();
7490}