blob: 592de529b59648acf2f847112227768d534f6672 [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"
Alp Tokerb6cc5922014-05-03 03:45:55 +000030#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000031#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 {
Alp Tokerb6cc5922014-05-03 03:45:55 +000046 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
47 Context.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:
Reid Kleckner597e81d2014-03-26 15:38:33 +0000145 case Builtin::BI__va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000146 if (SemaBuiltinVAStart(TheCall))
147 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000148 break;
Chris Lattner2da14fb2007-12-20 00:26:33 +0000149 case Builtin::BI__builtin_isgreater:
150 case Builtin::BI__builtin_isgreaterequal:
151 case Builtin::BI__builtin_isless:
152 case Builtin::BI__builtin_islessequal:
153 case Builtin::BI__builtin_islessgreater:
154 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000155 if (SemaBuiltinUnorderedCompare(TheCall))
156 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000157 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000158 case Builtin::BI__builtin_fpclassify:
159 if (SemaBuiltinFPClassification(TheCall, 6))
160 return ExprError();
161 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000162 case Builtin::BI__builtin_isfinite:
163 case Builtin::BI__builtin_isinf:
164 case Builtin::BI__builtin_isinf_sign:
165 case Builtin::BI__builtin_isnan:
166 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000167 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000168 return ExprError();
169 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000170 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000171 return SemaBuiltinShuffleVector(TheCall);
172 // TheCall will be freed by the smart pointer here, but that's fine, since
173 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000174 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000175 if (SemaBuiltinPrefetch(TheCall))
176 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000177 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000178 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000179 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000180 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000181 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000182 case Builtin::BI__builtin_longjmp:
183 if (SemaBuiltinLongjmp(TheCall))
184 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000185 break;
John McCallbebede42011-02-26 05:39:39 +0000186
187 case Builtin::BI__builtin_classify_type:
188 if (checkArgCount(*this, TheCall, 1)) return true;
189 TheCall->setType(Context.IntTy);
190 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000191 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000192 if (checkArgCount(*this, TheCall, 1)) return true;
193 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000194 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000195 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000196 case Builtin::BI__sync_fetch_and_add_1:
197 case Builtin::BI__sync_fetch_and_add_2:
198 case Builtin::BI__sync_fetch_and_add_4:
199 case Builtin::BI__sync_fetch_and_add_8:
200 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000201 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000202 case Builtin::BI__sync_fetch_and_sub_1:
203 case Builtin::BI__sync_fetch_and_sub_2:
204 case Builtin::BI__sync_fetch_and_sub_4:
205 case Builtin::BI__sync_fetch_and_sub_8:
206 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000207 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000208 case Builtin::BI__sync_fetch_and_or_1:
209 case Builtin::BI__sync_fetch_and_or_2:
210 case Builtin::BI__sync_fetch_and_or_4:
211 case Builtin::BI__sync_fetch_and_or_8:
212 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000213 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000214 case Builtin::BI__sync_fetch_and_and_1:
215 case Builtin::BI__sync_fetch_and_and_2:
216 case Builtin::BI__sync_fetch_and_and_4:
217 case Builtin::BI__sync_fetch_and_and_8:
218 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000219 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000220 case Builtin::BI__sync_fetch_and_xor_1:
221 case Builtin::BI__sync_fetch_and_xor_2:
222 case Builtin::BI__sync_fetch_and_xor_4:
223 case Builtin::BI__sync_fetch_and_xor_8:
224 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000225 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000226 case Builtin::BI__sync_add_and_fetch_1:
227 case Builtin::BI__sync_add_and_fetch_2:
228 case Builtin::BI__sync_add_and_fetch_4:
229 case Builtin::BI__sync_add_and_fetch_8:
230 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000231 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000232 case Builtin::BI__sync_sub_and_fetch_1:
233 case Builtin::BI__sync_sub_and_fetch_2:
234 case Builtin::BI__sync_sub_and_fetch_4:
235 case Builtin::BI__sync_sub_and_fetch_8:
236 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000237 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000238 case Builtin::BI__sync_and_and_fetch_1:
239 case Builtin::BI__sync_and_and_fetch_2:
240 case Builtin::BI__sync_and_and_fetch_4:
241 case Builtin::BI__sync_and_and_fetch_8:
242 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000243 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000244 case Builtin::BI__sync_or_and_fetch_1:
245 case Builtin::BI__sync_or_and_fetch_2:
246 case Builtin::BI__sync_or_and_fetch_4:
247 case Builtin::BI__sync_or_and_fetch_8:
248 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000249 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000250 case Builtin::BI__sync_xor_and_fetch_1:
251 case Builtin::BI__sync_xor_and_fetch_2:
252 case Builtin::BI__sync_xor_and_fetch_4:
253 case Builtin::BI__sync_xor_and_fetch_8:
254 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000255 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000256 case Builtin::BI__sync_val_compare_and_swap_1:
257 case Builtin::BI__sync_val_compare_and_swap_2:
258 case Builtin::BI__sync_val_compare_and_swap_4:
259 case Builtin::BI__sync_val_compare_and_swap_8:
260 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000261 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000262 case Builtin::BI__sync_bool_compare_and_swap_1:
263 case Builtin::BI__sync_bool_compare_and_swap_2:
264 case Builtin::BI__sync_bool_compare_and_swap_4:
265 case Builtin::BI__sync_bool_compare_and_swap_8:
266 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000267 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000268 case Builtin::BI__sync_lock_test_and_set_1:
269 case Builtin::BI__sync_lock_test_and_set_2:
270 case Builtin::BI__sync_lock_test_and_set_4:
271 case Builtin::BI__sync_lock_test_and_set_8:
272 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000273 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000274 case Builtin::BI__sync_lock_release_1:
275 case Builtin::BI__sync_lock_release_2:
276 case Builtin::BI__sync_lock_release_4:
277 case Builtin::BI__sync_lock_release_8:
278 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000279 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000280 case Builtin::BI__sync_swap_1:
281 case Builtin::BI__sync_swap_2:
282 case Builtin::BI__sync_swap_4:
283 case Builtin::BI__sync_swap_8:
284 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000285 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000286#define BUILTIN(ID, TYPE, ATTRS)
287#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
288 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000289 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000290#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000291 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000292 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000293 return ExprError();
294 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000295 case Builtin::BI__builtin_addressof:
296 if (SemaBuiltinAddressof(*this, TheCall))
297 return ExprError();
298 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000299 }
300
301 // Since the target specific builtins for each arch overlap, only check those
302 // of the arch we are compiling for.
303 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000304 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000305 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000306 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000307 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000308 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000309 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
310 return ExprError();
311 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000312 case llvm::Triple::aarch64:
313 case llvm::Triple::aarch64_be:
Tim Northovera2ee4332014-03-29 15:09:45 +0000314 case llvm::Triple::arm64:
James Molloyfa403682014-04-30 10:11:40 +0000315 case llvm::Triple::arm64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000316 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000317 return ExprError();
318 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000319 case llvm::Triple::mips:
320 case llvm::Triple::mipsel:
321 case llvm::Triple::mips64:
322 case llvm::Triple::mips64el:
323 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
324 return ExprError();
325 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000326 case llvm::Triple::x86:
327 case llvm::Triple::x86_64:
328 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
329 return ExprError();
330 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000331 default:
332 break;
333 }
334 }
335
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000336 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000337}
338
Nate Begeman91e1fea2010-06-14 05:21:25 +0000339// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000340static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000341 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000342 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000343 switch (Type.getEltType()) {
344 case NeonTypeFlags::Int8:
345 case NeonTypeFlags::Poly8:
346 return shift ? 7 : (8 << IsQuad) - 1;
347 case NeonTypeFlags::Int16:
348 case NeonTypeFlags::Poly16:
349 return shift ? 15 : (4 << IsQuad) - 1;
350 case NeonTypeFlags::Int32:
351 return shift ? 31 : (2 << IsQuad) - 1;
352 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000353 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000354 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000355 case NeonTypeFlags::Poly128:
356 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000357 case NeonTypeFlags::Float16:
358 assert(!shift && "cannot shift float types!");
359 return (4 << IsQuad) - 1;
360 case NeonTypeFlags::Float32:
361 assert(!shift && "cannot shift float types!");
362 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000363 case NeonTypeFlags::Float64:
364 assert(!shift && "cannot shift float types!");
365 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000366 }
David Blaikie8a40f702012-01-17 06:56:22 +0000367 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000368}
369
Bob Wilsone4d77232011-11-08 05:04:11 +0000370/// getNeonEltType - Return the QualType corresponding to the elements of
371/// the vector type specified by the NeonTypeFlags. This is used to check
372/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000373static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000374 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000375 switch (Flags.getEltType()) {
376 case NeonTypeFlags::Int8:
377 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
378 case NeonTypeFlags::Int16:
379 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
380 case NeonTypeFlags::Int32:
381 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
382 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000383 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000384 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
385 else
386 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
387 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000388 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000389 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000390 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000391 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000392 case NeonTypeFlags::Poly64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000393 return Context.UnsignedLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000394 case NeonTypeFlags::Poly128:
395 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000396 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000397 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000398 case NeonTypeFlags::Float32:
399 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000400 case NeonTypeFlags::Float64:
401 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000402 }
David Blaikie8a40f702012-01-17 06:56:22 +0000403 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000404}
405
Tim Northover12670412014-02-19 10:37:05 +0000406bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000407 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000408 uint64_t mask = 0;
409 unsigned TV = 0;
410 int PtrArgNum = -1;
411 bool HasConstPtr = false;
412 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000413#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000414#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000415#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000416 }
417
418 // For NEON intrinsics which are overloaded on vector element type, validate
419 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000420 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000421 if (mask) {
422 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
423 return true;
424
425 TV = Result.getLimitedValue(64);
426 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
427 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000428 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000429 }
430
431 if (PtrArgNum >= 0) {
432 // Check that pointer arguments have the specified type.
433 Expr *Arg = TheCall->getArg(PtrArgNum);
434 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
435 Arg = ICE->getSubExpr();
436 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
437 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000438
Tim Northovera2ee4332014-03-29 15:09:45 +0000439 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
440 bool IsPolyUnsigned =
441 Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::arm64;
442 bool IsInt64Long =
443 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
444 QualType EltTy =
445 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000446 if (HasConstPtr)
447 EltTy = EltTy.withConst();
448 QualType LHSTy = Context.getPointerType(EltTy);
449 AssignConvertType ConvTy;
450 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
451 if (RHS.isInvalid())
452 return true;
453 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
454 RHS.get(), AA_Assigning))
455 return true;
456 }
457
458 // For NEON intrinsics which take an immediate value as part of the
459 // instruction, range check them here.
460 unsigned i = 0, l = 0, u = 0;
461 switch (BuiltinID) {
462 default:
463 return false;
Tim Northover12670412014-02-19 10:37:05 +0000464#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000465#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000466#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000467 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000468
Richard Sandiford28940af2014-04-16 08:47:51 +0000469 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000470}
471
Tim Northovera2ee4332014-03-29 15:09:45 +0000472bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
473 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000474 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000475 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000476 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
477 BuiltinID == AArch64::BI__builtin_arm_strex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000478 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000479 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000480 BuiltinID == AArch64::BI__builtin_arm_ldrex;
Tim Northover6aacd492013-07-16 09:47:53 +0000481
482 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
483
484 // Ensure that we have the proper number of arguments.
485 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
486 return true;
487
488 // Inspect the pointer argument of the atomic builtin. This should always be
489 // a pointer type, whose element is an integral scalar or pointer type.
490 // Because it is a pointer type, we don't have to worry about any implicit
491 // casts here.
492 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
493 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
494 if (PointerArgRes.isInvalid())
495 return true;
496 PointerArg = PointerArgRes.take();
497
498 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
499 if (!pointerType) {
500 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
501 << PointerArg->getType() << PointerArg->getSourceRange();
502 return true;
503 }
504
505 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
506 // task is to insert the appropriate casts into the AST. First work out just
507 // what the appropriate type is.
508 QualType ValType = pointerType->getPointeeType();
509 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
510 if (IsLdrex)
511 AddrType.addConst();
512
513 // Issue a warning if the cast is dodgy.
514 CastKind CastNeeded = CK_NoOp;
515 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
516 CastNeeded = CK_BitCast;
517 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
518 << PointerArg->getType()
519 << Context.getPointerType(AddrType)
520 << AA_Passing << PointerArg->getSourceRange();
521 }
522
523 // Finally, do the cast and replace the argument with the corrected version.
524 AddrType = Context.getPointerType(AddrType);
525 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
526 if (PointerArgRes.isInvalid())
527 return true;
528 PointerArg = PointerArgRes.take();
529
530 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
531
532 // In general, we allow ints, floats and pointers to be loaded and stored.
533 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
534 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
535 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
536 << PointerArg->getType() << PointerArg->getSourceRange();
537 return true;
538 }
539
540 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000541 if (Context.getTypeSize(ValType) > MaxWidth) {
542 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000543 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) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000588 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000589 }
590
Tim Northover12670412014-02-19 10:37:05 +0000591 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
592 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000593
Bob Wilsond836d3d2014-03-09 23:02:27 +0000594 // For NEON intrinsics which take an immediate value as part of the
Nate Begemand773fe62010-06-13 04:47:52 +0000595 // 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;
Richard Sandiford28940af2014-04-16 08:47:51 +0000605 }
Nate Begemand773fe62010-06-13 04:47:52 +0000606
Nate Begemanf568b072010-08-03 21:32:34 +0000607 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000608 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000609}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000610
Tim Northover573cbee2014-05-24 12:52:07 +0000611bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000612 CallExpr *TheCall) {
613 llvm::APSInt Result;
614
Tim Northover573cbee2014-05-24 12:52:07 +0000615 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
616 BuiltinID == AArch64::BI__builtin_arm_strex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000617 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
618 }
619
620 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
621 return true;
622
623 return false;
624}
625
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;
Richard Sandiford28940af2014-04-16 08:47:51 +0000637 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000638
Richard Sandiford28940af2014-04-16 08:47:51 +0000639 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000640}
641
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000642bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
643 switch (BuiltinID) {
644 case X86::BI_mm_prefetch:
Richard Sandiford28940af2014-04-16 08:47:51 +0000645 // This is declared to take (const char*, int)
646 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000647 }
648 return false;
649}
650
Richard Smith55ce3522012-06-25 20:30:08 +0000651/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
652/// parameter with the FormatAttr's correct format_idx and firstDataArg.
653/// Returns true when the format fits the function and the FormatStringInfo has
654/// been populated.
655bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
656 FormatStringInfo *FSI) {
657 FSI->HasVAListArg = Format->getFirstArg() == 0;
658 FSI->FormatIdx = Format->getFormatIdx() - 1;
659 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000660
Richard Smith55ce3522012-06-25 20:30:08 +0000661 // The way the format attribute works in GCC, the implicit this argument
662 // of member functions is counted. However, it doesn't appear in our own
663 // lists, so decrement format_idx in that case.
664 if (IsCXXMember) {
665 if(FSI->FormatIdx == 0)
666 return false;
667 --FSI->FormatIdx;
668 if (FSI->FirstDataArg != 0)
669 --FSI->FirstDataArg;
670 }
671 return true;
672}
Mike Stump11289f42009-09-09 15:08:12 +0000673
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000674/// Checks if a the given expression evaluates to null.
675///
676/// \brief Returns true if the value evaluates to null.
677static bool CheckNonNullExpr(Sema &S,
678 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000679 // As a special case, transparent unions initialized with zero are
680 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000681 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000682 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
683 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000684 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000685 if (const InitListExpr *ILE =
686 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000687 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000688 }
689
690 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000691 return (!Expr->isValueDependent() &&
692 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
693 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000694}
695
696static void CheckNonNullArgument(Sema &S,
697 const Expr *ArgExpr,
698 SourceLocation CallSiteLoc) {
699 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000700 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
701}
702
Ted Kremenek2bc73332014-01-17 06:24:43 +0000703static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +0000704 const NamedDecl *FDecl,
Ted Kremenek2bc73332014-01-17 06:24:43 +0000705 const Expr * const *ExprArgs,
706 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000707 // Check the attributes attached to the method/function itself.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000708 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000709 for (const auto &Val : NonNull->args())
710 CheckNonNullArgument(S, ExprArgs[Val], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +0000711 }
Ted Kremenek9aedc152014-01-17 06:24:56 +0000712
713 // Check the attributes on the parameters.
714 ArrayRef<ParmVarDecl*> parms;
715 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
716 parms = FD->parameters();
717 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
718 parms = MD->parameters();
719
720 unsigned argIndex = 0;
721 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
722 I != E; ++I, ++argIndex) {
723 const ParmVarDecl *PVD = *I;
724 if (PVD->hasAttr<NonNullAttr>())
725 CheckNonNullArgument(S, ExprArgs[argIndex], CallSiteLoc);
726 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000727}
728
Richard Smith55ce3522012-06-25 20:30:08 +0000729/// Handles the checks for format strings, non-POD arguments to vararg
730/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000731void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
732 unsigned NumParams, bool IsMemberFunction,
733 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +0000734 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +0000735 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +0000736 if (CurContext->isDependentContext())
737 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000738
Ted Kremenekb8176da2010-09-09 04:33:05 +0000739 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +0000740 llvm::SmallBitVector CheckedVarArgs;
741 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000742 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000743 // Only create vector if there are format attributes.
744 CheckedVarArgs.resize(Args.size());
745
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000746 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000747 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000748 }
Richard Smithd7293d72013-08-05 18:49:43 +0000749 }
Richard Smith55ce3522012-06-25 20:30:08 +0000750
751 // Refuse POD arguments that weren't caught by the format string
752 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +0000753 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000754 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000755 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +0000756 if (const Expr *Arg = Args[ArgIdx]) {
757 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
758 checkVariadicArgument(Arg, CallType);
759 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000760 }
Richard Smithd7293d72013-08-05 18:49:43 +0000761 }
Mike Stump11289f42009-09-09 15:08:12 +0000762
Richard Trieu41bc0992013-06-22 00:20:41 +0000763 if (FDecl) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000764 CheckNonNullArguments(*this, FDecl, Args.data(), Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000765
Richard Trieu41bc0992013-06-22 00:20:41 +0000766 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000767 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
768 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000769 }
Richard Smith55ce3522012-06-25 20:30:08 +0000770}
771
772/// CheckConstructorCall - Check a constructor call for correctness and safety
773/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000774void Sema::CheckConstructorCall(FunctionDecl *FDecl,
775 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +0000776 const FunctionProtoType *Proto,
777 SourceLocation Loc) {
778 VariadicCallType CallType =
779 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +0000780 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +0000781 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
782}
783
784/// CheckFunctionCall - Check a direct function call for various correctness
785/// and safety properties not strictly enforced by the C type system.
786bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
787 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000788 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
789 isa<CXXMethodDecl>(FDecl);
790 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
791 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +0000792 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
793 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000794 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +0000795 Expr** Args = TheCall->getArgs();
796 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +0000797 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000798 // If this is a call to a member operator, hide the first argument
799 // from checkCall.
800 // FIXME: Our choice of AST representation here is less than ideal.
801 ++Args;
802 --NumArgs;
803 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000804 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +0000805 IsMemberFunction, TheCall->getRParenLoc(),
806 TheCall->getCallee()->getSourceRange(), CallType);
807
808 IdentifierInfo *FnInfo = FDecl->getIdentifier();
809 // None of the checks below are needed for functions that don't have
810 // simple names (e.g., C++ conversion functions).
811 if (!FnInfo)
812 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000813
Richard Trieu7eb0b2c2014-02-26 01:17:28 +0000814 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
815
Anna Zaks22122702012-01-17 00:37:07 +0000816 unsigned CMId = FDecl->getMemoryFunctionKind();
817 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +0000818 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +0000819
Anna Zaks201d4892012-01-13 21:52:01 +0000820 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +0000821 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +0000822 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +0000823 else if (CMId == Builtin::BIstrncat)
824 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +0000825 else
Anna Zaks22122702012-01-17 00:37:07 +0000826 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +0000827
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000828 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000829}
830
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000831bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000832 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +0000833 VariadicCallType CallType =
834 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000835
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000836 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +0000837 /*IsMemberFunction=*/false,
838 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000839
840 return false;
841}
842
Richard Trieu664c4c62013-06-20 21:03:13 +0000843bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
844 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000845 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
846 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000847 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000848
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000849 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +0000850 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000851 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000852
Richard Trieu664c4c62013-06-20 21:03:13 +0000853 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +0000854 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +0000855 CallType = VariadicDoesNotApply;
856 } else if (Ty->isBlockPointerType()) {
857 CallType = VariadicBlock;
858 } else { // Ty->isFunctionPointerType()
859 CallType = VariadicFunction;
860 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000861 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000862
Alp Toker9cacbab2014-01-20 20:26:09 +0000863 checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
864 TheCall->getNumArgs()),
865 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +0000866 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +0000867
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000868 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000869}
870
Richard Trieu41bc0992013-06-22 00:20:41 +0000871/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
872/// such as function pointers returned from functions.
873bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
874 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
875 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000876 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +0000877
Alp Toker9cacbab2014-01-20 20:26:09 +0000878 checkCall(/*FDecl=*/0, llvm::makeArrayRef<const Expr *>(
879 TheCall->getArgs(), TheCall->getNumArgs()),
880 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +0000881 TheCall->getCallee()->getSourceRange(), CallType);
882
883 return false;
884}
885
Tim Northovere94a34c2014-03-11 10:49:14 +0000886static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
887 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
888 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
889 return false;
890
891 switch (Op) {
892 case AtomicExpr::AO__c11_atomic_init:
893 llvm_unreachable("There is no ordering argument for an init");
894
895 case AtomicExpr::AO__c11_atomic_load:
896 case AtomicExpr::AO__atomic_load_n:
897 case AtomicExpr::AO__atomic_load:
898 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
899 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
900
901 case AtomicExpr::AO__c11_atomic_store:
902 case AtomicExpr::AO__atomic_store:
903 case AtomicExpr::AO__atomic_store_n:
904 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
905 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
906 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
907
908 default:
909 return true;
910 }
911}
912
Richard Smithfeea8832012-04-12 05:08:17 +0000913ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
914 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000915 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
916 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000917
Richard Smithfeea8832012-04-12 05:08:17 +0000918 // All these operations take one of the following forms:
919 enum {
920 // C __c11_atomic_init(A *, C)
921 Init,
922 // C __c11_atomic_load(A *, int)
923 Load,
924 // void __atomic_load(A *, CP, int)
925 Copy,
926 // C __c11_atomic_add(A *, M, int)
927 Arithmetic,
928 // C __atomic_exchange_n(A *, CP, int)
929 Xchg,
930 // void __atomic_exchange(A *, C *, CP, int)
931 GNUXchg,
932 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
933 C11CmpXchg,
934 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
935 GNUCmpXchg
936 } Form = Init;
937 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
938 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
939 // where:
940 // C is an appropriate type,
941 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
942 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
943 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
944 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000945
Richard Smithfeea8832012-04-12 05:08:17 +0000946 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
947 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
948 && "need to update code for modified C11 atomics");
949 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
950 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
951 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
952 Op == AtomicExpr::AO__atomic_store_n ||
953 Op == AtomicExpr::AO__atomic_exchange_n ||
954 Op == AtomicExpr::AO__atomic_compare_exchange_n;
955 bool IsAddSub = false;
956
957 switch (Op) {
958 case AtomicExpr::AO__c11_atomic_init:
959 Form = Init;
960 break;
961
962 case AtomicExpr::AO__c11_atomic_load:
963 case AtomicExpr::AO__atomic_load_n:
964 Form = Load;
965 break;
966
967 case AtomicExpr::AO__c11_atomic_store:
968 case AtomicExpr::AO__atomic_load:
969 case AtomicExpr::AO__atomic_store:
970 case AtomicExpr::AO__atomic_store_n:
971 Form = Copy;
972 break;
973
974 case AtomicExpr::AO__c11_atomic_fetch_add:
975 case AtomicExpr::AO__c11_atomic_fetch_sub:
976 case AtomicExpr::AO__atomic_fetch_add:
977 case AtomicExpr::AO__atomic_fetch_sub:
978 case AtomicExpr::AO__atomic_add_fetch:
979 case AtomicExpr::AO__atomic_sub_fetch:
980 IsAddSub = true;
981 // Fall through.
982 case AtomicExpr::AO__c11_atomic_fetch_and:
983 case AtomicExpr::AO__c11_atomic_fetch_or:
984 case AtomicExpr::AO__c11_atomic_fetch_xor:
985 case AtomicExpr::AO__atomic_fetch_and:
986 case AtomicExpr::AO__atomic_fetch_or:
987 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +0000988 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +0000989 case AtomicExpr::AO__atomic_and_fetch:
990 case AtomicExpr::AO__atomic_or_fetch:
991 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +0000992 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +0000993 Form = Arithmetic;
994 break;
995
996 case AtomicExpr::AO__c11_atomic_exchange:
997 case AtomicExpr::AO__atomic_exchange_n:
998 Form = Xchg;
999 break;
1000
1001 case AtomicExpr::AO__atomic_exchange:
1002 Form = GNUXchg;
1003 break;
1004
1005 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1006 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1007 Form = C11CmpXchg;
1008 break;
1009
1010 case AtomicExpr::AO__atomic_compare_exchange:
1011 case AtomicExpr::AO__atomic_compare_exchange_n:
1012 Form = GNUCmpXchg;
1013 break;
1014 }
1015
1016 // Check we have the right number of arguments.
1017 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001018 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001019 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001020 << TheCall->getCallee()->getSourceRange();
1021 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001022 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1023 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001024 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001025 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001026 << TheCall->getCallee()->getSourceRange();
1027 return ExprError();
1028 }
1029
Richard Smithfeea8832012-04-12 05:08:17 +00001030 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001031 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001032 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1033 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1034 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001035 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001036 << Ptr->getType() << Ptr->getSourceRange();
1037 return ExprError();
1038 }
1039
Richard Smithfeea8832012-04-12 05:08:17 +00001040 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1041 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1042 QualType ValType = AtomTy; // 'C'
1043 if (IsC11) {
1044 if (!AtomTy->isAtomicType()) {
1045 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1046 << Ptr->getType() << Ptr->getSourceRange();
1047 return ExprError();
1048 }
Richard Smithe00921a2012-09-15 06:09:58 +00001049 if (AtomTy.isConstQualified()) {
1050 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1051 << Ptr->getType() << Ptr->getSourceRange();
1052 return ExprError();
1053 }
Richard Smithfeea8832012-04-12 05:08:17 +00001054 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001055 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001056
Richard Smithfeea8832012-04-12 05:08:17 +00001057 // For an arithmetic operation, the implied arithmetic must be well-formed.
1058 if (Form == Arithmetic) {
1059 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1060 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1061 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1062 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1063 return ExprError();
1064 }
1065 if (!IsAddSub && !ValType->isIntegerType()) {
1066 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1067 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1068 return ExprError();
1069 }
1070 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1071 // For __atomic_*_n operations, the value type must be a scalar integral or
1072 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001073 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001074 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1075 return ExprError();
1076 }
1077
Eli Friedmanaa769812013-09-11 03:49:34 +00001078 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1079 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001080 // For GNU atomics, require a trivially-copyable type. This is not part of
1081 // the GNU atomics specification, but we enforce it for sanity.
1082 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001083 << Ptr->getType() << Ptr->getSourceRange();
1084 return ExprError();
1085 }
1086
Richard Smithfeea8832012-04-12 05:08:17 +00001087 // FIXME: For any builtin other than a load, the ValType must not be
1088 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001089
1090 switch (ValType.getObjCLifetime()) {
1091 case Qualifiers::OCL_None:
1092 case Qualifiers::OCL_ExplicitNone:
1093 // okay
1094 break;
1095
1096 case Qualifiers::OCL_Weak:
1097 case Qualifiers::OCL_Strong:
1098 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001099 // FIXME: Can this happen? By this point, ValType should be known
1100 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001101 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1102 << ValType << Ptr->getSourceRange();
1103 return ExprError();
1104 }
1105
1106 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001107 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001108 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001109 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001110 ResultType = Context.BoolTy;
1111
Richard Smithfeea8832012-04-12 05:08:17 +00001112 // The type of a parameter passed 'by value'. In the GNU atomics, such
1113 // arguments are actually passed as pointers.
1114 QualType ByValType = ValType; // 'CP'
1115 if (!IsC11 && !IsN)
1116 ByValType = Ptr->getType();
1117
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001118 // The first argument --- the pointer --- has a fixed type; we
1119 // deduce the types of the rest of the arguments accordingly. Walk
1120 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001121 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001122 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001123 if (i < NumVals[Form] + 1) {
1124 switch (i) {
1125 case 1:
1126 // The second argument is the non-atomic operand. For arithmetic, this
1127 // is always passed by value, and for a compare_exchange it is always
1128 // passed by address. For the rest, GNU uses by-address and C11 uses
1129 // by-value.
1130 assert(Form != Load);
1131 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1132 Ty = ValType;
1133 else if (Form == Copy || Form == Xchg)
1134 Ty = ByValType;
1135 else if (Form == Arithmetic)
1136 Ty = Context.getPointerDiffType();
1137 else
1138 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1139 break;
1140 case 2:
1141 // The third argument to compare_exchange / GNU exchange is a
1142 // (pointer to a) desired value.
1143 Ty = ByValType;
1144 break;
1145 case 3:
1146 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1147 Ty = Context.BoolTy;
1148 break;
1149 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001150 } else {
1151 // The order(s) are always converted to int.
1152 Ty = Context.IntTy;
1153 }
Richard Smithfeea8832012-04-12 05:08:17 +00001154
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001155 InitializedEntity Entity =
1156 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001157 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001158 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1159 if (Arg.isInvalid())
1160 return true;
1161 TheCall->setArg(i, Arg.get());
1162 }
1163
Richard Smithfeea8832012-04-12 05:08:17 +00001164 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001165 SmallVector<Expr*, 5> SubExprs;
1166 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001167 switch (Form) {
1168 case Init:
1169 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001170 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001171 break;
1172 case Load:
1173 SubExprs.push_back(TheCall->getArg(1)); // Order
1174 break;
1175 case Copy:
1176 case Arithmetic:
1177 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001178 SubExprs.push_back(TheCall->getArg(2)); // Order
1179 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001180 break;
1181 case GNUXchg:
1182 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1183 SubExprs.push_back(TheCall->getArg(3)); // Order
1184 SubExprs.push_back(TheCall->getArg(1)); // Val1
1185 SubExprs.push_back(TheCall->getArg(2)); // Val2
1186 break;
1187 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001188 SubExprs.push_back(TheCall->getArg(3)); // Order
1189 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001190 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001191 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001192 break;
1193 case GNUCmpXchg:
1194 SubExprs.push_back(TheCall->getArg(4)); // Order
1195 SubExprs.push_back(TheCall->getArg(1)); // Val1
1196 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1197 SubExprs.push_back(TheCall->getArg(2)); // Val2
1198 SubExprs.push_back(TheCall->getArg(3)); // Weak
1199 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001200 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001201
1202 if (SubExprs.size() >= 2 && Form != Init) {
1203 llvm::APSInt Result(32);
1204 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1205 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001206 Diag(SubExprs[1]->getLocStart(),
1207 diag::warn_atomic_op_has_invalid_memory_order)
1208 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001209 }
1210
Fariborz Jahanian615de762013-05-28 17:37:39 +00001211 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1212 SubExprs, ResultType, Op,
1213 TheCall->getRParenLoc());
1214
1215 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1216 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1217 Context.AtomicUsesUnsupportedLibcall(AE))
1218 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1219 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001220
Fariborz Jahanian615de762013-05-28 17:37:39 +00001221 return Owned(AE);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001222}
1223
1224
John McCall29ad95b2011-08-27 01:09:30 +00001225/// checkBuiltinArgument - Given a call to a builtin function, perform
1226/// normal type-checking on the given argument, updating the call in
1227/// place. This is useful when a builtin function requires custom
1228/// type-checking for some of its arguments but not necessarily all of
1229/// them.
1230///
1231/// Returns true on error.
1232static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1233 FunctionDecl *Fn = E->getDirectCallee();
1234 assert(Fn && "builtin call without direct callee!");
1235
1236 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1237 InitializedEntity Entity =
1238 InitializedEntity::InitializeParameter(S.Context, Param);
1239
1240 ExprResult Arg = E->getArg(0);
1241 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1242 if (Arg.isInvalid())
1243 return true;
1244
1245 E->setArg(ArgIndex, Arg.take());
1246 return false;
1247}
1248
Chris Lattnerdc046542009-05-08 06:58:22 +00001249/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1250/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1251/// type of its first argument. The main ActOnCallExpr routines have already
1252/// promoted the types of arguments because all of these calls are prototyped as
1253/// void(...).
1254///
1255/// This function goes through and does final semantic checking for these
1256/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001257ExprResult
1258Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001259 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001260 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1261 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1262
1263 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001264 if (TheCall->getNumArgs() < 1) {
1265 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1266 << 0 << 1 << TheCall->getNumArgs()
1267 << TheCall->getCallee()->getSourceRange();
1268 return ExprError();
1269 }
Mike Stump11289f42009-09-09 15:08:12 +00001270
Chris Lattnerdc046542009-05-08 06:58:22 +00001271 // Inspect the first argument of the atomic builtin. This should always be
1272 // a pointer type, whose element is an integral scalar or pointer type.
1273 // Because it is a pointer type, we don't have to worry about any implicit
1274 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001275 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001276 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001277 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1278 if (FirstArgResult.isInvalid())
1279 return ExprError();
1280 FirstArg = FirstArgResult.take();
1281 TheCall->setArg(0, FirstArg);
1282
John McCall31168b02011-06-15 23:02:42 +00001283 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1284 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001285 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1286 << FirstArg->getType() << FirstArg->getSourceRange();
1287 return ExprError();
1288 }
Mike Stump11289f42009-09-09 15:08:12 +00001289
John McCall31168b02011-06-15 23:02:42 +00001290 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001291 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001292 !ValType->isBlockPointerType()) {
1293 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1294 << FirstArg->getType() << FirstArg->getSourceRange();
1295 return ExprError();
1296 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001297
John McCall31168b02011-06-15 23:02:42 +00001298 switch (ValType.getObjCLifetime()) {
1299 case Qualifiers::OCL_None:
1300 case Qualifiers::OCL_ExplicitNone:
1301 // okay
1302 break;
1303
1304 case Qualifiers::OCL_Weak:
1305 case Qualifiers::OCL_Strong:
1306 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001307 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001308 << ValType << FirstArg->getSourceRange();
1309 return ExprError();
1310 }
1311
John McCallb50451a2011-10-05 07:41:44 +00001312 // Strip any qualifiers off ValType.
1313 ValType = ValType.getUnqualifiedType();
1314
Chandler Carruth3973af72010-07-18 20:54:12 +00001315 // The majority of builtins return a value, but a few have special return
1316 // types, so allow them to override appropriately below.
1317 QualType ResultType = ValType;
1318
Chris Lattnerdc046542009-05-08 06:58:22 +00001319 // We need to figure out which concrete builtin this maps onto. For example,
1320 // __sync_fetch_and_add with a 2 byte object turns into
1321 // __sync_fetch_and_add_2.
1322#define BUILTIN_ROW(x) \
1323 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1324 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001325
Chris Lattnerdc046542009-05-08 06:58:22 +00001326 static const unsigned BuiltinIndices[][5] = {
1327 BUILTIN_ROW(__sync_fetch_and_add),
1328 BUILTIN_ROW(__sync_fetch_and_sub),
1329 BUILTIN_ROW(__sync_fetch_and_or),
1330 BUILTIN_ROW(__sync_fetch_and_and),
1331 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +00001332
Chris Lattnerdc046542009-05-08 06:58:22 +00001333 BUILTIN_ROW(__sync_add_and_fetch),
1334 BUILTIN_ROW(__sync_sub_and_fetch),
1335 BUILTIN_ROW(__sync_and_and_fetch),
1336 BUILTIN_ROW(__sync_or_and_fetch),
1337 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001338
Chris Lattnerdc046542009-05-08 06:58:22 +00001339 BUILTIN_ROW(__sync_val_compare_and_swap),
1340 BUILTIN_ROW(__sync_bool_compare_and_swap),
1341 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001342 BUILTIN_ROW(__sync_lock_release),
1343 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001344 };
Mike Stump11289f42009-09-09 15:08:12 +00001345#undef BUILTIN_ROW
1346
Chris Lattnerdc046542009-05-08 06:58:22 +00001347 // Determine the index of the size.
1348 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001349 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001350 case 1: SizeIndex = 0; break;
1351 case 2: SizeIndex = 1; break;
1352 case 4: SizeIndex = 2; break;
1353 case 8: SizeIndex = 3; break;
1354 case 16: SizeIndex = 4; break;
1355 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001356 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1357 << FirstArg->getType() << FirstArg->getSourceRange();
1358 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001359 }
Mike Stump11289f42009-09-09 15:08:12 +00001360
Chris Lattnerdc046542009-05-08 06:58:22 +00001361 // Each of these builtins has one pointer argument, followed by some number of
1362 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1363 // that we ignore. Find out which row of BuiltinIndices to read from as well
1364 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001365 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001366 unsigned BuiltinIndex, NumFixed = 1;
1367 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001368 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001369 case Builtin::BI__sync_fetch_and_add:
1370 case Builtin::BI__sync_fetch_and_add_1:
1371 case Builtin::BI__sync_fetch_and_add_2:
1372 case Builtin::BI__sync_fetch_and_add_4:
1373 case Builtin::BI__sync_fetch_and_add_8:
1374 case Builtin::BI__sync_fetch_and_add_16:
1375 BuiltinIndex = 0;
1376 break;
1377
1378 case Builtin::BI__sync_fetch_and_sub:
1379 case Builtin::BI__sync_fetch_and_sub_1:
1380 case Builtin::BI__sync_fetch_and_sub_2:
1381 case Builtin::BI__sync_fetch_and_sub_4:
1382 case Builtin::BI__sync_fetch_and_sub_8:
1383 case Builtin::BI__sync_fetch_and_sub_16:
1384 BuiltinIndex = 1;
1385 break;
1386
1387 case Builtin::BI__sync_fetch_and_or:
1388 case Builtin::BI__sync_fetch_and_or_1:
1389 case Builtin::BI__sync_fetch_and_or_2:
1390 case Builtin::BI__sync_fetch_and_or_4:
1391 case Builtin::BI__sync_fetch_and_or_8:
1392 case Builtin::BI__sync_fetch_and_or_16:
1393 BuiltinIndex = 2;
1394 break;
1395
1396 case Builtin::BI__sync_fetch_and_and:
1397 case Builtin::BI__sync_fetch_and_and_1:
1398 case Builtin::BI__sync_fetch_and_and_2:
1399 case Builtin::BI__sync_fetch_and_and_4:
1400 case Builtin::BI__sync_fetch_and_and_8:
1401 case Builtin::BI__sync_fetch_and_and_16:
1402 BuiltinIndex = 3;
1403 break;
Mike Stump11289f42009-09-09 15:08:12 +00001404
Douglas Gregor73722482011-11-28 16:30:08 +00001405 case Builtin::BI__sync_fetch_and_xor:
1406 case Builtin::BI__sync_fetch_and_xor_1:
1407 case Builtin::BI__sync_fetch_and_xor_2:
1408 case Builtin::BI__sync_fetch_and_xor_4:
1409 case Builtin::BI__sync_fetch_and_xor_8:
1410 case Builtin::BI__sync_fetch_and_xor_16:
1411 BuiltinIndex = 4;
1412 break;
1413
1414 case Builtin::BI__sync_add_and_fetch:
1415 case Builtin::BI__sync_add_and_fetch_1:
1416 case Builtin::BI__sync_add_and_fetch_2:
1417 case Builtin::BI__sync_add_and_fetch_4:
1418 case Builtin::BI__sync_add_and_fetch_8:
1419 case Builtin::BI__sync_add_and_fetch_16:
1420 BuiltinIndex = 5;
1421 break;
1422
1423 case Builtin::BI__sync_sub_and_fetch:
1424 case Builtin::BI__sync_sub_and_fetch_1:
1425 case Builtin::BI__sync_sub_and_fetch_2:
1426 case Builtin::BI__sync_sub_and_fetch_4:
1427 case Builtin::BI__sync_sub_and_fetch_8:
1428 case Builtin::BI__sync_sub_and_fetch_16:
1429 BuiltinIndex = 6;
1430 break;
1431
1432 case Builtin::BI__sync_and_and_fetch:
1433 case Builtin::BI__sync_and_and_fetch_1:
1434 case Builtin::BI__sync_and_and_fetch_2:
1435 case Builtin::BI__sync_and_and_fetch_4:
1436 case Builtin::BI__sync_and_and_fetch_8:
1437 case Builtin::BI__sync_and_and_fetch_16:
1438 BuiltinIndex = 7;
1439 break;
1440
1441 case Builtin::BI__sync_or_and_fetch:
1442 case Builtin::BI__sync_or_and_fetch_1:
1443 case Builtin::BI__sync_or_and_fetch_2:
1444 case Builtin::BI__sync_or_and_fetch_4:
1445 case Builtin::BI__sync_or_and_fetch_8:
1446 case Builtin::BI__sync_or_and_fetch_16:
1447 BuiltinIndex = 8;
1448 break;
1449
1450 case Builtin::BI__sync_xor_and_fetch:
1451 case Builtin::BI__sync_xor_and_fetch_1:
1452 case Builtin::BI__sync_xor_and_fetch_2:
1453 case Builtin::BI__sync_xor_and_fetch_4:
1454 case Builtin::BI__sync_xor_and_fetch_8:
1455 case Builtin::BI__sync_xor_and_fetch_16:
1456 BuiltinIndex = 9;
1457 break;
Mike Stump11289f42009-09-09 15:08:12 +00001458
Chris Lattnerdc046542009-05-08 06:58:22 +00001459 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001460 case Builtin::BI__sync_val_compare_and_swap_1:
1461 case Builtin::BI__sync_val_compare_and_swap_2:
1462 case Builtin::BI__sync_val_compare_and_swap_4:
1463 case Builtin::BI__sync_val_compare_and_swap_8:
1464 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001465 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +00001466 NumFixed = 2;
1467 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001468
Chris Lattnerdc046542009-05-08 06:58:22 +00001469 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001470 case Builtin::BI__sync_bool_compare_and_swap_1:
1471 case Builtin::BI__sync_bool_compare_and_swap_2:
1472 case Builtin::BI__sync_bool_compare_and_swap_4:
1473 case Builtin::BI__sync_bool_compare_and_swap_8:
1474 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001475 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +00001476 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001477 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001478 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001479
1480 case Builtin::BI__sync_lock_test_and_set:
1481 case Builtin::BI__sync_lock_test_and_set_1:
1482 case Builtin::BI__sync_lock_test_and_set_2:
1483 case Builtin::BI__sync_lock_test_and_set_4:
1484 case Builtin::BI__sync_lock_test_and_set_8:
1485 case Builtin::BI__sync_lock_test_and_set_16:
1486 BuiltinIndex = 12;
1487 break;
1488
Chris Lattnerdc046542009-05-08 06:58:22 +00001489 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001490 case Builtin::BI__sync_lock_release_1:
1491 case Builtin::BI__sync_lock_release_2:
1492 case Builtin::BI__sync_lock_release_4:
1493 case Builtin::BI__sync_lock_release_8:
1494 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001495 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001496 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001497 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001498 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001499
1500 case Builtin::BI__sync_swap:
1501 case Builtin::BI__sync_swap_1:
1502 case Builtin::BI__sync_swap_2:
1503 case Builtin::BI__sync_swap_4:
1504 case Builtin::BI__sync_swap_8:
1505 case Builtin::BI__sync_swap_16:
1506 BuiltinIndex = 14;
1507 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001508 }
Mike Stump11289f42009-09-09 15:08:12 +00001509
Chris Lattnerdc046542009-05-08 06:58:22 +00001510 // Now that we know how many fixed arguments we expect, first check that we
1511 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001512 if (TheCall->getNumArgs() < 1+NumFixed) {
1513 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1514 << 0 << 1+NumFixed << TheCall->getNumArgs()
1515 << TheCall->getCallee()->getSourceRange();
1516 return ExprError();
1517 }
Mike Stump11289f42009-09-09 15:08:12 +00001518
Chris Lattner5b9241b2009-05-08 15:36:58 +00001519 // Get the decl for the concrete builtin from this, we can tell what the
1520 // concrete integer type we should convert to is.
1521 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1522 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001523 FunctionDecl *NewBuiltinDecl;
1524 if (NewBuiltinID == BuiltinID)
1525 NewBuiltinDecl = FDecl;
1526 else {
1527 // Perform builtin lookup to avoid redeclaring it.
1528 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1529 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1530 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1531 assert(Res.getFoundDecl());
1532 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1533 if (NewBuiltinDecl == 0)
1534 return ExprError();
1535 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001536
John McCallcf142162010-08-07 06:22:56 +00001537 // The first argument --- the pointer --- has a fixed type; we
1538 // deduce the types of the rest of the arguments accordingly. Walk
1539 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001540 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001541 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001542
Chris Lattnerdc046542009-05-08 06:58:22 +00001543 // GCC does an implicit conversion to the pointer or integer ValType. This
1544 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001545 // Initialize the argument.
1546 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1547 ValType, /*consume*/ false);
1548 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001549 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001550 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001551
Chris Lattnerdc046542009-05-08 06:58:22 +00001552 // Okay, we have something that *can* be converted to the right type. Check
1553 // to see if there is a potentially weird extension going on here. This can
1554 // happen when you do an atomic operation on something like an char* and
1555 // pass in 42. The 42 gets converted to char. This is even more strange
1556 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001557 // FIXME: Do this check.
John McCallb50451a2011-10-05 07:41:44 +00001558 TheCall->setArg(i+1, Arg.take());
Chris Lattnerdc046542009-05-08 06:58:22 +00001559 }
Mike Stump11289f42009-09-09 15:08:12 +00001560
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001561 ASTContext& Context = this->getASTContext();
1562
1563 // Create a new DeclRefExpr to refer to the new decl.
1564 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1565 Context,
1566 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001567 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001568 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001569 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001570 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001571 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001572 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001573
Chris Lattnerdc046542009-05-08 06:58:22 +00001574 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001575 // FIXME: This loses syntactic information.
1576 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1577 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1578 CK_BuiltinFnToFnPtr);
John Wiegley01296292011-04-08 18:41:53 +00001579 TheCall->setCallee(PromotedCall.take());
Mike Stump11289f42009-09-09 15:08:12 +00001580
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001581 // Change the result type of the call to match the original value type. This
1582 // is arbitrary, but the codegen for these builtins ins design to handle it
1583 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001584 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001585
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001586 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001587}
1588
Chris Lattner6436fb62009-02-18 06:01:06 +00001589/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001590/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001591/// Note: It might also make sense to do the UTF-16 conversion here (would
1592/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001593bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001594 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001595 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1596
Douglas Gregorfb65e592011-07-27 05:40:30 +00001597 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001598 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1599 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001600 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001601 }
Mike Stump11289f42009-09-09 15:08:12 +00001602
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001603 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001604 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001605 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001606 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001607 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001608 UTF16 *ToPtr = &ToBuf[0];
1609
1610 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1611 &ToPtr, ToPtr + NumBytes,
1612 strictConversion);
1613 // Check for conversion failure.
1614 if (Result != conversionOK)
1615 Diag(Arg->getLocStart(),
1616 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1617 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001618 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001619}
1620
Chris Lattnere202e6a2007-12-20 00:05:45 +00001621/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1622/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001623bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1624 Expr *Fn = TheCall->getCallee();
1625 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001626 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001627 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001628 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1629 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001630 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001631 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001632 return true;
1633 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001634
1635 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001636 return Diag(TheCall->getLocEnd(),
1637 diag::err_typecheck_call_too_few_args_at_least)
1638 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001639 }
1640
John McCall29ad95b2011-08-27 01:09:30 +00001641 // Type-check the first argument normally.
1642 if (checkBuiltinArgument(*this, TheCall, 0))
1643 return true;
1644
Chris Lattnere202e6a2007-12-20 00:05:45 +00001645 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001646 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001647 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001648 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001649 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001650 else if (FunctionDecl *FD = getCurFunctionDecl())
1651 isVariadic = FD->isVariadic();
1652 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001653 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001654
Chris Lattnere202e6a2007-12-20 00:05:45 +00001655 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001656 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1657 return true;
1658 }
Mike Stump11289f42009-09-09 15:08:12 +00001659
Chris Lattner43be2e62007-12-19 23:59:04 +00001660 // Verify that the second argument to the builtin is the last argument of the
1661 // current function or method.
1662 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001663 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001664
Nico Weber9eea7642013-05-24 23:31:57 +00001665 // These are valid if SecondArgIsLastNamedArgument is false after the next
1666 // block.
1667 QualType Type;
1668 SourceLocation ParamLoc;
1669
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001670 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1671 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001672 // FIXME: This isn't correct for methods (results in bogus warning).
1673 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001674 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001675 if (CurBlock)
1676 LastArg = *(CurBlock->TheDecl->param_end()-1);
1677 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001678 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001679 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001680 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001681 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00001682
1683 Type = PV->getType();
1684 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00001685 }
1686 }
Mike Stump11289f42009-09-09 15:08:12 +00001687
Chris Lattner43be2e62007-12-19 23:59:04 +00001688 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001689 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001690 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00001691 else if (Type->isReferenceType()) {
1692 Diag(Arg->getLocStart(),
1693 diag::warn_va_start_of_reference_type_is_undefined);
1694 Diag(ParamLoc, diag::note_parameter_type) << Type;
1695 }
1696
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00001697 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00001698 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001699}
Chris Lattner43be2e62007-12-19 23:59:04 +00001700
Chris Lattner2da14fb2007-12-20 00:26:33 +00001701/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1702/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001703bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1704 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001705 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001706 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001707 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001708 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001709 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001710 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001711 << SourceRange(TheCall->getArg(2)->getLocStart(),
1712 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001713
John Wiegley01296292011-04-08 18:41:53 +00001714 ExprResult OrigArg0 = TheCall->getArg(0);
1715 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001716
Chris Lattner2da14fb2007-12-20 00:26:33 +00001717 // Do standard promotions between the two arguments, returning their common
1718 // type.
Chris Lattner08464942007-12-28 05:29:59 +00001719 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00001720 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1721 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00001722
1723 // Make sure any conversions are pushed back into the call; this is
1724 // type safe since unordered compare builtins are declared as "_Bool
1725 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00001726 TheCall->setArg(0, OrigArg0.get());
1727 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00001728
John Wiegley01296292011-04-08 18:41:53 +00001729 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00001730 return false;
1731
Chris Lattner2da14fb2007-12-20 00:26:33 +00001732 // If the common type isn't a real floating type, then the arguments were
1733 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001734 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00001735 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001736 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00001737 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1738 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001739
Chris Lattner2da14fb2007-12-20 00:26:33 +00001740 return false;
1741}
1742
Benjamin Kramer634fc102010-02-15 22:42:31 +00001743/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1744/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001745/// to check everything. We expect the last argument to be a floating point
1746/// value.
1747bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1748 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001749 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001750 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001751 if (TheCall->getNumArgs() > NumArgs)
1752 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001753 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001754 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001755 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001756 (*(TheCall->arg_end()-1))->getLocEnd());
1757
Benjamin Kramer64aae502010-02-16 10:07:31 +00001758 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00001759
Eli Friedman7e4faac2009-08-31 20:06:00 +00001760 if (OrigArg->isTypeDependent())
1761 return false;
1762
Chris Lattner68784ef2010-05-06 05:50:07 +00001763 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00001764 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00001765 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001766 diag::err_typecheck_call_invalid_unary_fp)
1767 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001768
Chris Lattner68784ef2010-05-06 05:50:07 +00001769 // If this is an implicit conversion from float -> double, remove it.
1770 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1771 Expr *CastArg = Cast->getSubExpr();
1772 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1773 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1774 "promotion from float to double is the only expected cast here");
1775 Cast->setSubExpr(0);
Chris Lattner68784ef2010-05-06 05:50:07 +00001776 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00001777 }
1778 }
1779
Eli Friedman7e4faac2009-08-31 20:06:00 +00001780 return false;
1781}
1782
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001783/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1784// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00001785ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00001786 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001787 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00001788 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00001789 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1790 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001791
Nate Begemana0110022010-06-08 00:16:34 +00001792 // Determine which of the following types of shufflevector we're checking:
1793 // 1) unary, vector mask: (lhs, mask)
1794 // 2) binary, vector mask: (lhs, rhs, mask)
1795 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1796 QualType resType = TheCall->getArg(0)->getType();
1797 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00001798
Douglas Gregorc25f7662009-05-19 22:10:17 +00001799 if (!TheCall->getArg(0)->isTypeDependent() &&
1800 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00001801 QualType LHSType = TheCall->getArg(0)->getType();
1802 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00001803
Craig Topperbaca3892013-07-29 06:47:04 +00001804 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1805 return ExprError(Diag(TheCall->getLocStart(),
1806 diag::err_shufflevector_non_vector)
1807 << SourceRange(TheCall->getArg(0)->getLocStart(),
1808 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001809
Nate Begemana0110022010-06-08 00:16:34 +00001810 numElements = LHSType->getAs<VectorType>()->getNumElements();
1811 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00001812
Nate Begemana0110022010-06-08 00:16:34 +00001813 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1814 // with mask. If so, verify that RHS is an integer vector type with the
1815 // same number of elts as lhs.
1816 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00001817 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00001818 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00001819 return ExprError(Diag(TheCall->getLocStart(),
1820 diag::err_shufflevector_incompatible_vector)
1821 << SourceRange(TheCall->getArg(1)->getLocStart(),
1822 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001823 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00001824 return ExprError(Diag(TheCall->getLocStart(),
1825 diag::err_shufflevector_incompatible_vector)
1826 << SourceRange(TheCall->getArg(0)->getLocStart(),
1827 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00001828 } else if (numElements != numResElements) {
1829 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00001830 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001831 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001832 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001833 }
1834
1835 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001836 if (TheCall->getArg(i)->isTypeDependent() ||
1837 TheCall->getArg(i)->isValueDependent())
1838 continue;
1839
Nate Begemana0110022010-06-08 00:16:34 +00001840 llvm::APSInt Result(32);
1841 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1842 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001843 diag::err_shufflevector_nonconstant_argument)
1844 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001845
Craig Topper50ad5b72013-08-03 17:40:38 +00001846 // Allow -1 which will be translated to undef in the IR.
1847 if (Result.isSigned() && Result.isAllOnesValue())
1848 continue;
1849
Chris Lattner7ab824e2008-08-10 02:05:13 +00001850 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001851 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001852 diag::err_shufflevector_argument_too_large)
1853 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001854 }
1855
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001856 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001857
Chris Lattner7ab824e2008-08-10 02:05:13 +00001858 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001859 exprs.push_back(TheCall->getArg(i));
1860 TheCall->setArg(i, 0);
1861 }
1862
Benjamin Kramerc215e762012-08-24 11:54:20 +00001863 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek5a201952009-02-07 01:47:29 +00001864 TheCall->getCallee()->getLocStart(),
1865 TheCall->getRParenLoc()));
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001866}
Chris Lattner43be2e62007-12-19 23:59:04 +00001867
Hal Finkelc4d7c822013-09-18 03:29:45 +00001868/// SemaConvertVectorExpr - Handle __builtin_convertvector
1869ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1870 SourceLocation BuiltinLoc,
1871 SourceLocation RParenLoc) {
1872 ExprValueKind VK = VK_RValue;
1873 ExprObjectKind OK = OK_Ordinary;
1874 QualType DstTy = TInfo->getType();
1875 QualType SrcTy = E->getType();
1876
1877 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1878 return ExprError(Diag(BuiltinLoc,
1879 diag::err_convertvector_non_vector)
1880 << E->getSourceRange());
1881 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1882 return ExprError(Diag(BuiltinLoc,
1883 diag::err_convertvector_non_vector_type));
1884
1885 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1886 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1887 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1888 if (SrcElts != DstElts)
1889 return ExprError(Diag(BuiltinLoc,
1890 diag::err_convertvector_incompatible_vector)
1891 << E->getSourceRange());
1892 }
1893
1894 return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
1895 BuiltinLoc, RParenLoc));
1896
1897}
1898
Daniel Dunbarb7257262008-07-21 22:59:13 +00001899/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1900// This is declared to take (const void*, ...) and can take two
1901// optional constant int args.
1902bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00001903 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001904
Chris Lattner3b054132008-11-19 05:08:23 +00001905 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001906 return Diag(TheCall->getLocEnd(),
1907 diag::err_typecheck_call_too_many_args_at_most)
1908 << 0 /*function call*/ << 3 << NumArgs
1909 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001910
1911 // Argument 0 is checked for us and the remaining arguments must be
1912 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00001913 for (unsigned i = 1; i != NumArgs; ++i)
1914 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00001915 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001916
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001917 return false;
1918}
1919
Eric Christopher8d0c6212010-04-17 02:26:23 +00001920/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1921/// TheCall is a constant expression.
1922bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1923 llvm::APSInt &Result) {
1924 Expr *Arg = TheCall->getArg(ArgNum);
1925 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1926 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1927
1928 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1929
1930 if (!Arg->isIntegerConstantExpr(Result, Context))
1931 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00001932 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00001933
Chris Lattnerd545ad12009-09-23 06:06:36 +00001934 return false;
1935}
1936
Richard Sandiford28940af2014-04-16 08:47:51 +00001937/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
1938/// TheCall is a constant expression in the range [Low, High].
1939bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
1940 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00001941 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001942
1943 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00001944 Expr *Arg = TheCall->getArg(ArgNum);
1945 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001946 return false;
1947
Eric Christopher8d0c6212010-04-17 02:26:23 +00001948 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00001949 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00001950 return true;
1951
Richard Sandiford28940af2014-04-16 08:47:51 +00001952 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00001953 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00001954 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001955
1956 return false;
1957}
1958
Eli Friedmanc97d0142009-05-03 06:04:26 +00001959/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00001960/// This checks that val is a constant 1.
1961bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1962 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00001963 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00001964
Eric Christopher8d0c6212010-04-17 02:26:23 +00001965 // TODO: This is less than ideal. Overload this to take a value.
1966 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1967 return true;
1968
1969 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00001970 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1971 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1972
1973 return false;
1974}
1975
Richard Smithd7293d72013-08-05 18:49:43 +00001976namespace {
1977enum StringLiteralCheckType {
1978 SLCT_NotALiteral,
1979 SLCT_UncheckedLiteral,
1980 SLCT_CheckedLiteral
1981};
1982}
1983
Richard Smith55ce3522012-06-25 20:30:08 +00001984// Determine if an expression is a string literal or constant string.
1985// If this function returns false on the arguments to a function expecting a
1986// format string, we will usually need to emit a warning.
1987// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00001988static StringLiteralCheckType
1989checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
1990 bool HasVAListArg, unsigned format_idx,
1991 unsigned firstDataArg, Sema::FormatStringType Type,
1992 Sema::VariadicCallType CallType, bool InFunctionCall,
1993 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00001994 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00001995 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00001996 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001997
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00001998 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00001999
Richard Smithd7293d72013-08-05 18:49:43 +00002000 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002001 // Technically -Wformat-nonliteral does not warn about this case.
2002 // The behavior of printf and friends in this case is implementation
2003 // dependent. Ideally if the format string cannot be null then
2004 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002005 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002006
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002007 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002008 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002009 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002010 // The expression is a literal if both sub-expressions were, and it was
2011 // completely checked only if both sub-expressions were checked.
2012 const AbstractConditionalOperator *C =
2013 cast<AbstractConditionalOperator>(E);
2014 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002015 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002016 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002017 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002018 if (Left == SLCT_NotALiteral)
2019 return SLCT_NotALiteral;
2020 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002021 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002022 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002023 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002024 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002025 }
2026
2027 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002028 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2029 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002030 }
2031
John McCallc07a0c72011-02-17 10:25:35 +00002032 case Stmt::OpaqueValueExprClass:
2033 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2034 E = src;
2035 goto tryAgain;
2036 }
Richard Smith55ce3522012-06-25 20:30:08 +00002037 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002038
Ted Kremeneka8890832011-02-24 23:03:04 +00002039 case Stmt::PredefinedExprClass:
2040 // While __func__, etc., are technically not string literals, they
2041 // cannot contain format specifiers and thus are not a security
2042 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002043 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002044
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002045 case Stmt::DeclRefExprClass: {
2046 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002047
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002048 // As an exception, do not flag errors for variables binding to
2049 // const string literals.
2050 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2051 bool isConstant = false;
2052 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002053
Richard Smithd7293d72013-08-05 18:49:43 +00002054 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2055 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002056 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002057 isConstant = T.isConstant(S.Context) &&
2058 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002059 } else if (T->isObjCObjectPointerType()) {
2060 // In ObjC, there is usually no "const ObjectPointer" type,
2061 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002062 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002063 }
Mike Stump11289f42009-09-09 15:08:12 +00002064
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002065 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002066 if (const Expr *Init = VD->getAnyInitializer()) {
2067 // Look through initializers like const char c[] = { "foo" }
2068 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2069 if (InitList->isStringLiteralInit())
2070 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2071 }
Richard Smithd7293d72013-08-05 18:49:43 +00002072 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002073 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002074 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002075 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002076 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002077 }
Mike Stump11289f42009-09-09 15:08:12 +00002078
Anders Carlssonb012ca92009-06-28 19:55:58 +00002079 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2080 // special check to see if the format string is a function parameter
2081 // of the function calling the printf function. If the function
2082 // has an attribute indicating it is a printf-like function, then we
2083 // should suppress warnings concerning non-literals being used in a call
2084 // to a vprintf function. For example:
2085 //
2086 // void
2087 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2088 // va_list ap;
2089 // va_start(ap, fmt);
2090 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2091 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002092 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002093 if (HasVAListArg) {
2094 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2095 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2096 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002097 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002098 // adjust for implicit parameter
2099 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2100 if (MD->isInstance())
2101 ++PVIndex;
2102 // We also check if the formats are compatible.
2103 // We can't pass a 'scanf' string to a 'printf' function.
2104 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002105 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002106 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002107 }
2108 }
2109 }
2110 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002111 }
Mike Stump11289f42009-09-09 15:08:12 +00002112
Richard Smith55ce3522012-06-25 20:30:08 +00002113 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002114 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002115
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002116 case Stmt::CallExprClass:
2117 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002118 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002119 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2120 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2121 unsigned ArgIndex = FA->getFormatIdx();
2122 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2123 if (MD->isInstance())
2124 --ArgIndex;
2125 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002126
Richard Smithd7293d72013-08-05 18:49:43 +00002127 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002128 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002129 Type, CallType, InFunctionCall,
2130 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002131 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2132 unsigned BuiltinID = FD->getBuiltinID();
2133 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2134 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2135 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002136 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002137 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002138 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002139 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002140 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002141 }
2142 }
Mike Stump11289f42009-09-09 15:08:12 +00002143
Richard Smith55ce3522012-06-25 20:30:08 +00002144 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002145 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002146 case Stmt::ObjCStringLiteralClass:
2147 case Stmt::StringLiteralClass: {
2148 const StringLiteral *StrE = NULL;
Mike Stump11289f42009-09-09 15:08:12 +00002149
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002150 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002151 StrE = ObjCFExpr->getString();
2152 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002153 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002154
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002155 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002156 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2157 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002158 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002159 }
Mike Stump11289f42009-09-09 15:08:12 +00002160
Richard Smith55ce3522012-06-25 20:30:08 +00002161 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002162 }
Mike Stump11289f42009-09-09 15:08:12 +00002163
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002164 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002165 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002166 }
2167}
2168
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002169Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002170 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002171 .Case("scanf", FST_Scanf)
2172 .Cases("printf", "printf0", FST_Printf)
2173 .Cases("NSString", "CFString", FST_NSString)
2174 .Case("strftime", FST_Strftime)
2175 .Case("strfmon", FST_Strfmon)
2176 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2177 .Default(FST_Unknown);
2178}
2179
Jordan Rose3e0ec582012-07-19 18:10:23 +00002180/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002181/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002182/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002183bool Sema::CheckFormatArguments(const FormatAttr *Format,
2184 ArrayRef<const Expr *> Args,
2185 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002186 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002187 SourceLocation Loc, SourceRange Range,
2188 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002189 FormatStringInfo FSI;
2190 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002191 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002192 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002193 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002194 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002195}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002196
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002197bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002198 bool HasVAListArg, unsigned format_idx,
2199 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002200 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002201 SourceLocation Loc, SourceRange Range,
2202 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002203 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002204 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002205 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002206 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002207 }
Mike Stump11289f42009-09-09 15:08:12 +00002208
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002209 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002210
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002211 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002212 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002213 // Dynamically generated format strings are difficult to
2214 // automatically vet at compile time. Requiring that format strings
2215 // are string literals: (1) permits the checking of format strings by
2216 // the compiler and thereby (2) can practically remove the source of
2217 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002218
Mike Stump11289f42009-09-09 15:08:12 +00002219 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002220 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002221 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002222 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002223 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002224 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2225 format_idx, firstDataArg, Type, CallType,
2226 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002227 if (CT != SLCT_NotALiteral)
2228 // Literal format string found, check done!
2229 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002230
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002231 // Strftime is particular as it always uses a single 'time' argument,
2232 // so it is safe to pass a non-literal string.
2233 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002234 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002235
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002236 // Do not emit diag when the string param is a macro expansion and the
2237 // format is either NSString or CFString. This is a hack to prevent
2238 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2239 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002240 if (Type == FST_NSString &&
2241 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002242 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002243
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002244 // If there are no arguments specified, warn with -Wformat-security, otherwise
2245 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002246 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002247 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002248 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002249 << OrigFormatExpr->getSourceRange();
2250 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002251 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002252 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002253 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002254 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002255}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002256
Ted Kremenekab278de2010-01-28 23:39:18 +00002257namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002258class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2259protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002260 Sema &S;
2261 const StringLiteral *FExpr;
2262 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002263 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002264 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002265 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002266 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002267 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002268 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002269 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002270 bool usesPositionalArgs;
2271 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002272 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002273 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002274 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002275public:
Ted Kremenek02087932010-07-16 02:11:22 +00002276 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002277 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002278 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002279 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002280 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002281 Sema::VariadicCallType callType,
2282 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002283 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002284 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2285 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002286 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002287 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002288 inFunctionCall(inFunctionCall), CallType(callType),
2289 CheckedVarArgs(CheckedVarArgs) {
2290 CoveredArgs.resize(numDataArgs);
2291 CoveredArgs.reset();
2292 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002293
Ted Kremenek019d2242010-01-29 01:50:07 +00002294 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002295
Ted Kremenek02087932010-07-16 02:11:22 +00002296 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002297 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002298
Jordan Rose92303592012-09-08 04:00:03 +00002299 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002300 const analyze_format_string::FormatSpecifier &FS,
2301 const analyze_format_string::ConversionSpecifier &CS,
2302 const char *startSpecifier, unsigned specifierLen,
2303 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002304
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002305 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002306 const analyze_format_string::FormatSpecifier &FS,
2307 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002308
2309 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002310 const analyze_format_string::ConversionSpecifier &CS,
2311 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002312
Craig Toppere14c0f82014-03-12 04:55:44 +00002313 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002314
Craig Toppere14c0f82014-03-12 04:55:44 +00002315 void HandleInvalidPosition(const char *startSpecifier,
2316 unsigned specifierLen,
2317 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002318
Craig Toppere14c0f82014-03-12 04:55:44 +00002319 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002320
Craig Toppere14c0f82014-03-12 04:55:44 +00002321 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002322
Richard Trieu03cf7b72011-10-28 00:41:25 +00002323 template <typename Range>
2324 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2325 const Expr *ArgumentExpr,
2326 PartialDiagnostic PDiag,
2327 SourceLocation StringLoc,
2328 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002329 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002330
Ted Kremenek02087932010-07-16 02:11:22 +00002331protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002332 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2333 const char *startSpec,
2334 unsigned specifierLen,
2335 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002336
2337 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2338 const char *startSpec,
2339 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002340
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002341 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002342 CharSourceRange getSpecifierRange(const char *startSpecifier,
2343 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002344 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002345
Ted Kremenek5739de72010-01-29 01:06:55 +00002346 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002347
2348 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2349 const analyze_format_string::ConversionSpecifier &CS,
2350 const char *startSpecifier, unsigned specifierLen,
2351 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002352
2353 template <typename Range>
2354 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2355 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002356 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002357};
2358}
2359
Ted Kremenek02087932010-07-16 02:11:22 +00002360SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002361 return OrigFormatExpr->getSourceRange();
2362}
2363
Ted Kremenek02087932010-07-16 02:11:22 +00002364CharSourceRange CheckFormatHandler::
2365getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002366 SourceLocation Start = getLocationOfByte(startSpecifier);
2367 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2368
2369 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002370 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002371
2372 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002373}
2374
Ted Kremenek02087932010-07-16 02:11:22 +00002375SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002376 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002377}
2378
Ted Kremenek02087932010-07-16 02:11:22 +00002379void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2380 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002381 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2382 getLocationOfByte(startSpecifier),
2383 /*IsStringLocation*/true,
2384 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002385}
2386
Jordan Rose92303592012-09-08 04:00:03 +00002387void CheckFormatHandler::HandleInvalidLengthModifier(
2388 const analyze_format_string::FormatSpecifier &FS,
2389 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002390 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002391 using namespace analyze_format_string;
2392
2393 const LengthModifier &LM = FS.getLengthModifier();
2394 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2395
2396 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002397 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002398 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002399 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002400 getLocationOfByte(LM.getStart()),
2401 /*IsStringLocation*/true,
2402 getSpecifierRange(startSpecifier, specifierLen));
2403
2404 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2405 << FixedLM->toString()
2406 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2407
2408 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002409 FixItHint Hint;
2410 if (DiagID == diag::warn_format_nonsensical_length)
2411 Hint = FixItHint::CreateRemoval(LMRange);
2412
2413 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002414 getLocationOfByte(LM.getStart()),
2415 /*IsStringLocation*/true,
2416 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002417 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002418 }
2419}
2420
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002421void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002422 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002423 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002424 using namespace analyze_format_string;
2425
2426 const LengthModifier &LM = FS.getLengthModifier();
2427 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2428
2429 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002430 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002431 if (FixedLM) {
2432 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2433 << LM.toString() << 0,
2434 getLocationOfByte(LM.getStart()),
2435 /*IsStringLocation*/true,
2436 getSpecifierRange(startSpecifier, specifierLen));
2437
2438 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2439 << FixedLM->toString()
2440 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2441
2442 } else {
2443 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2444 << LM.toString() << 0,
2445 getLocationOfByte(LM.getStart()),
2446 /*IsStringLocation*/true,
2447 getSpecifierRange(startSpecifier, specifierLen));
2448 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002449}
2450
2451void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2452 const analyze_format_string::ConversionSpecifier &CS,
2453 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002454 using namespace analyze_format_string;
2455
2456 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002457 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002458 if (FixedCS) {
2459 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2460 << CS.toString() << /*conversion specifier*/1,
2461 getLocationOfByte(CS.getStart()),
2462 /*IsStringLocation*/true,
2463 getSpecifierRange(startSpecifier, specifierLen));
2464
2465 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2466 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2467 << FixedCS->toString()
2468 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2469 } else {
2470 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2471 << CS.toString() << /*conversion specifier*/1,
2472 getLocationOfByte(CS.getStart()),
2473 /*IsStringLocation*/true,
2474 getSpecifierRange(startSpecifier, specifierLen));
2475 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002476}
2477
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002478void CheckFormatHandler::HandlePosition(const char *startPos,
2479 unsigned posLen) {
2480 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2481 getLocationOfByte(startPos),
2482 /*IsStringLocation*/true,
2483 getSpecifierRange(startPos, posLen));
2484}
2485
Ted Kremenekd1668192010-02-27 01:41:03 +00002486void
Ted Kremenek02087932010-07-16 02:11:22 +00002487CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2488 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002489 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2490 << (unsigned) p,
2491 getLocationOfByte(startPos), /*IsStringLocation*/true,
2492 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002493}
2494
Ted Kremenek02087932010-07-16 02:11:22 +00002495void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002496 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002497 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2498 getLocationOfByte(startPos),
2499 /*IsStringLocation*/true,
2500 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002501}
2502
Ted Kremenek02087932010-07-16 02:11:22 +00002503void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002504 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002505 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002506 EmitFormatDiagnostic(
2507 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2508 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2509 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002510 }
Ted Kremenek02087932010-07-16 02:11:22 +00002511}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002512
Jordan Rose58bbe422012-07-19 18:10:08 +00002513// Note that this may return NULL if there was an error parsing or building
2514// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002515const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002516 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002517}
2518
2519void CheckFormatHandler::DoneProcessing() {
2520 // Does the number of data arguments exceed the number of
2521 // format conversions in the format string?
2522 if (!HasVAListArg) {
2523 // Find any arguments that weren't covered.
2524 CoveredArgs.flip();
2525 signed notCoveredArg = CoveredArgs.find_first();
2526 if (notCoveredArg >= 0) {
2527 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002528 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2529 SourceLocation Loc = E->getLocStart();
2530 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2531 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2532 Loc, /*IsStringLocation*/false,
2533 getFormatStringRange());
2534 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002535 }
Ted Kremenek02087932010-07-16 02:11:22 +00002536 }
2537 }
2538}
2539
Ted Kremenekce815422010-07-19 21:25:57 +00002540bool
2541CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2542 SourceLocation Loc,
2543 const char *startSpec,
2544 unsigned specifierLen,
2545 const char *csStart,
2546 unsigned csLen) {
2547
2548 bool keepGoing = true;
2549 if (argIndex < NumDataArgs) {
2550 // Consider the argument coverered, even though the specifier doesn't
2551 // make sense.
2552 CoveredArgs.set(argIndex);
2553 }
2554 else {
2555 // If argIndex exceeds the number of data arguments we
2556 // don't issue a warning because that is just a cascade of warnings (and
2557 // they may have intended '%%' anyway). We don't want to continue processing
2558 // the format string after this point, however, as we will like just get
2559 // gibberish when trying to match arguments.
2560 keepGoing = false;
2561 }
2562
Richard Trieu03cf7b72011-10-28 00:41:25 +00002563 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2564 << StringRef(csStart, csLen),
2565 Loc, /*IsStringLocation*/true,
2566 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00002567
2568 return keepGoing;
2569}
2570
Richard Trieu03cf7b72011-10-28 00:41:25 +00002571void
2572CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2573 const char *startSpec,
2574 unsigned specifierLen) {
2575 EmitFormatDiagnostic(
2576 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2577 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2578}
2579
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002580bool
2581CheckFormatHandler::CheckNumArgs(
2582 const analyze_format_string::FormatSpecifier &FS,
2583 const analyze_format_string::ConversionSpecifier &CS,
2584 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2585
2586 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002587 PartialDiagnostic PDiag = FS.usesPositionalArg()
2588 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2589 << (argIndex+1) << NumDataArgs)
2590 : S.PDiag(diag::warn_printf_insufficient_data_args);
2591 EmitFormatDiagnostic(
2592 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2593 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002594 return false;
2595 }
2596 return true;
2597}
2598
Richard Trieu03cf7b72011-10-28 00:41:25 +00002599template<typename Range>
2600void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2601 SourceLocation Loc,
2602 bool IsStringLocation,
2603 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002604 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002605 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002606 Loc, IsStringLocation, StringRange, FixIt);
2607}
2608
2609/// \brief If the format string is not within the funcion call, emit a note
2610/// so that the function call and string are in diagnostic messages.
2611///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002612/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00002613/// call and only one diagnostic message will be produced. Otherwise, an
2614/// extra note will be emitted pointing to location of the format string.
2615///
2616/// \param ArgumentExpr the expression that is passed as the format string
2617/// argument in the function call. Used for getting locations when two
2618/// diagnostics are emitted.
2619///
2620/// \param PDiag the callee should already have provided any strings for the
2621/// diagnostic message. This function only adds locations and fixits
2622/// to diagnostics.
2623///
2624/// \param Loc primary location for diagnostic. If two diagnostics are
2625/// required, one will be at Loc and a new SourceLocation will be created for
2626/// the other one.
2627///
2628/// \param IsStringLocation if true, Loc points to the format string should be
2629/// used for the note. Otherwise, Loc points to the argument list and will
2630/// be used with PDiag.
2631///
2632/// \param StringRange some or all of the string to highlight. This is
2633/// templated so it can accept either a CharSourceRange or a SourceRange.
2634///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002635/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002636template<typename Range>
2637void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2638 const Expr *ArgumentExpr,
2639 PartialDiagnostic PDiag,
2640 SourceLocation Loc,
2641 bool IsStringLocation,
2642 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002643 ArrayRef<FixItHint> FixIt) {
2644 if (InFunctionCall) {
2645 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2646 D << StringRange;
2647 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2648 I != E; ++I) {
2649 D << *I;
2650 }
2651 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002652 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2653 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00002654
2655 const Sema::SemaDiagnosticBuilder &Note =
2656 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2657 diag::note_format_string_defined);
2658
2659 Note << StringRange;
2660 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2661 I != E; ++I) {
2662 Note << *I;
2663 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00002664 }
2665}
2666
Ted Kremenek02087932010-07-16 02:11:22 +00002667//===--- CHECK: Printf format string checking ------------------------------===//
2668
2669namespace {
2670class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002671 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00002672public:
2673 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2674 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002675 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00002676 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002677 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002678 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002679 Sema::VariadicCallType CallType,
2680 llvm::SmallBitVector &CheckedVarArgs)
2681 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2682 numDataArgs, beg, hasVAListArg, Args,
2683 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2684 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00002685 {}
2686
Craig Toppere14c0f82014-03-12 04:55:44 +00002687
Ted Kremenek02087932010-07-16 02:11:22 +00002688 bool HandleInvalidPrintfConversionSpecifier(
2689 const analyze_printf::PrintfSpecifier &FS,
2690 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002691 unsigned specifierLen) override;
2692
Ted Kremenek02087932010-07-16 02:11:22 +00002693 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2694 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002695 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00002696 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2697 const char *StartSpecifier,
2698 unsigned SpecifierLen,
2699 const Expr *E);
2700
Ted Kremenek02087932010-07-16 02:11:22 +00002701 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2702 const char *startSpecifier, unsigned specifierLen);
2703 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2704 const analyze_printf::OptionalAmount &Amt,
2705 unsigned type,
2706 const char *startSpecifier, unsigned specifierLen);
2707 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2708 const analyze_printf::OptionalFlag &flag,
2709 const char *startSpecifier, unsigned specifierLen);
2710 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2711 const analyze_printf::OptionalFlag &ignoredFlag,
2712 const analyze_printf::OptionalFlag &flag,
2713 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002714 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00002715 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00002716
Ted Kremenek02087932010-07-16 02:11:22 +00002717};
2718}
2719
2720bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2721 const analyze_printf::PrintfSpecifier &FS,
2722 const char *startSpecifier,
2723 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002724 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00002725 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00002726
Ted Kremenekce815422010-07-19 21:25:57 +00002727 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2728 getLocationOfByte(CS.getStart()),
2729 startSpecifier, specifierLen,
2730 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00002731}
2732
Ted Kremenek02087932010-07-16 02:11:22 +00002733bool CheckPrintfHandler::HandleAmount(
2734 const analyze_format_string::OptionalAmount &Amt,
2735 unsigned k, const char *startSpecifier,
2736 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002737
2738 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002739 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00002740 unsigned argIndex = Amt.getArgIndex();
2741 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002742 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2743 << k,
2744 getLocationOfByte(Amt.getStart()),
2745 /*IsStringLocation*/true,
2746 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002747 // Don't do any more checking. We will just emit
2748 // spurious errors.
2749 return false;
2750 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002751
Ted Kremenek5739de72010-01-29 01:06:55 +00002752 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00002753 // Although not in conformance with C99, we also allow the argument to be
2754 // an 'unsigned int' as that is a reasonably safe case. GCC also
2755 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00002756 CoveredArgs.set(argIndex);
2757 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00002758 if (!Arg)
2759 return false;
2760
Ted Kremenek5739de72010-01-29 01:06:55 +00002761 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002762
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002763 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2764 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002765
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002766 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002767 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002768 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00002769 << T << Arg->getSourceRange(),
2770 getLocationOfByte(Amt.getStart()),
2771 /*IsStringLocation*/true,
2772 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002773 // Don't do any more checking. We will just emit
2774 // spurious errors.
2775 return false;
2776 }
2777 }
2778 }
2779 return true;
2780}
Ted Kremenek5739de72010-01-29 01:06:55 +00002781
Tom Careb49ec692010-06-17 19:00:27 +00002782void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00002783 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002784 const analyze_printf::OptionalAmount &Amt,
2785 unsigned type,
2786 const char *startSpecifier,
2787 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002788 const analyze_printf::PrintfConversionSpecifier &CS =
2789 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00002790
Richard Trieu03cf7b72011-10-28 00:41:25 +00002791 FixItHint fixit =
2792 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2793 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2794 Amt.getConstantLength()))
2795 : FixItHint();
2796
2797 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2798 << type << CS.toString(),
2799 getLocationOfByte(Amt.getStart()),
2800 /*IsStringLocation*/true,
2801 getSpecifierRange(startSpecifier, specifierLen),
2802 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00002803}
2804
Ted Kremenek02087932010-07-16 02:11:22 +00002805void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002806 const analyze_printf::OptionalFlag &flag,
2807 const char *startSpecifier,
2808 unsigned specifierLen) {
2809 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002810 const analyze_printf::PrintfConversionSpecifier &CS =
2811 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00002812 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2813 << flag.toString() << CS.toString(),
2814 getLocationOfByte(flag.getPosition()),
2815 /*IsStringLocation*/true,
2816 getSpecifierRange(startSpecifier, specifierLen),
2817 FixItHint::CreateRemoval(
2818 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002819}
2820
2821void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00002822 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002823 const analyze_printf::OptionalFlag &ignoredFlag,
2824 const analyze_printf::OptionalFlag &flag,
2825 const char *startSpecifier,
2826 unsigned specifierLen) {
2827 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002828 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2829 << ignoredFlag.toString() << flag.toString(),
2830 getLocationOfByte(ignoredFlag.getPosition()),
2831 /*IsStringLocation*/true,
2832 getSpecifierRange(startSpecifier, specifierLen),
2833 FixItHint::CreateRemoval(
2834 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002835}
2836
Richard Smith55ce3522012-06-25 20:30:08 +00002837// Determines if the specified is a C++ class or struct containing
2838// a member with the specified name and kind (e.g. a CXXMethodDecl named
2839// "c_str()").
2840template<typename MemberKind>
2841static llvm::SmallPtrSet<MemberKind*, 1>
2842CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2843 const RecordType *RT = Ty->getAs<RecordType>();
2844 llvm::SmallPtrSet<MemberKind*, 1> Results;
2845
2846 if (!RT)
2847 return Results;
2848 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00002849 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00002850 return Results;
2851
Alp Tokerb6cc5922014-05-03 03:45:55 +00002852 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00002853 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00002854 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00002855
2856 // We just need to include all members of the right kind turned up by the
2857 // filter, at this point.
2858 if (S.LookupQualifiedName(R, RT->getDecl()))
2859 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2860 NamedDecl *decl = (*I)->getUnderlyingDecl();
2861 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2862 Results.insert(FK);
2863 }
2864 return Results;
2865}
2866
Richard Smith2868a732014-02-28 01:36:39 +00002867/// Check if we could call '.c_str()' on an object.
2868///
2869/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
2870/// allow the call, or if it would be ambiguous).
2871bool Sema::hasCStrMethod(const Expr *E) {
2872 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2873 MethodSet Results =
2874 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
2875 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2876 MI != ME; ++MI)
2877 if ((*MI)->getMinRequiredArguments() == 0)
2878 return true;
2879 return false;
2880}
2881
Richard Smith55ce3522012-06-25 20:30:08 +00002882// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002883// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00002884// Returns true when a c_str() conversion method is found.
2885bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00002886 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00002887 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2888
2889 MethodSet Results =
2890 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2891
2892 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2893 MI != ME; ++MI) {
2894 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00002895 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00002896 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00002897 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00002898 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00002899 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2900 << "c_str()"
2901 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2902 return true;
2903 }
2904 }
2905
2906 return false;
2907}
2908
Ted Kremenekab278de2010-01-28 23:39:18 +00002909bool
Ted Kremenek02087932010-07-16 02:11:22 +00002910CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00002911 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00002912 const char *startSpecifier,
2913 unsigned specifierLen) {
2914
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002915 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00002916 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002917 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00002918
Ted Kremenek6cd69422010-07-19 22:01:06 +00002919 if (FS.consumesDataArgument()) {
2920 if (atFirstArg) {
2921 atFirstArg = false;
2922 usesPositionalArgs = FS.usesPositionalArg();
2923 }
2924 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002925 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2926 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00002927 return false;
2928 }
Ted Kremenek5739de72010-01-29 01:06:55 +00002929 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002930
Ted Kremenekd1668192010-02-27 01:41:03 +00002931 // First check if the field width, precision, and conversion specifier
2932 // have matching data arguments.
2933 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2934 startSpecifier, specifierLen)) {
2935 return false;
2936 }
2937
2938 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2939 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002940 return false;
2941 }
2942
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002943 if (!CS.consumesDataArgument()) {
2944 // FIXME: Technically specifying a precision or field width here
2945 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00002946 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002947 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002948
Ted Kremenek4a49d982010-02-26 19:18:41 +00002949 // Consume the argument.
2950 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00002951 if (argIndex < NumDataArgs) {
2952 // The check to see if the argIndex is valid will come later.
2953 // We set the bit here because we may exit early from this
2954 // function if we encounter some other error.
2955 CoveredArgs.set(argIndex);
2956 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00002957
2958 // Check for using an Objective-C specific conversion specifier
2959 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002960 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00002961 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2962 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00002963 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002964
Tom Careb49ec692010-06-17 19:00:27 +00002965 // Check for invalid use of field width
2966 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00002967 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00002968 startSpecifier, specifierLen);
2969 }
2970
2971 // Check for invalid use of precision
2972 if (!FS.hasValidPrecision()) {
2973 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2974 startSpecifier, specifierLen);
2975 }
2976
2977 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00002978 if (!FS.hasValidThousandsGroupingPrefix())
2979 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00002980 if (!FS.hasValidLeadingZeros())
2981 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2982 if (!FS.hasValidPlusPrefix())
2983 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00002984 if (!FS.hasValidSpacePrefix())
2985 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00002986 if (!FS.hasValidAlternativeForm())
2987 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2988 if (!FS.hasValidLeftJustified())
2989 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2990
2991 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00002992 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2993 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2994 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00002995 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2996 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2997 startSpecifier, specifierLen);
2998
2999 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003000 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003001 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3002 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003003 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003004 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003005 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003006 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3007 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003008
Jordan Rose92303592012-09-08 04:00:03 +00003009 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3010 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3011
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003012 // The remaining checks depend on the data arguments.
3013 if (HasVAListArg)
3014 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003015
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003016 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003017 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003018
Jordan Rose58bbe422012-07-19 18:10:08 +00003019 const Expr *Arg = getDataArg(argIndex);
3020 if (!Arg)
3021 return true;
3022
3023 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003024}
3025
Jordan Roseaee34382012-09-05 22:56:26 +00003026static bool requiresParensToAddCast(const Expr *E) {
3027 // FIXME: We should have a general way to reason about operator
3028 // precedence and whether parens are actually needed here.
3029 // Take care of a few common cases where they aren't.
3030 const Expr *Inside = E->IgnoreImpCasts();
3031 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3032 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3033
3034 switch (Inside->getStmtClass()) {
3035 case Stmt::ArraySubscriptExprClass:
3036 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003037 case Stmt::CharacterLiteralClass:
3038 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003039 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003040 case Stmt::FloatingLiteralClass:
3041 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003042 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003043 case Stmt::ObjCArrayLiteralClass:
3044 case Stmt::ObjCBoolLiteralExprClass:
3045 case Stmt::ObjCBoxedExprClass:
3046 case Stmt::ObjCDictionaryLiteralClass:
3047 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003048 case Stmt::ObjCIvarRefExprClass:
3049 case Stmt::ObjCMessageExprClass:
3050 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003051 case Stmt::ObjCStringLiteralClass:
3052 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003053 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003054 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003055 case Stmt::UnaryOperatorClass:
3056 return false;
3057 default:
3058 return true;
3059 }
3060}
3061
Richard Smith55ce3522012-06-25 20:30:08 +00003062bool
3063CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3064 const char *StartSpecifier,
3065 unsigned SpecifierLen,
3066 const Expr *E) {
3067 using namespace analyze_format_string;
3068 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003069 // Now type check the data expression that matches the
3070 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003071 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3072 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003073 if (!AT.isValid())
3074 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003075
Jordan Rose598ec092012-12-05 18:44:40 +00003076 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003077 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3078 ExprTy = TET->getUnderlyingExpr()->getType();
3079 }
3080
Jordan Rose598ec092012-12-05 18:44:40 +00003081 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003082 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003083
Jordan Rose22b74712012-09-05 22:56:19 +00003084 // Look through argument promotions for our error message's reported type.
3085 // This includes the integral and floating promotions, but excludes array
3086 // and function pointer decay; seeing that an argument intended to be a
3087 // string has type 'char [6]' is probably more confusing than 'char *'.
3088 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3089 if (ICE->getCastKind() == CK_IntegralCast ||
3090 ICE->getCastKind() == CK_FloatingCast) {
3091 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003092 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003093
3094 // Check if we didn't match because of an implicit cast from a 'char'
3095 // or 'short' to an 'int'. This is done because printf is a varargs
3096 // function.
3097 if (ICE->getType() == S.Context.IntTy ||
3098 ICE->getType() == S.Context.UnsignedIntTy) {
3099 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003100 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003101 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003102 }
Jordan Rose98709982012-06-04 22:48:57 +00003103 }
Jordan Rose598ec092012-12-05 18:44:40 +00003104 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3105 // Special case for 'a', which has type 'int' in C.
3106 // Note, however, that we do /not/ want to treat multibyte constants like
3107 // 'MooV' as characters! This form is deprecated but still exists.
3108 if (ExprTy == S.Context.IntTy)
3109 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3110 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003111 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003112
Jordan Rose0e5badd2012-12-05 18:44:49 +00003113 // %C in an Objective-C context prints a unichar, not a wchar_t.
3114 // If the argument is an integer of some kind, believe the %C and suggest
3115 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003116 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003117 if (ObjCContext &&
3118 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3119 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3120 !ExprTy->isCharType()) {
3121 // 'unichar' is defined as a typedef of unsigned short, but we should
3122 // prefer using the typedef if it is visible.
3123 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003124
3125 // While we are here, check if the value is an IntegerLiteral that happens
3126 // to be within the valid range.
3127 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3128 const llvm::APInt &V = IL->getValue();
3129 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3130 return true;
3131 }
3132
Jordan Rose0e5badd2012-12-05 18:44:49 +00003133 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3134 Sema::LookupOrdinaryName);
3135 if (S.LookupName(Result, S.getCurScope())) {
3136 NamedDecl *ND = Result.getFoundDecl();
3137 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3138 if (TD->getUnderlyingType() == IntendedTy)
3139 IntendedTy = S.Context.getTypedefType(TD);
3140 }
3141 }
3142 }
3143
3144 // Special-case some of Darwin's platform-independence types by suggesting
3145 // casts to primitive types that are known to be large enough.
3146 bool ShouldNotPrintDirectly = false;
Jordan Roseaee34382012-09-05 22:56:26 +00003147 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003148 // Use a 'while' to peel off layers of typedefs.
3149 QualType TyTy = IntendedTy;
3150 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseaee34382012-09-05 22:56:26 +00003151 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose0e5badd2012-12-05 18:44:49 +00003152 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseaee34382012-09-05 22:56:26 +00003153 .Case("NSInteger", S.Context.LongTy)
3154 .Case("NSUInteger", S.Context.UnsignedLongTy)
3155 .Case("SInt32", S.Context.IntTy)
3156 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose0e5badd2012-12-05 18:44:49 +00003157 .Default(QualType());
3158
3159 if (!CastTy.isNull()) {
3160 ShouldNotPrintDirectly = true;
3161 IntendedTy = CastTy;
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003162 break;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003163 }
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003164 TyTy = UserTy->desugar();
Jordan Roseaee34382012-09-05 22:56:26 +00003165 }
3166 }
3167
Jordan Rose22b74712012-09-05 22:56:19 +00003168 // We may be able to offer a FixItHint if it is a supported type.
3169 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003170 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003171 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003172
Jordan Rose22b74712012-09-05 22:56:19 +00003173 if (success) {
3174 // Get the fix string from the fixed format specifier
3175 SmallString<16> buf;
3176 llvm::raw_svector_ostream os(buf);
3177 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003178
Jordan Roseaee34382012-09-05 22:56:26 +00003179 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3180
Jordan Rose0e5badd2012-12-05 18:44:49 +00003181 if (IntendedTy == ExprTy) {
3182 // In this case, the specifier is wrong and should be changed to match
3183 // the argument.
3184 EmitFormatDiagnostic(
3185 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3186 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3187 << E->getSourceRange(),
3188 E->getLocStart(),
3189 /*IsStringLocation*/false,
3190 SpecRange,
3191 FixItHint::CreateReplacement(SpecRange, os.str()));
3192
3193 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003194 // The canonical type for formatting this value is different from the
3195 // actual type of the expression. (This occurs, for example, with Darwin's
3196 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3197 // should be printed as 'long' for 64-bit compatibility.)
3198 // Rather than emitting a normal format/argument mismatch, we want to
3199 // add a cast to the recommended type (and correct the format string
3200 // if necessary).
3201 SmallString<16> CastBuf;
3202 llvm::raw_svector_ostream CastFix(CastBuf);
3203 CastFix << "(";
3204 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3205 CastFix << ")";
3206
3207 SmallVector<FixItHint,4> Hints;
3208 if (!AT.matchesType(S.Context, IntendedTy))
3209 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3210
3211 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3212 // If there's already a cast present, just replace it.
3213 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3214 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3215
3216 } else if (!requiresParensToAddCast(E)) {
3217 // If the expression has high enough precedence,
3218 // just write the C-style cast.
3219 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3220 CastFix.str()));
3221 } else {
3222 // Otherwise, add parens around the expression as well as the cast.
3223 CastFix << "(";
3224 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3225 CastFix.str()));
3226
Alp Tokerb6cc5922014-05-03 03:45:55 +00003227 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003228 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3229 }
3230
Jordan Rose0e5badd2012-12-05 18:44:49 +00003231 if (ShouldNotPrintDirectly) {
3232 // The expression has a type that should not be printed directly.
3233 // We extract the name from the typedef because we don't want to show
3234 // the underlying type in the diagnostic.
3235 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseaee34382012-09-05 22:56:26 +00003236
Jordan Rose0e5badd2012-12-05 18:44:49 +00003237 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3238 << Name << IntendedTy
3239 << E->getSourceRange(),
3240 E->getLocStart(), /*IsStringLocation=*/false,
3241 SpecRange, Hints);
3242 } else {
3243 // In this case, the expression could be printed using a different
3244 // specifier, but we've decided that the specifier is probably correct
3245 // and we should cast instead. Just use the normal warning message.
3246 EmitFormatDiagnostic(
3247 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3248 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3249 << E->getSourceRange(),
3250 E->getLocStart(), /*IsStringLocation*/false,
3251 SpecRange, Hints);
3252 }
Jordan Roseaee34382012-09-05 22:56:26 +00003253 }
Jordan Rose22b74712012-09-05 22:56:19 +00003254 } else {
3255 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3256 SpecifierLen);
3257 // Since the warning for passing non-POD types to variadic functions
3258 // was deferred until now, we emit a warning for non-POD
3259 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003260 switch (S.isValidVarArgType(ExprTy)) {
3261 case Sema::VAK_Valid:
3262 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003263 EmitFormatDiagnostic(
Richard Smithd7293d72013-08-05 18:49:43 +00003264 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3265 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3266 << CSR
3267 << E->getSourceRange(),
3268 E->getLocStart(), /*IsStringLocation*/false, CSR);
3269 break;
3270
3271 case Sema::VAK_Undefined:
3272 EmitFormatDiagnostic(
3273 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003274 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003275 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003276 << CallType
3277 << AT.getRepresentativeTypeName(S.Context)
3278 << CSR
3279 << E->getSourceRange(),
3280 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003281 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003282 break;
3283
3284 case Sema::VAK_Invalid:
3285 if (ExprTy->isObjCObjectType())
3286 EmitFormatDiagnostic(
3287 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3288 << S.getLangOpts().CPlusPlus11
3289 << ExprTy
3290 << CallType
3291 << AT.getRepresentativeTypeName(S.Context)
3292 << CSR
3293 << E->getSourceRange(),
3294 E->getLocStart(), /*IsStringLocation*/false, CSR);
3295 else
3296 // FIXME: If this is an initializer list, suggest removing the braces
3297 // or inserting a cast to the target type.
3298 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3299 << isa<InitListExpr>(E) << ExprTy << CallType
3300 << AT.getRepresentativeTypeName(S.Context)
3301 << E->getSourceRange();
3302 break;
3303 }
3304
3305 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3306 "format string specifier index out of range");
3307 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003308 }
3309
Ted Kremenekab278de2010-01-28 23:39:18 +00003310 return true;
3311}
3312
Ted Kremenek02087932010-07-16 02:11:22 +00003313//===--- CHECK: Scanf format string checking ------------------------------===//
3314
3315namespace {
3316class CheckScanfHandler : public CheckFormatHandler {
3317public:
3318 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3319 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003320 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003321 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003322 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003323 Sema::VariadicCallType CallType,
3324 llvm::SmallBitVector &CheckedVarArgs)
3325 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3326 numDataArgs, beg, hasVAListArg,
3327 Args, formatIdx, inFunctionCall, CallType,
3328 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003329 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003330
3331 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3332 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003333 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003334
3335 bool HandleInvalidScanfConversionSpecifier(
3336 const analyze_scanf::ScanfSpecifier &FS,
3337 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003338 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003339
Craig Toppere14c0f82014-03-12 04:55:44 +00003340 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003341};
Ted Kremenek019d2242010-01-29 01:50:07 +00003342}
Ted Kremenekab278de2010-01-28 23:39:18 +00003343
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003344void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3345 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003346 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3347 getLocationOfByte(end), /*IsStringLocation*/true,
3348 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003349}
3350
Ted Kremenekce815422010-07-19 21:25:57 +00003351bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3352 const analyze_scanf::ScanfSpecifier &FS,
3353 const char *startSpecifier,
3354 unsigned specifierLen) {
3355
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003356 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003357 FS.getConversionSpecifier();
3358
3359 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3360 getLocationOfByte(CS.getStart()),
3361 startSpecifier, specifierLen,
3362 CS.getStart(), CS.getLength());
3363}
3364
Ted Kremenek02087932010-07-16 02:11:22 +00003365bool CheckScanfHandler::HandleScanfSpecifier(
3366 const analyze_scanf::ScanfSpecifier &FS,
3367 const char *startSpecifier,
3368 unsigned specifierLen) {
3369
3370 using namespace analyze_scanf;
3371 using namespace analyze_format_string;
3372
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003373 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003374
Ted Kremenek6cd69422010-07-19 22:01:06 +00003375 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3376 // be used to decide if we are using positional arguments consistently.
3377 if (FS.consumesDataArgument()) {
3378 if (atFirstArg) {
3379 atFirstArg = false;
3380 usesPositionalArgs = FS.usesPositionalArg();
3381 }
3382 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003383 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3384 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003385 return false;
3386 }
Ted Kremenek02087932010-07-16 02:11:22 +00003387 }
3388
3389 // Check if the field with is non-zero.
3390 const OptionalAmount &Amt = FS.getFieldWidth();
3391 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3392 if (Amt.getConstantAmount() == 0) {
3393 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3394 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003395 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3396 getLocationOfByte(Amt.getStart()),
3397 /*IsStringLocation*/true, R,
3398 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003399 }
3400 }
3401
3402 if (!FS.consumesDataArgument()) {
3403 // FIXME: Technically specifying a precision or field width here
3404 // makes no sense. Worth issuing a warning at some point.
3405 return true;
3406 }
3407
3408 // Consume the argument.
3409 unsigned argIndex = FS.getArgIndex();
3410 if (argIndex < NumDataArgs) {
3411 // The check to see if the argIndex is valid will come later.
3412 // We set the bit here because we may exit early from this
3413 // function if we encounter some other error.
3414 CoveredArgs.set(argIndex);
3415 }
3416
Ted Kremenek4407ea42010-07-20 20:04:47 +00003417 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003418 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003419 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3420 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003421 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003422 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003423 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003424 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3425 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003426
Jordan Rose92303592012-09-08 04:00:03 +00003427 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3428 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3429
Ted Kremenek02087932010-07-16 02:11:22 +00003430 // The remaining checks depend on the data arguments.
3431 if (HasVAListArg)
3432 return true;
3433
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003434 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003435 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003436
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003437 // Check that the argument type matches the format specifier.
3438 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003439 if (!Ex)
3440 return true;
3441
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003442 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3443 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003444 ScanfSpecifier fixedFS = FS;
Jordan Rose177b0a32014-03-20 03:32:39 +00003445 bool success = fixedFS.fixType(Ex->getType(),
3446 Ex->IgnoreImpCasts()->getType(),
3447 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003448
3449 if (success) {
3450 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003451 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003452 llvm::raw_svector_ostream os(buf);
3453 fixedFS.toString(os);
3454
3455 EmitFormatDiagnostic(
3456 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003457 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003458 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003459 Ex->getLocStart(),
3460 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003461 getSpecifierRange(startSpecifier, specifierLen),
3462 FixItHint::CreateReplacement(
3463 getSpecifierRange(startSpecifier, specifierLen),
3464 os.str()));
3465 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003466 EmitFormatDiagnostic(
3467 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003468 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003469 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003470 Ex->getLocStart(),
3471 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003472 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003473 }
3474 }
3475
Ted Kremenek02087932010-07-16 02:11:22 +00003476 return true;
3477}
3478
3479void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003480 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003481 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003482 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003483 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003484 bool inFunctionCall, VariadicCallType CallType,
3485 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003486
Ted Kremenekab278de2010-01-28 23:39:18 +00003487 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003488 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003489 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003490 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003491 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3492 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003493 return;
3494 }
Ted Kremenek02087932010-07-16 02:11:22 +00003495
Ted Kremenekab278de2010-01-28 23:39:18 +00003496 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003497 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003498 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003499 // Account for cases where the string literal is truncated in a declaration.
3500 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3501 assert(T && "String literal not of constant array type!");
3502 size_t TypeSize = T->getSize().getZExtValue();
3503 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003504 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003505
3506 // Emit a warning if the string literal is truncated and does not contain an
3507 // embedded null character.
3508 if (TypeSize <= StrRef.size() &&
3509 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3510 CheckFormatHandler::EmitFormatDiagnostic(
3511 *this, inFunctionCall, Args[format_idx],
3512 PDiag(diag::warn_printf_format_string_not_null_terminated),
3513 FExpr->getLocStart(),
3514 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3515 return;
3516 }
3517
Ted Kremenekab278de2010-01-28 23:39:18 +00003518 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00003519 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003520 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003521 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003522 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3523 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003524 return;
3525 }
Ted Kremenek02087932010-07-16 02:11:22 +00003526
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003527 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00003528 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003529 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003530 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003531 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003532
Hans Wennborg23926bd2011-12-15 10:25:47 +00003533 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003534 getLangOpts(),
3535 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003536 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003537 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003538 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003539 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003540 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003541
Hans Wennborg23926bd2011-12-15 10:25:47 +00003542 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003543 getLangOpts(),
3544 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003545 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003546 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00003547}
3548
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003549//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
3550
3551// Returns the related absolute value function that is larger, of 0 if one
3552// does not exist.
3553static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
3554 switch (AbsFunction) {
3555 default:
3556 return 0;
3557
3558 case Builtin::BI__builtin_abs:
3559 return Builtin::BI__builtin_labs;
3560 case Builtin::BI__builtin_labs:
3561 return Builtin::BI__builtin_llabs;
3562 case Builtin::BI__builtin_llabs:
3563 return 0;
3564
3565 case Builtin::BI__builtin_fabsf:
3566 return Builtin::BI__builtin_fabs;
3567 case Builtin::BI__builtin_fabs:
3568 return Builtin::BI__builtin_fabsl;
3569 case Builtin::BI__builtin_fabsl:
3570 return 0;
3571
3572 case Builtin::BI__builtin_cabsf:
3573 return Builtin::BI__builtin_cabs;
3574 case Builtin::BI__builtin_cabs:
3575 return Builtin::BI__builtin_cabsl;
3576 case Builtin::BI__builtin_cabsl:
3577 return 0;
3578
3579 case Builtin::BIabs:
3580 return Builtin::BIlabs;
3581 case Builtin::BIlabs:
3582 return Builtin::BIllabs;
3583 case Builtin::BIllabs:
3584 return 0;
3585
3586 case Builtin::BIfabsf:
3587 return Builtin::BIfabs;
3588 case Builtin::BIfabs:
3589 return Builtin::BIfabsl;
3590 case Builtin::BIfabsl:
3591 return 0;
3592
3593 case Builtin::BIcabsf:
3594 return Builtin::BIcabs;
3595 case Builtin::BIcabs:
3596 return Builtin::BIcabsl;
3597 case Builtin::BIcabsl:
3598 return 0;
3599 }
3600}
3601
3602// Returns the argument type of the absolute value function.
3603static QualType getAbsoluteValueArgumentType(ASTContext &Context,
3604 unsigned AbsType) {
3605 if (AbsType == 0)
3606 return QualType();
3607
3608 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3609 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
3610 if (Error != ASTContext::GE_None)
3611 return QualType();
3612
3613 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
3614 if (!FT)
3615 return QualType();
3616
3617 if (FT->getNumParams() != 1)
3618 return QualType();
3619
3620 return FT->getParamType(0);
3621}
3622
3623// Returns the best absolute value function, or zero, based on type and
3624// current absolute value function.
3625static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
3626 unsigned AbsFunctionKind) {
3627 unsigned BestKind = 0;
3628 uint64_t ArgSize = Context.getTypeSize(ArgType);
3629 for (unsigned Kind = AbsFunctionKind; Kind != 0;
3630 Kind = getLargerAbsoluteValueFunction(Kind)) {
3631 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
3632 if (Context.getTypeSize(ParamType) >= ArgSize) {
3633 if (BestKind == 0)
3634 BestKind = Kind;
3635 else if (Context.hasSameType(ParamType, ArgType)) {
3636 BestKind = Kind;
3637 break;
3638 }
3639 }
3640 }
3641 return BestKind;
3642}
3643
3644enum AbsoluteValueKind {
3645 AVK_Integer,
3646 AVK_Floating,
3647 AVK_Complex
3648};
3649
3650static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
3651 if (T->isIntegralOrEnumerationType())
3652 return AVK_Integer;
3653 if (T->isRealFloatingType())
3654 return AVK_Floating;
3655 if (T->isAnyComplexType())
3656 return AVK_Complex;
3657
3658 llvm_unreachable("Type not integer, floating, or complex");
3659}
3660
3661// Changes the absolute value function to a different type. Preserves whether
3662// the function is a builtin.
3663static unsigned changeAbsFunction(unsigned AbsKind,
3664 AbsoluteValueKind ValueKind) {
3665 switch (ValueKind) {
3666 case AVK_Integer:
3667 switch (AbsKind) {
3668 default:
3669 return 0;
3670 case Builtin::BI__builtin_fabsf:
3671 case Builtin::BI__builtin_fabs:
3672 case Builtin::BI__builtin_fabsl:
3673 case Builtin::BI__builtin_cabsf:
3674 case Builtin::BI__builtin_cabs:
3675 case Builtin::BI__builtin_cabsl:
3676 return Builtin::BI__builtin_abs;
3677 case Builtin::BIfabsf:
3678 case Builtin::BIfabs:
3679 case Builtin::BIfabsl:
3680 case Builtin::BIcabsf:
3681 case Builtin::BIcabs:
3682 case Builtin::BIcabsl:
3683 return Builtin::BIabs;
3684 }
3685 case AVK_Floating:
3686 switch (AbsKind) {
3687 default:
3688 return 0;
3689 case Builtin::BI__builtin_abs:
3690 case Builtin::BI__builtin_labs:
3691 case Builtin::BI__builtin_llabs:
3692 case Builtin::BI__builtin_cabsf:
3693 case Builtin::BI__builtin_cabs:
3694 case Builtin::BI__builtin_cabsl:
3695 return Builtin::BI__builtin_fabsf;
3696 case Builtin::BIabs:
3697 case Builtin::BIlabs:
3698 case Builtin::BIllabs:
3699 case Builtin::BIcabsf:
3700 case Builtin::BIcabs:
3701 case Builtin::BIcabsl:
3702 return Builtin::BIfabsf;
3703 }
3704 case AVK_Complex:
3705 switch (AbsKind) {
3706 default:
3707 return 0;
3708 case Builtin::BI__builtin_abs:
3709 case Builtin::BI__builtin_labs:
3710 case Builtin::BI__builtin_llabs:
3711 case Builtin::BI__builtin_fabsf:
3712 case Builtin::BI__builtin_fabs:
3713 case Builtin::BI__builtin_fabsl:
3714 return Builtin::BI__builtin_cabsf;
3715 case Builtin::BIabs:
3716 case Builtin::BIlabs:
3717 case Builtin::BIllabs:
3718 case Builtin::BIfabsf:
3719 case Builtin::BIfabs:
3720 case Builtin::BIfabsl:
3721 return Builtin::BIcabsf;
3722 }
3723 }
3724 llvm_unreachable("Unable to convert function");
3725}
3726
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00003727static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003728 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
3729 if (!FnInfo)
3730 return 0;
3731
3732 switch (FDecl->getBuiltinID()) {
3733 default:
3734 return 0;
3735 case Builtin::BI__builtin_abs:
3736 case Builtin::BI__builtin_fabs:
3737 case Builtin::BI__builtin_fabsf:
3738 case Builtin::BI__builtin_fabsl:
3739 case Builtin::BI__builtin_labs:
3740 case Builtin::BI__builtin_llabs:
3741 case Builtin::BI__builtin_cabs:
3742 case Builtin::BI__builtin_cabsf:
3743 case Builtin::BI__builtin_cabsl:
3744 case Builtin::BIabs:
3745 case Builtin::BIlabs:
3746 case Builtin::BIllabs:
3747 case Builtin::BIfabs:
3748 case Builtin::BIfabsf:
3749 case Builtin::BIfabsl:
3750 case Builtin::BIcabs:
3751 case Builtin::BIcabsf:
3752 case Builtin::BIcabsl:
3753 return FDecl->getBuiltinID();
3754 }
3755 llvm_unreachable("Unknown Builtin type");
3756}
3757
3758// If the replacement is valid, emit a note with replacement function.
3759// Additionally, suggest including the proper header if not already included.
3760static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00003761 unsigned AbsKind, QualType ArgType) {
3762 bool EmitHeaderHint = true;
3763 const char *HeaderName = 0;
3764 const char *FunctionName = 0;
3765 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
3766 FunctionName = "std::abs";
3767 if (ArgType->isIntegralOrEnumerationType()) {
3768 HeaderName = "cstdlib";
3769 } else if (ArgType->isRealFloatingType()) {
3770 HeaderName = "cmath";
3771 } else {
3772 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003773 }
Richard Trieubeffb832014-04-15 23:47:53 +00003774
3775 // Lookup all std::abs
3776 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00003777 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00003778 R.suppressDiagnostics();
3779 S.LookupQualifiedName(R, Std);
3780
3781 for (const auto *I : R) {
3782 const FunctionDecl *FDecl = 0;
3783 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
3784 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
3785 } else {
3786 FDecl = dyn_cast<FunctionDecl>(I);
3787 }
3788 if (!FDecl)
3789 continue;
3790
3791 // Found std::abs(), check that they are the right ones.
3792 if (FDecl->getNumParams() != 1)
3793 continue;
3794
3795 // Check that the parameter type can handle the argument.
3796 QualType ParamType = FDecl->getParamDecl(0)->getType();
3797 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
3798 S.Context.getTypeSize(ArgType) <=
3799 S.Context.getTypeSize(ParamType)) {
3800 // Found a function, don't need the header hint.
3801 EmitHeaderHint = false;
3802 break;
3803 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003804 }
Richard Trieubeffb832014-04-15 23:47:53 +00003805 }
3806 } else {
3807 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
3808 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
3809
3810 if (HeaderName) {
3811 DeclarationName DN(&S.Context.Idents.get(FunctionName));
3812 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
3813 R.suppressDiagnostics();
3814 S.LookupName(R, S.getCurScope());
3815
3816 if (R.isSingleResult()) {
3817 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3818 if (FD && FD->getBuiltinID() == AbsKind) {
3819 EmitHeaderHint = false;
3820 } else {
3821 return;
3822 }
3823 } else if (!R.empty()) {
3824 return;
3825 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003826 }
3827 }
3828
3829 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00003830 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003831
Richard Trieubeffb832014-04-15 23:47:53 +00003832 if (!HeaderName)
3833 return;
3834
3835 if (!EmitHeaderHint)
3836 return;
3837
3838 S.Diag(Loc, diag::note_please_include_header) << HeaderName << FunctionName;
3839}
3840
3841static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
3842 if (!FDecl)
3843 return false;
3844
3845 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
3846 return false;
3847
3848 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
3849
3850 while (ND && ND->isInlineNamespace()) {
3851 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003852 }
Richard Trieubeffb832014-04-15 23:47:53 +00003853
3854 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
3855 return false;
3856
3857 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
3858 return false;
3859
3860 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003861}
3862
3863// Warn when using the wrong abs() function.
3864void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
3865 const FunctionDecl *FDecl,
3866 IdentifierInfo *FnInfo) {
3867 if (Call->getNumArgs() != 1)
3868 return;
3869
3870 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00003871 bool IsStdAbs = IsFunctionStdAbs(FDecl);
3872 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003873 return;
3874
3875 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
3876 QualType ParamType = Call->getArg(0)->getType();
3877
3878 // Unsigned types can not be negative. Suggest to drop the absolute value
3879 // function.
3880 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00003881 const char *FunctionName =
3882 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003883 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
3884 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00003885 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003886 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
3887 return;
3888 }
3889
Richard Trieubeffb832014-04-15 23:47:53 +00003890 // std::abs has overloads which prevent most of the absolute value problems
3891 // from occurring.
3892 if (IsStdAbs)
3893 return;
3894
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003895 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
3896 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
3897
3898 // The argument and parameter are the same kind. Check if they are the right
3899 // size.
3900 if (ArgValueKind == ParamValueKind) {
3901 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
3902 return;
3903
3904 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
3905 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
3906 << FDecl << ArgType << ParamType;
3907
3908 if (NewAbsKind == 0)
3909 return;
3910
3911 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00003912 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003913 return;
3914 }
3915
3916 // ArgValueKind != ParamValueKind
3917 // The wrong type of absolute value function was used. Attempt to find the
3918 // proper one.
3919 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
3920 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
3921 if (NewAbsKind == 0)
3922 return;
3923
3924 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
3925 << FDecl << ParamValueKind << ArgValueKind;
3926
3927 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00003928 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003929 return;
3930}
3931
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003932//===--- CHECK: Standard memory functions ---------------------------------===//
3933
Nico Weber0e6daef2013-12-26 23:38:39 +00003934/// \brief Takes the expression passed to the size_t parameter of functions
3935/// such as memcmp, strncat, etc and warns if it's a comparison.
3936///
3937/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
3938static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
3939 IdentifierInfo *FnName,
3940 SourceLocation FnLoc,
3941 SourceLocation RParenLoc) {
3942 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
3943 if (!Size)
3944 return false;
3945
3946 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
3947 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
3948 return false;
3949
Nico Weber0e6daef2013-12-26 23:38:39 +00003950 SourceRange SizeRange = Size->getSourceRange();
3951 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
3952 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00003953 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00003954 << FnName << FixItHint::CreateInsertion(
3955 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00003956 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00003957 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00003958 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00003959 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
3960 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00003961
3962 return true;
3963}
3964
Douglas Gregora74926b2011-05-03 20:05:22 +00003965/// \brief Determine whether the given type is a dynamic class type (e.g.,
3966/// whether it has a vtable).
3967static bool isDynamicClassType(QualType T) {
3968 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3969 if (CXXRecordDecl *Definition = Record->getDefinition())
3970 if (Definition->isDynamicClass())
3971 return true;
3972
3973 return false;
3974}
3975
Chandler Carruth889ed862011-06-21 23:04:20 +00003976/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003977/// otherwise returns NULL.
3978static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00003979 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003980 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3981 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3982 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00003983
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003984 return 0;
3985}
3986
Chandler Carruth889ed862011-06-21 23:04:20 +00003987/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003988static QualType getSizeOfArgType(const Expr* E) {
3989 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3990 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3991 if (SizeOf->getKind() == clang::UETT_SizeOf)
3992 return SizeOf->getTypeOfArgument();
3993
3994 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00003995}
3996
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003997/// \brief Check for dangerous or invalid arguments to memset().
3998///
Chandler Carruthac687262011-06-03 06:23:57 +00003999/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004000/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4001/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004002///
4003/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004004void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004005 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004006 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004007 assert(BId != 0);
4008
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004009 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004010 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004011 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004012 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004013 return;
4014
Anna Zaks22122702012-01-17 00:37:07 +00004015 unsigned LastArg = (BId == Builtin::BImemset ||
4016 BId == Builtin::BIstrndup ? 1 : 2);
4017 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004018 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004019
Nico Weber0e6daef2013-12-26 23:38:39 +00004020 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4021 Call->getLocStart(), Call->getRParenLoc()))
4022 return;
4023
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004024 // We have special checking when the length is a sizeof expression.
4025 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4026 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4027 llvm::FoldingSetNodeID SizeOfArgID;
4028
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004029 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4030 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004031 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004032
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004033 QualType DestTy = Dest->getType();
4034 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4035 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004036
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004037 // Never warn about void type pointers. This can be used to suppress
4038 // false positives.
4039 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004040 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004041
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004042 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4043 // actually comparing the expressions for equality. Because computing the
4044 // expression IDs can be expensive, we only do this if the diagnostic is
4045 // enabled.
4046 if (SizeOfArg &&
4047 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
4048 SizeOfArg->getExprLoc())) {
4049 // We only compute IDs for expressions if the warning is enabled, and
4050 // cache the sizeof arg's ID.
4051 if (SizeOfArgID == llvm::FoldingSetNodeID())
4052 SizeOfArg->Profile(SizeOfArgID, Context, true);
4053 llvm::FoldingSetNodeID DestID;
4054 Dest->Profile(DestID, Context, true);
4055 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004056 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4057 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004058 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004059 StringRef ReadableName = FnName->getName();
4060
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004061 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004062 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004063 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004064 if (!PointeeTy->isIncompleteType() &&
4065 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004066 ActionIdx = 2; // If the pointee's size is sizeof(char),
4067 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004068
4069 // If the function is defined as a builtin macro, do not show macro
4070 // expansion.
4071 SourceLocation SL = SizeOfArg->getExprLoc();
4072 SourceRange DSR = Dest->getSourceRange();
4073 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004074 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004075
4076 if (SM.isMacroArgExpansion(SL)) {
4077 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4078 SL = SM.getSpellingLoc(SL);
4079 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4080 SM.getSpellingLoc(DSR.getEnd()));
4081 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4082 SM.getSpellingLoc(SSR.getEnd()));
4083 }
4084
Anna Zaksd08d9152012-05-30 23:14:52 +00004085 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004086 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004087 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004088 << PointeeTy
4089 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004090 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004091 << SSR);
4092 DiagRuntimeBehavior(SL, SizeOfArg,
4093 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4094 << ActionIdx
4095 << SSR);
4096
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004097 break;
4098 }
4099 }
4100
4101 // Also check for cases where the sizeof argument is the exact same
4102 // type as the memory argument, and where it points to a user-defined
4103 // record type.
4104 if (SizeOfArgTy != QualType()) {
4105 if (PointeeTy->isRecordType() &&
4106 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4107 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4108 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4109 << FnName << SizeOfArgTy << ArgIdx
4110 << PointeeTy << Dest->getSourceRange()
4111 << LenExpr->getSourceRange());
4112 break;
4113 }
Nico Weberc5e73862011-06-14 16:14:58 +00004114 }
4115
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004116 // Always complain about dynamic classes.
Anna Zaks22122702012-01-17 00:37:07 +00004117 if (isDynamicClassType(PointeeTy)) {
4118
4119 unsigned OperationType = 0;
4120 // "overwritten" if we're warning about the destination for any call
4121 // but memcmp; otherwise a verb appropriate to the call.
4122 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4123 if (BId == Builtin::BImemcpy)
4124 OperationType = 1;
4125 else if(BId == Builtin::BImemmove)
4126 OperationType = 2;
4127 else if (BId == Builtin::BImemcmp)
4128 OperationType = 3;
4129 }
4130
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004131 DiagRuntimeBehavior(
4132 Dest->getExprLoc(), Dest,
4133 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004134 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaks201d4892012-01-13 21:52:01 +00004135 << FnName << PointeeTy
Anna Zaks22122702012-01-17 00:37:07 +00004136 << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004137 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004138 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4139 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004140 DiagRuntimeBehavior(
4141 Dest->getExprLoc(), Dest,
4142 PDiag(diag::warn_arc_object_memaccess)
4143 << ArgIdx << FnName << PointeeTy
4144 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004145 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004146 continue;
John McCall31168b02011-06-15 23:02:42 +00004147
4148 DiagRuntimeBehavior(
4149 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004150 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004151 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4152 break;
4153 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004154 }
4155}
4156
Ted Kremenek6865f772011-08-18 20:55:45 +00004157// A little helper routine: ignore addition and subtraction of integer literals.
4158// This intentionally does not ignore all integer constant expressions because
4159// we don't want to remove sizeof().
4160static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4161 Ex = Ex->IgnoreParenCasts();
4162
4163 for (;;) {
4164 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4165 if (!BO || !BO->isAdditiveOp())
4166 break;
4167
4168 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4169 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4170
4171 if (isa<IntegerLiteral>(RHS))
4172 Ex = LHS;
4173 else if (isa<IntegerLiteral>(LHS))
4174 Ex = RHS;
4175 else
4176 break;
4177 }
4178
4179 return Ex;
4180}
4181
Anna Zaks13b08572012-08-08 21:42:23 +00004182static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4183 ASTContext &Context) {
4184 // Only handle constant-sized or VLAs, but not flexible members.
4185 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4186 // Only issue the FIXIT for arrays of size > 1.
4187 if (CAT->getSize().getSExtValue() <= 1)
4188 return false;
4189 } else if (!Ty->isVariableArrayType()) {
4190 return false;
4191 }
4192 return true;
4193}
4194
Ted Kremenek6865f772011-08-18 20:55:45 +00004195// Warn if the user has made the 'size' argument to strlcpy or strlcat
4196// be the size of the source, instead of the destination.
4197void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4198 IdentifierInfo *FnName) {
4199
4200 // Don't crash if the user has the wrong number of arguments
4201 if (Call->getNumArgs() != 3)
4202 return;
4203
4204 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4205 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
4206 const Expr *CompareWithSrc = NULL;
Nico Weber0e6daef2013-12-26 23:38:39 +00004207
4208 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4209 Call->getLocStart(), Call->getRParenLoc()))
4210 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004211
4212 // Look for 'strlcpy(dst, x, sizeof(x))'
4213 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4214 CompareWithSrc = Ex;
4215 else {
4216 // Look for 'strlcpy(dst, x, strlen(x))'
4217 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004218 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4219 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004220 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4221 }
4222 }
4223
4224 if (!CompareWithSrc)
4225 return;
4226
4227 // Determine if the argument to sizeof/strlen is equal to the source
4228 // argument. In principle there's all kinds of things you could do
4229 // here, for instance creating an == expression and evaluating it with
4230 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4231 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4232 if (!SrcArgDRE)
4233 return;
4234
4235 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4236 if (!CompareWithSrcDRE ||
4237 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4238 return;
4239
4240 const Expr *OriginalSizeArg = Call->getArg(2);
4241 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4242 << OriginalSizeArg->getSourceRange() << FnName;
4243
4244 // Output a FIXIT hint if the destination is an array (rather than a
4245 // pointer to an array). This could be enhanced to handle some
4246 // pointers if we know the actual size, like if DstArg is 'array+2'
4247 // we could say 'sizeof(array)-2'.
4248 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004249 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004250 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004251
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004252 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004253 llvm::raw_svector_ostream OS(sizeString);
4254 OS << "sizeof(";
Richard Smith235341b2012-08-16 03:56:14 +00004255 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004256 OS << ")";
4257
4258 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4259 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4260 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004261}
4262
Anna Zaks314cd092012-02-01 19:08:57 +00004263/// Check if two expressions refer to the same declaration.
4264static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4265 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4266 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4267 return D1->getDecl() == D2->getDecl();
4268 return false;
4269}
4270
4271static const Expr *getStrlenExprArg(const Expr *E) {
4272 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4273 const FunctionDecl *FD = CE->getDirectCallee();
4274 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
4275 return 0;
4276 return CE->getArg(0)->IgnoreParenCasts();
4277 }
4278 return 0;
4279}
4280
4281// Warn on anti-patterns as the 'size' argument to strncat.
4282// The correct size argument should look like following:
4283// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4284void Sema::CheckStrncatArguments(const CallExpr *CE,
4285 IdentifierInfo *FnName) {
4286 // Don't crash if the user has the wrong number of arguments.
4287 if (CE->getNumArgs() < 3)
4288 return;
4289 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4290 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4291 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4292
Nico Weber0e6daef2013-12-26 23:38:39 +00004293 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4294 CE->getRParenLoc()))
4295 return;
4296
Anna Zaks314cd092012-02-01 19:08:57 +00004297 // Identify common expressions, which are wrongly used as the size argument
4298 // to strncat and may lead to buffer overflows.
4299 unsigned PatternType = 0;
4300 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4301 // - sizeof(dst)
4302 if (referToTheSameDecl(SizeOfArg, DstArg))
4303 PatternType = 1;
4304 // - sizeof(src)
4305 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4306 PatternType = 2;
4307 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4308 if (BE->getOpcode() == BO_Sub) {
4309 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4310 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4311 // - sizeof(dst) - strlen(dst)
4312 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4313 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4314 PatternType = 1;
4315 // - sizeof(src) - (anything)
4316 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4317 PatternType = 2;
4318 }
4319 }
4320
4321 if (PatternType == 0)
4322 return;
4323
Anna Zaks5069aa32012-02-03 01:27:37 +00004324 // Generate the diagnostic.
4325 SourceLocation SL = LenArg->getLocStart();
4326 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004327 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00004328
4329 // If the function is defined as a builtin macro, do not show macro expansion.
4330 if (SM.isMacroArgExpansion(SL)) {
4331 SL = SM.getSpellingLoc(SL);
4332 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4333 SM.getSpellingLoc(SR.getEnd()));
4334 }
4335
Anna Zaks13b08572012-08-08 21:42:23 +00004336 // Check if the destination is an array (rather than a pointer to an array).
4337 QualType DstTy = DstArg->getType();
4338 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4339 Context);
4340 if (!isKnownSizeArray) {
4341 if (PatternType == 1)
4342 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4343 else
4344 Diag(SL, diag::warn_strncat_src_size) << SR;
4345 return;
4346 }
4347
Anna Zaks314cd092012-02-01 19:08:57 +00004348 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004349 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004350 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004351 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004352
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004353 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004354 llvm::raw_svector_ostream OS(sizeString);
4355 OS << "sizeof(";
Richard Smith235341b2012-08-16 03:56:14 +00004356 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004357 OS << ") - ";
4358 OS << "strlen(";
Richard Smith235341b2012-08-16 03:56:14 +00004359 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004360 OS << ") - 1";
4361
Anna Zaks5069aa32012-02-03 01:27:37 +00004362 Diag(SL, diag::note_strncat_wrong_size)
4363 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004364}
4365
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004366//===--- CHECK: Return Address of Stack Variable --------------------------===//
4367
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004368static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4369 Decl *ParentDecl);
4370static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4371 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004372
4373/// CheckReturnStackAddr - Check if a return statement returns the address
4374/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004375static void
4376CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4377 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004378
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004379 Expr *stackE = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004380 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004381
4382 // Perform checking for returned stack addresses, local blocks,
4383 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004384 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004385 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004386 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stump12b8ce12009-08-04 21:02:39 +00004387 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004388 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004389 }
4390
4391 if (stackE == 0)
4392 return; // Nothing suspicious was found.
4393
4394 SourceLocation diagLoc;
4395 SourceRange diagRange;
4396 if (refVars.empty()) {
4397 diagLoc = stackE->getLocStart();
4398 diagRange = stackE->getSourceRange();
4399 } else {
4400 // We followed through a reference variable. 'stackE' contains the
4401 // problematic expression but we will warn at the return statement pointing
4402 // at the reference variable. We will later display the "trail" of
4403 // reference variables using notes.
4404 diagLoc = refVars[0]->getLocStart();
4405 diagRange = refVars[0]->getSourceRange();
4406 }
4407
4408 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004409 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004410 : diag::warn_ret_stack_addr)
4411 << DR->getDecl()->getDeclName() << diagRange;
4412 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004413 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004414 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004415 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004416 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004417 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4418 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004419 << diagRange;
4420 }
4421
4422 // Display the "trail" of reference variables that we followed until we
4423 // found the problematic expression using notes.
4424 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4425 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4426 // If this var binds to another reference var, show the range of the next
4427 // var, otherwise the var binds to the problematic expression, in which case
4428 // show the range of the expression.
4429 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4430 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004431 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4432 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004433 }
4434}
4435
4436/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4437/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004438/// to a location on the stack, a local block, an address of a label, or a
4439/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004440/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004441/// encounter a subexpression that (1) clearly does not lead to one of the
4442/// above problematic expressions (2) is something we cannot determine leads to
4443/// a problematic expression based on such local checking.
4444///
4445/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4446/// the expression that they point to. Such variables are added to the
4447/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004448///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004449/// EvalAddr processes expressions that are pointers that are used as
4450/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004451/// At the base case of the recursion is a check for the above problematic
4452/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004453///
4454/// This implementation handles:
4455///
4456/// * pointer-to-pointer casts
4457/// * implicit conversions from array references to pointers
4458/// * taking the address of fields
4459/// * arbitrary interplay between "&" and "*" operators
4460/// * pointer arithmetic from an address of a stack variable
4461/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004462static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4463 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004464 if (E->isTypeDependent())
Craig Topper47005942013-08-02 05:10:31 +00004465 return NULL;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004466
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004467 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00004468 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004469 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004470 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00004471 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00004472
Peter Collingbourne91147592011-04-15 00:35:48 +00004473 E = E->IgnoreParens();
4474
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004475 // Our "symbolic interpreter" is just a dispatch off the currently
4476 // viewed AST node. We then recursively traverse the AST by calling
4477 // EvalAddr and EvalVal appropriately.
4478 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004479 case Stmt::DeclRefExprClass: {
4480 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4481
Richard Smith40f08eb2014-01-30 22:05:38 +00004482 // If we leave the immediate function, the lifetime isn't about to end.
4483 if (DR->refersToEnclosingLocal())
4484 return 0;
4485
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004486 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4487 // If this is a reference variable, follow through to the expression that
4488 // it points to.
4489 if (V->hasLocalStorage() &&
4490 V->getType()->isReferenceType() && V->hasInit()) {
4491 // Add the reference variable to the "trail".
4492 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004493 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004494 }
4495
4496 return NULL;
4497 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004498
Chris Lattner934edb22007-12-28 05:31:15 +00004499 case Stmt::UnaryOperatorClass: {
4500 // The only unary operator that make sense to handle here
4501 // is AddrOf. All others don't make sense as pointers.
4502 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004503
John McCalle3027922010-08-25 11:45:40 +00004504 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004505 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004506 else
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004507 return NULL;
4508 }
Mike Stump11289f42009-09-09 15:08:12 +00004509
Chris Lattner934edb22007-12-28 05:31:15 +00004510 case Stmt::BinaryOperatorClass: {
4511 // Handle pointer arithmetic. All other binary operators are not valid
4512 // in this context.
4513 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00004514 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00004515
John McCalle3027922010-08-25 11:45:40 +00004516 if (op != BO_Add && op != BO_Sub)
Chris Lattner934edb22007-12-28 05:31:15 +00004517 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00004518
Chris Lattner934edb22007-12-28 05:31:15 +00004519 Expr *Base = B->getLHS();
4520
4521 // Determine which argument is the real pointer base. It could be
4522 // the RHS argument instead of the LHS.
4523 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00004524
Chris Lattner934edb22007-12-28 05:31:15 +00004525 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004526 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004527 }
Steve Naroff2752a172008-09-10 19:17:48 +00004528
Chris Lattner934edb22007-12-28 05:31:15 +00004529 // For conditional operators we need to see if either the LHS or RHS are
4530 // valid DeclRefExpr*s. If one of them is valid, we return it.
4531 case Stmt::ConditionalOperatorClass: {
4532 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004533
Chris Lattner934edb22007-12-28 05:31:15 +00004534 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004535 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4536 if (Expr *LHSExpr = C->getLHS()) {
4537 // In C++, we can have a throw-expression, which has 'void' type.
4538 if (!LHSExpr->getType()->isVoidType())
4539 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004540 return LHS;
4541 }
Chris Lattner934edb22007-12-28 05:31:15 +00004542
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004543 // In C++, we can have a throw-expression, which has 'void' type.
4544 if (C->getRHS()->getType()->isVoidType())
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004545 return 0;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004546
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004547 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004548 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004549
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004550 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00004551 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004552 return E; // local block.
4553 return NULL;
4554
4555 case Stmt::AddrLabelExprClass:
4556 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00004557
John McCall28fc7092011-11-10 05:35:25 +00004558 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004559 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4560 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004561
Ted Kremenekc3b4c522008-08-07 00:49:01 +00004562 // For casts, we need to handle conversions from arrays to
4563 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00004564 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00004565 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00004566 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00004567 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00004568 case Stmt::CXXStaticCastExprClass:
4569 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00004570 case Stmt::CXXConstCastExprClass:
4571 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00004572 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4573 switch (cast<CastExpr>(E)->getCastKind()) {
4574 case CK_BitCast:
4575 case CK_LValueToRValue:
4576 case CK_NoOp:
4577 case CK_BaseToDerived:
4578 case CK_DerivedToBase:
4579 case CK_UncheckedDerivedToBase:
4580 case CK_Dynamic:
4581 case CK_CPointerToObjCPointerCast:
4582 case CK_BlockPointerToObjCPointerCast:
4583 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004584 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004585
4586 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004587 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004588
4589 default:
4590 return 0;
4591 }
Chris Lattner934edb22007-12-28 05:31:15 +00004592 }
Mike Stump11289f42009-09-09 15:08:12 +00004593
Douglas Gregorfe314812011-06-21 17:03:29 +00004594 case Stmt::MaterializeTemporaryExprClass:
4595 if (Expr *Result = EvalAddr(
4596 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004597 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004598 return Result;
4599
4600 return E;
4601
Chris Lattner934edb22007-12-28 05:31:15 +00004602 // Everything else: we simply don't reason about them.
4603 default:
4604 return NULL;
4605 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004606}
Mike Stump11289f42009-09-09 15:08:12 +00004607
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004608
4609/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4610/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004611static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4612 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004613do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004614 // We should only be called for evaluating non-pointer expressions, or
4615 // expressions with a pointer type that are not used as references but instead
4616 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00004617
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004618 // Our "symbolic interpreter" is just a dispatch off the currently
4619 // viewed AST node. We then recursively traverse the AST by calling
4620 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00004621
4622 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004623 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004624 case Stmt::ImplicitCastExprClass: {
4625 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00004626 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004627 E = IE->getSubExpr();
4628 continue;
4629 }
4630 return NULL;
4631 }
4632
John McCall28fc7092011-11-10 05:35:25 +00004633 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004634 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004635
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004636 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004637 // When we hit a DeclRefExpr we are looking at code that refers to a
4638 // variable's name. If it's not a reference variable we check if it has
4639 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004640 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004641
Richard Smith40f08eb2014-01-30 22:05:38 +00004642 // If we leave the immediate function, the lifetime isn't about to end.
4643 if (DR->refersToEnclosingLocal())
4644 return 0;
4645
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004646 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4647 // Check if it refers to itself, e.g. "int& i = i;".
4648 if (V == ParentDecl)
4649 return DR;
4650
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004651 if (V->hasLocalStorage()) {
4652 if (!V->getType()->isReferenceType())
4653 return DR;
4654
4655 // Reference variable, follow through to the expression that
4656 // it points to.
4657 if (V->hasInit()) {
4658 // Add the reference variable to the "trail".
4659 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004660 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004661 }
4662 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004663 }
Mike Stump11289f42009-09-09 15:08:12 +00004664
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004665 return NULL;
4666 }
Mike Stump11289f42009-09-09 15:08:12 +00004667
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004668 case Stmt::UnaryOperatorClass: {
4669 // The only unary operator that make sense to handle here
4670 // is Deref. All others don't resolve to a "name." This includes
4671 // handling all sorts of rvalues passed to a unary operator.
4672 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004673
John McCalle3027922010-08-25 11:45:40 +00004674 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004675 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004676
4677 return NULL;
4678 }
Mike Stump11289f42009-09-09 15:08:12 +00004679
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004680 case Stmt::ArraySubscriptExprClass: {
4681 // Array subscripts are potential references to data on the stack. We
4682 // retrieve the DeclRefExpr* for the array variable if it indeed
4683 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004684 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004685 }
Mike Stump11289f42009-09-09 15:08:12 +00004686
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004687 case Stmt::ConditionalOperatorClass: {
4688 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004689 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004690 ConditionalOperator *C = cast<ConditionalOperator>(E);
4691
Anders Carlsson801c5c72007-11-30 19:04:31 +00004692 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004693 if (Expr *LHSExpr = C->getLHS()) {
4694 // In C++, we can have a throw-expression, which has 'void' type.
4695 if (!LHSExpr->getType()->isVoidType())
4696 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
4697 return LHS;
4698 }
4699
4700 // In C++, we can have a throw-expression, which has 'void' type.
4701 if (C->getRHS()->getType()->isVoidType())
4702 return 0;
Anders Carlsson801c5c72007-11-30 19:04:31 +00004703
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004704 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004705 }
Mike Stump11289f42009-09-09 15:08:12 +00004706
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004707 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00004708 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004709 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004710
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004711 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004712 if (M->isArrow())
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004713 return NULL;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004714
4715 // Check whether the member type is itself a reference, in which case
4716 // we're not going to refer to the member, but to what the member refers to.
4717 if (M->getMemberDecl()->getType()->isReferenceType())
4718 return NULL;
4719
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004720 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004721 }
Mike Stump11289f42009-09-09 15:08:12 +00004722
Douglas Gregorfe314812011-06-21 17:03:29 +00004723 case Stmt::MaterializeTemporaryExprClass:
4724 if (Expr *Result = EvalVal(
4725 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004726 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004727 return Result;
4728
4729 return E;
4730
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004731 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004732 // Check that we don't return or take the address of a reference to a
4733 // temporary. This is only useful in C++.
4734 if (!E->isTypeDependent() && E->isRValue())
4735 return E;
4736
4737 // Everything else: we simply don't reason about them.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004738 return NULL;
4739 }
Ted Kremenekb7861562010-08-04 20:01:07 +00004740} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004741}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004742
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004743void
4744Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
4745 SourceLocation ReturnLoc,
4746 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00004747 const AttrVec *Attrs,
4748 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004749 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
4750
4751 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00004752 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
4753 CheckNonNullExpr(*this, RetValExp))
4754 Diag(ReturnLoc, diag::warn_null_ret)
4755 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00004756
4757 // C++11 [basic.stc.dynamic.allocation]p4:
4758 // If an allocation function declared with a non-throwing
4759 // exception-specification fails to allocate storage, it shall return
4760 // a null pointer. Any other allocation function that fails to allocate
4761 // storage shall indicate failure only by throwing an exception [...]
4762 if (FD) {
4763 OverloadedOperatorKind Op = FD->getOverloadedOperator();
4764 if (Op == OO_New || Op == OO_Array_New) {
4765 const FunctionProtoType *Proto
4766 = FD->getType()->castAs<FunctionProtoType>();
4767 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
4768 CheckNonNullExpr(*this, RetValExp))
4769 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
4770 << FD << getLangOpts().CPlusPlus11;
4771 }
4772 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004773}
4774
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004775//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4776
4777/// Check for comparisons of floating point operands using != and ==.
4778/// Issue a warning if these are no self-comparisons, as they are not likely
4779/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00004780void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00004781 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4782 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004783
4784 // Special case: check for x == x (which is OK).
4785 // Do not emit warnings for such cases.
4786 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4787 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4788 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00004789 return;
Mike Stump11289f42009-09-09 15:08:12 +00004790
4791
Ted Kremenekeda40e22007-11-29 00:59:04 +00004792 // Special case: check for comparisons against literals that can be exactly
4793 // represented by APFloat. In such cases, do not emit a warning. This
4794 // is a heuristic: often comparison against such literals are used to
4795 // detect if a value in a variable has not changed. This clearly can
4796 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00004797 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4798 if (FLL->isExact())
4799 return;
4800 } else
4801 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4802 if (FLR->isExact())
4803 return;
Mike Stump11289f42009-09-09 15:08:12 +00004804
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004805 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00004806 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004807 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004808 return;
Mike Stump11289f42009-09-09 15:08:12 +00004809
David Blaikie1f4ff152012-07-16 20:47:22 +00004810 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004811 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004812 return;
Mike Stump11289f42009-09-09 15:08:12 +00004813
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004814 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00004815 Diag(Loc, diag::warn_floatingpoint_eq)
4816 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004817}
John McCallca01b222010-01-04 23:21:16 +00004818
John McCall70aa5392010-01-06 05:24:50 +00004819//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4820//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00004821
John McCall70aa5392010-01-06 05:24:50 +00004822namespace {
John McCallca01b222010-01-04 23:21:16 +00004823
John McCall70aa5392010-01-06 05:24:50 +00004824/// Structure recording the 'active' range of an integer-valued
4825/// expression.
4826struct IntRange {
4827 /// The number of bits active in the int.
4828 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00004829
John McCall70aa5392010-01-06 05:24:50 +00004830 /// True if the int is known not to have negative values.
4831 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00004832
John McCall70aa5392010-01-06 05:24:50 +00004833 IntRange(unsigned Width, bool NonNegative)
4834 : Width(Width), NonNegative(NonNegative)
4835 {}
John McCallca01b222010-01-04 23:21:16 +00004836
John McCall817d4af2010-11-10 23:38:19 +00004837 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00004838 static IntRange forBoolType() {
4839 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00004840 }
4841
John McCall817d4af2010-11-10 23:38:19 +00004842 /// Returns the range of an opaque value of the given integral type.
4843 static IntRange forValueOfType(ASTContext &C, QualType T) {
4844 return forValueOfCanonicalType(C,
4845 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00004846 }
4847
John McCall817d4af2010-11-10 23:38:19 +00004848 /// Returns the range of an opaque value of a canonical integral type.
4849 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00004850 assert(T->isCanonicalUnqualified());
4851
4852 if (const VectorType *VT = dyn_cast<VectorType>(T))
4853 T = VT->getElementType().getTypePtr();
4854 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4855 T = CT->getElementType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00004856
David Majnemer6a426652013-06-07 22:07:20 +00004857 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00004858 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00004859 EnumDecl *Enum = ET->getDecl();
4860 if (!Enum->isCompleteDefinition())
4861 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00004862
David Majnemer6a426652013-06-07 22:07:20 +00004863 unsigned NumPositive = Enum->getNumPositiveBits();
4864 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00004865
David Majnemer6a426652013-06-07 22:07:20 +00004866 if (NumNegative == 0)
4867 return IntRange(NumPositive, true/*NonNegative*/);
4868 else
4869 return IntRange(std::max(NumPositive + 1, NumNegative),
4870 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00004871 }
John McCall70aa5392010-01-06 05:24:50 +00004872
4873 const BuiltinType *BT = cast<BuiltinType>(T);
4874 assert(BT->isInteger());
4875
4876 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4877 }
4878
John McCall817d4af2010-11-10 23:38:19 +00004879 /// Returns the "target" range of a canonical integral type, i.e.
4880 /// the range of values expressible in the type.
4881 ///
4882 /// This matches forValueOfCanonicalType except that enums have the
4883 /// full range of their type, not the range of their enumerators.
4884 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4885 assert(T->isCanonicalUnqualified());
4886
4887 if (const VectorType *VT = dyn_cast<VectorType>(T))
4888 T = VT->getElementType().getTypePtr();
4889 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4890 T = CT->getElementType().getTypePtr();
4891 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00004892 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00004893
4894 const BuiltinType *BT = cast<BuiltinType>(T);
4895 assert(BT->isInteger());
4896
4897 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4898 }
4899
4900 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00004901 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00004902 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00004903 L.NonNegative && R.NonNegative);
4904 }
4905
John McCall817d4af2010-11-10 23:38:19 +00004906 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00004907 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00004908 return IntRange(std::min(L.Width, R.Width),
4909 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00004910 }
4911};
4912
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004913static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4914 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004915 if (value.isSigned() && value.isNegative())
4916 return IntRange(value.getMinSignedBits(), false);
4917
4918 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00004919 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004920
4921 // isNonNegative() just checks the sign bit without considering
4922 // signedness.
4923 return IntRange(value.getActiveBits(), true);
4924}
4925
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004926static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4927 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004928 if (result.isInt())
4929 return GetValueRange(C, result.getInt(), MaxWidth);
4930
4931 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00004932 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4933 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4934 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4935 R = IntRange::join(R, El);
4936 }
John McCall70aa5392010-01-06 05:24:50 +00004937 return R;
4938 }
4939
4940 if (result.isComplexInt()) {
4941 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4942 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4943 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00004944 }
4945
4946 // This can happen with lossless casts to intptr_t of "based" lvalues.
4947 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00004948 // FIXME: The only reason we need to pass the type in here is to get
4949 // the sign right on this one case. It would be nice if APValue
4950 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004951 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00004952 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00004953}
John McCall70aa5392010-01-06 05:24:50 +00004954
Eli Friedmane6d33952013-07-08 20:20:06 +00004955static QualType GetExprType(Expr *E) {
4956 QualType Ty = E->getType();
4957 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4958 Ty = AtomicRHS->getValueType();
4959 return Ty;
4960}
4961
John McCall70aa5392010-01-06 05:24:50 +00004962/// Pseudo-evaluate the given integer expression, estimating the
4963/// range of values it might take.
4964///
4965/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004966static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004967 E = E->IgnoreParens();
4968
4969 // Try a full evaluation first.
4970 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00004971 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00004972 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004973
4974 // I think we only want to look through implicit casts here; if the
4975 // user has an explicit widening cast, we should treat the value as
4976 // being of the new, wider type.
4977 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00004978 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00004979 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4980
Eli Friedmane6d33952013-07-08 20:20:06 +00004981 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00004982
John McCalle3027922010-08-25 11:45:40 +00004983 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00004984
John McCall70aa5392010-01-06 05:24:50 +00004985 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00004986 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00004987 return OutputTypeRange;
4988
4989 IntRange SubRange
4990 = GetExprRange(C, CE->getSubExpr(),
4991 std::min(MaxWidth, OutputTypeRange.Width));
4992
4993 // Bail out if the subexpr's range is as wide as the cast type.
4994 if (SubRange.Width >= OutputTypeRange.Width)
4995 return OutputTypeRange;
4996
4997 // Otherwise, we take the smaller width, and we're non-negative if
4998 // either the output type or the subexpr is.
4999 return IntRange(SubRange.Width,
5000 SubRange.NonNegative || OutputTypeRange.NonNegative);
5001 }
5002
5003 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5004 // If we can fold the condition, just take that operand.
5005 bool CondResult;
5006 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5007 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5008 : CO->getFalseExpr(),
5009 MaxWidth);
5010
5011 // Otherwise, conservatively merge.
5012 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5013 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5014 return IntRange::join(L, R);
5015 }
5016
5017 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5018 switch (BO->getOpcode()) {
5019
5020 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005021 case BO_LAnd:
5022 case BO_LOr:
5023 case BO_LT:
5024 case BO_GT:
5025 case BO_LE:
5026 case BO_GE:
5027 case BO_EQ:
5028 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005029 return IntRange::forBoolType();
5030
John McCallc3688382011-07-13 06:35:24 +00005031 // The type of the assignments is the type of the LHS, so the RHS
5032 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005033 case BO_MulAssign:
5034 case BO_DivAssign:
5035 case BO_RemAssign:
5036 case BO_AddAssign:
5037 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005038 case BO_XorAssign:
5039 case BO_OrAssign:
5040 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005041 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005042
John McCallc3688382011-07-13 06:35:24 +00005043 // Simple assignments just pass through the RHS, which will have
5044 // been coerced to the LHS type.
5045 case BO_Assign:
5046 // TODO: bitfields?
5047 return GetExprRange(C, BO->getRHS(), MaxWidth);
5048
John McCall70aa5392010-01-06 05:24:50 +00005049 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005050 case BO_PtrMemD:
5051 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005052 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005053
John McCall2ce81ad2010-01-06 22:07:33 +00005054 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005055 case BO_And:
5056 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005057 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5058 GetExprRange(C, BO->getRHS(), MaxWidth));
5059
John McCall70aa5392010-01-06 05:24:50 +00005060 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005061 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005062 // ...except that we want to treat '1 << (blah)' as logically
5063 // positive. It's an important idiom.
5064 if (IntegerLiteral *I
5065 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5066 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005067 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005068 return IntRange(R.Width, /*NonNegative*/ true);
5069 }
5070 }
5071 // fallthrough
5072
John McCalle3027922010-08-25 11:45:40 +00005073 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005074 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005075
John McCall2ce81ad2010-01-06 22:07:33 +00005076 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005077 case BO_Shr:
5078 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005079 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5080
5081 // If the shift amount is a positive constant, drop the width by
5082 // that much.
5083 llvm::APSInt shift;
5084 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5085 shift.isNonNegative()) {
5086 unsigned zext = shift.getZExtValue();
5087 if (zext >= L.Width)
5088 L.Width = (L.NonNegative ? 0 : 1);
5089 else
5090 L.Width -= zext;
5091 }
5092
5093 return L;
5094 }
5095
5096 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005097 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005098 return GetExprRange(C, BO->getRHS(), MaxWidth);
5099
John McCall2ce81ad2010-01-06 22:07:33 +00005100 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005101 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005102 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005103 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005104 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005105
John McCall51431812011-07-14 22:39:48 +00005106 // The width of a division result is mostly determined by the size
5107 // of the LHS.
5108 case BO_Div: {
5109 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005110 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005111 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5112
5113 // If the divisor is constant, use that.
5114 llvm::APSInt divisor;
5115 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5116 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5117 if (log2 >= L.Width)
5118 L.Width = (L.NonNegative ? 0 : 1);
5119 else
5120 L.Width = std::min(L.Width - log2, MaxWidth);
5121 return L;
5122 }
5123
5124 // Otherwise, just use the LHS's width.
5125 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5126 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5127 }
5128
5129 // The result of a remainder can't be larger than the result of
5130 // either side.
5131 case BO_Rem: {
5132 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005133 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005134 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5135 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5136
5137 IntRange meet = IntRange::meet(L, R);
5138 meet.Width = std::min(meet.Width, MaxWidth);
5139 return meet;
5140 }
5141
5142 // The default behavior is okay for these.
5143 case BO_Mul:
5144 case BO_Add:
5145 case BO_Xor:
5146 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005147 break;
5148 }
5149
John McCall51431812011-07-14 22:39:48 +00005150 // The default case is to treat the operation as if it were closed
5151 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005152 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5153 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5154 return IntRange::join(L, R);
5155 }
5156
5157 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5158 switch (UO->getOpcode()) {
5159 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005160 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005161 return IntRange::forBoolType();
5162
5163 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005164 case UO_Deref:
5165 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005166 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005167
5168 default:
5169 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5170 }
5171 }
5172
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005173 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5174 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5175
John McCalld25db7e2013-05-06 21:39:12 +00005176 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005177 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005178 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005179
Eli Friedmane6d33952013-07-08 20:20:06 +00005180 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005181}
John McCall263a48b2010-01-04 23:31:57 +00005182
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005183static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005184 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005185}
5186
John McCall263a48b2010-01-04 23:31:57 +00005187/// Checks whether the given value, which currently has the given
5188/// source semantics, has the same value when coerced through the
5189/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005190static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5191 const llvm::fltSemantics &Src,
5192 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005193 llvm::APFloat truncated = value;
5194
5195 bool ignored;
5196 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5197 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5198
5199 return truncated.bitwiseIsEqual(value);
5200}
5201
5202/// Checks whether the given value, which currently has the given
5203/// source semantics, has the same value when coerced through the
5204/// target semantics.
5205///
5206/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005207static bool IsSameFloatAfterCast(const APValue &value,
5208 const llvm::fltSemantics &Src,
5209 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005210 if (value.isFloat())
5211 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5212
5213 if (value.isVector()) {
5214 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5215 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5216 return false;
5217 return true;
5218 }
5219
5220 assert(value.isComplexFloat());
5221 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5222 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5223}
5224
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005225static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005226
Ted Kremenek6274be42010-09-23 21:43:44 +00005227static bool IsZero(Sema &S, Expr *E) {
5228 // Suppress cases where we are comparing against an enum constant.
5229 if (const DeclRefExpr *DR =
5230 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5231 if (isa<EnumConstantDecl>(DR->getDecl()))
5232 return false;
5233
5234 // Suppress cases where the '0' value is expanded from a macro.
5235 if (E->getLocStart().isMacroID())
5236 return false;
5237
John McCallcc7e5bf2010-05-06 08:58:33 +00005238 llvm::APSInt Value;
5239 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5240}
5241
John McCall2551c1b2010-10-06 00:25:24 +00005242static bool HasEnumType(Expr *E) {
5243 // Strip off implicit integral promotions.
5244 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005245 if (ICE->getCastKind() != CK_IntegralCast &&
5246 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005247 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005248 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005249 }
5250
5251 return E->getType()->isEnumeralType();
5252}
5253
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005254static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005255 // Disable warning in template instantiations.
5256 if (!S.ActiveTemplateInstantiations.empty())
5257 return;
5258
John McCalle3027922010-08-25 11:45:40 +00005259 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005260 if (E->isValueDependent())
5261 return;
5262
John McCalle3027922010-08-25 11:45:40 +00005263 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005264 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005265 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005266 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005267 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005268 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005269 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005270 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005271 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005272 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005273 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005274 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005275 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005276 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005277 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005278 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5279 }
5280}
5281
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005282static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005283 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005284 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005285 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005286 // Disable warning in template instantiations.
5287 if (!S.ActiveTemplateInstantiations.empty())
5288 return;
5289
Richard Trieu0f097742014-04-04 04:13:47 +00005290 // TODO: Investigate using GetExprRange() to get tighter bounds
5291 // on the bit ranges.
5292 QualType OtherT = Other->getType();
5293 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5294 unsigned OtherWidth = OtherRange.Width;
5295
5296 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5297
Richard Trieu560910c2012-11-14 22:50:24 +00005298 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00005299 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00005300 return;
5301
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005302 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00005303 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005304
Richard Trieu0f097742014-04-04 04:13:47 +00005305 // Used for diagnostic printout.
5306 enum {
5307 LiteralConstant = 0,
5308 CXXBoolLiteralTrue,
5309 CXXBoolLiteralFalse
5310 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005311
Richard Trieu0f097742014-04-04 04:13:47 +00005312 if (!OtherIsBooleanType) {
5313 QualType ConstantT = Constant->getType();
5314 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005315
Richard Trieu0f097742014-04-04 04:13:47 +00005316 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5317 return;
5318 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5319 "comparison with non-integer type");
5320
5321 bool ConstantSigned = ConstantT->isSignedIntegerType();
5322 bool CommonSigned = CommonT->isSignedIntegerType();
5323
5324 bool EqualityOnly = false;
5325
5326 if (CommonSigned) {
5327 // The common type is signed, therefore no signed to unsigned conversion.
5328 if (!OtherRange.NonNegative) {
5329 // Check that the constant is representable in type OtherT.
5330 if (ConstantSigned) {
5331 if (OtherWidth >= Value.getMinSignedBits())
5332 return;
5333 } else { // !ConstantSigned
5334 if (OtherWidth >= Value.getActiveBits() + 1)
5335 return;
5336 }
5337 } else { // !OtherSigned
5338 // Check that the constant is representable in type OtherT.
5339 // Negative values are out of range.
5340 if (ConstantSigned) {
5341 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5342 return;
5343 } else { // !ConstantSigned
5344 if (OtherWidth >= Value.getActiveBits())
5345 return;
5346 }
Richard Trieu560910c2012-11-14 22:50:24 +00005347 }
Richard Trieu0f097742014-04-04 04:13:47 +00005348 } else { // !CommonSigned
5349 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005350 if (OtherWidth >= Value.getActiveBits())
5351 return;
Richard Trieu0f097742014-04-04 04:13:47 +00005352 } else if (!OtherRange.NonNegative && !ConstantSigned) {
5353 // Check to see if the constant is representable in OtherT.
5354 if (OtherWidth > Value.getActiveBits())
5355 return;
5356 // Check to see if the constant is equivalent to a negative value
5357 // cast to CommonT.
5358 if (S.Context.getIntWidth(ConstantT) ==
5359 S.Context.getIntWidth(CommonT) &&
5360 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5361 return;
5362 // The constant value rests between values that OtherT can represent
5363 // after conversion. Relational comparison still works, but equality
5364 // comparisons will be tautological.
5365 EqualityOnly = true;
5366 } else { // OtherSigned && ConstantSigned
5367 assert(0 && "Two signed types converted to unsigned types.");
Richard Trieu560910c2012-11-14 22:50:24 +00005368 }
5369 }
Richard Trieu0f097742014-04-04 04:13:47 +00005370
5371 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5372
5373 if (op == BO_EQ || op == BO_NE) {
5374 IsTrue = op == BO_NE;
5375 } else if (EqualityOnly) {
5376 return;
5377 } else if (RhsConstant) {
5378 if (op == BO_GT || op == BO_GE)
5379 IsTrue = !PositiveConstant;
5380 else // op == BO_LT || op == BO_LE
5381 IsTrue = PositiveConstant;
5382 } else {
5383 if (op == BO_LT || op == BO_LE)
5384 IsTrue = !PositiveConstant;
5385 else // op == BO_GT || op == BO_GE
5386 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005387 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005388 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00005389 // Other isKnownToHaveBooleanValue
5390 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
5391 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
5392 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
5393
5394 static const struct LinkedConditions {
5395 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
5396 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
5397 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
5398 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
5399 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
5400 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
5401
5402 } TruthTable = {
5403 // Constant on LHS. | Constant on RHS. |
5404 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
5405 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
5406 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
5407 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
5408 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
5409 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
5410 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
5411 };
5412
5413 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
5414
5415 enum ConstantValue ConstVal = Zero;
5416 if (Value.isUnsigned() || Value.isNonNegative()) {
5417 if (Value == 0) {
5418 LiteralOrBoolConstant =
5419 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
5420 ConstVal = Zero;
5421 } else if (Value == 1) {
5422 LiteralOrBoolConstant =
5423 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
5424 ConstVal = One;
5425 } else {
5426 LiteralOrBoolConstant = LiteralConstant;
5427 ConstVal = GT_One;
5428 }
5429 } else {
5430 ConstVal = LT_Zero;
5431 }
5432
5433 CompareBoolWithConstantResult CmpRes;
5434
5435 switch (op) {
5436 case BO_LT:
5437 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
5438 break;
5439 case BO_GT:
5440 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
5441 break;
5442 case BO_LE:
5443 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
5444 break;
5445 case BO_GE:
5446 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
5447 break;
5448 case BO_EQ:
5449 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
5450 break;
5451 case BO_NE:
5452 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
5453 break;
5454 default:
5455 CmpRes = Unkwn;
5456 break;
5457 }
5458
5459 if (CmpRes == AFals) {
5460 IsTrue = false;
5461 } else if (CmpRes == ATrue) {
5462 IsTrue = true;
5463 } else {
5464 return;
5465 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005466 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005467
5468 // If this is a comparison to an enum constant, include that
5469 // constant in the diagnostic.
5470 const EnumConstantDecl *ED = 0;
5471 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5472 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5473
5474 SmallString<64> PrettySourceValue;
5475 llvm::raw_svector_ostream OS(PrettySourceValue);
5476 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00005477 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005478 else
5479 OS << Value;
5480
Richard Trieu0f097742014-04-04 04:13:47 +00005481 S.DiagRuntimeBehavior(
5482 E->getOperatorLoc(), E,
5483 S.PDiag(diag::warn_out_of_range_compare)
5484 << OS.str() << LiteralOrBoolConstant
5485 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
5486 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005487}
5488
John McCallcc7e5bf2010-05-06 08:58:33 +00005489/// Analyze the operands of the given comparison. Implements the
5490/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005491static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00005492 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5493 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00005494}
John McCall263a48b2010-01-04 23:31:57 +00005495
John McCallca01b222010-01-04 23:21:16 +00005496/// \brief Implements -Wsign-compare.
5497///
Richard Trieu82402a02011-09-15 21:56:47 +00005498/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005499static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005500 // The type the comparison is being performed in.
5501 QualType T = E->getLHS()->getType();
5502 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5503 && "comparison with mismatched types");
Fariborz Jahanian282071e2012-09-18 17:46:26 +00005504 if (E->isValueDependent())
5505 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005506
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005507 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5508 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005509
5510 bool IsComparisonConstant = false;
5511
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005512 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005513 // of 'true' or 'false'.
5514 if (T->isIntegralType(S.Context)) {
5515 llvm::APSInt RHSValue;
5516 bool IsRHSIntegralLiteral =
5517 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5518 llvm::APSInt LHSValue;
5519 bool IsLHSIntegralLiteral =
5520 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5521 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5522 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5523 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5524 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5525 else
5526 IsComparisonConstant =
5527 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005528 } else if (!T->hasUnsignedIntegerRepresentation())
5529 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005530
John McCallcc7e5bf2010-05-06 08:58:33 +00005531 // We don't do anything special if this isn't an unsigned integral
5532 // comparison: we're only interested in integral comparisons, and
5533 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00005534 //
5535 // We also don't care about value-dependent expressions or expressions
5536 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005537 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00005538 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005539
John McCallcc7e5bf2010-05-06 08:58:33 +00005540 // Check to see if one of the (unmodified) operands is of different
5541 // signedness.
5542 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00005543 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5544 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00005545 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00005546 signedOperand = LHS;
5547 unsignedOperand = RHS;
5548 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5549 signedOperand = RHS;
5550 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00005551 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00005552 CheckTrivialUnsignedComparison(S, E);
5553 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005554 }
5555
John McCallcc7e5bf2010-05-06 08:58:33 +00005556 // Otherwise, calculate the effective range of the signed operand.
5557 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00005558
John McCallcc7e5bf2010-05-06 08:58:33 +00005559 // Go ahead and analyze implicit conversions in the operands. Note
5560 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00005561 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5562 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00005563
John McCallcc7e5bf2010-05-06 08:58:33 +00005564 // If the signed range is non-negative, -Wsign-compare won't fire,
5565 // but we should still check for comparisons which are always true
5566 // or false.
5567 if (signedRange.NonNegative)
5568 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005569
5570 // For (in)equality comparisons, if the unsigned operand is a
5571 // constant which cannot collide with a overflowed signed operand,
5572 // then reinterpreting the signed operand as unsigned will not
5573 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00005574 if (E->isEqualityOp()) {
5575 unsigned comparisonWidth = S.Context.getIntWidth(T);
5576 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00005577
John McCallcc7e5bf2010-05-06 08:58:33 +00005578 // We should never be unable to prove that the unsigned operand is
5579 // non-negative.
5580 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5581
5582 if (unsignedRange.Width < comparisonWidth)
5583 return;
5584 }
5585
Douglas Gregorbfb4a212012-05-01 01:53:49 +00005586 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5587 S.PDiag(diag::warn_mixed_sign_comparison)
5588 << LHS->getType() << RHS->getType()
5589 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00005590}
5591
John McCall1f425642010-11-11 03:21:53 +00005592/// Analyzes an attempt to assign the given value to a bitfield.
5593///
5594/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005595static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5596 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00005597 assert(Bitfield->isBitField());
5598 if (Bitfield->isInvalidDecl())
5599 return false;
5600
John McCalldeebbcf2010-11-11 05:33:51 +00005601 // White-list bool bitfields.
5602 if (Bitfield->getType()->isBooleanType())
5603 return false;
5604
Douglas Gregor789adec2011-02-04 13:09:01 +00005605 // Ignore value- or type-dependent expressions.
5606 if (Bitfield->getBitWidth()->isValueDependent() ||
5607 Bitfield->getBitWidth()->isTypeDependent() ||
5608 Init->isValueDependent() ||
5609 Init->isTypeDependent())
5610 return false;
5611
John McCall1f425642010-11-11 03:21:53 +00005612 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5613
Richard Smith5fab0c92011-12-28 19:48:30 +00005614 llvm::APSInt Value;
5615 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00005616 return false;
5617
John McCall1f425642010-11-11 03:21:53 +00005618 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00005619 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00005620
5621 if (OriginalWidth <= FieldWidth)
5622 return false;
5623
Eli Friedmanc267a322012-01-26 23:11:39 +00005624 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005625 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00005626 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00005627
Eli Friedmanc267a322012-01-26 23:11:39 +00005628 // Check whether the stored value is equal to the original value.
5629 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00005630 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00005631 return false;
5632
Eli Friedmanc267a322012-01-26 23:11:39 +00005633 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00005634 // therefore don't strictly fit into a signed bitfield of width 1.
5635 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00005636 return false;
5637
John McCall1f425642010-11-11 03:21:53 +00005638 std::string PrettyValue = Value.toString(10);
5639 std::string PrettyTrunc = TruncatedValue.toString(10);
5640
5641 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5642 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5643 << Init->getSourceRange();
5644
5645 return true;
5646}
5647
John McCalld2a53122010-11-09 23:24:47 +00005648/// Analyze the given simple or compound assignment for warning-worthy
5649/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005650static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00005651 // Just recurse on the LHS.
5652 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5653
5654 // We want to recurse on the RHS as normal unless we're assigning to
5655 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00005656 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005657 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00005658 E->getOperatorLoc())) {
5659 // Recurse, ignoring any implicit conversions on the RHS.
5660 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5661 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00005662 }
5663 }
5664
5665 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5666}
5667
John McCall263a48b2010-01-04 23:31:57 +00005668/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005669static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005670 SourceLocation CContext, unsigned diag,
5671 bool pruneControlFlow = false) {
5672 if (pruneControlFlow) {
5673 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5674 S.PDiag(diag)
5675 << SourceType << T << E->getSourceRange()
5676 << SourceRange(CContext));
5677 return;
5678 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00005679 S.Diag(E->getExprLoc(), diag)
5680 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5681}
5682
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005683/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005684static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005685 SourceLocation CContext, unsigned diag,
5686 bool pruneControlFlow = false) {
5687 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005688}
5689
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005690/// Diagnose an implicit cast from a literal expression. Does not warn when the
5691/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00005692void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5693 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005694 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00005695 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005696 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00005697 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5698 T->hasUnsignedIntegerRepresentation());
5699 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00005700 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005701 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00005702 return;
5703
Eli Friedman07185912013-08-29 23:44:43 +00005704 // FIXME: Force the precision of the source value down so we don't print
5705 // digits which are usually useless (we don't really care here if we
5706 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5707 // would automatically print the shortest representation, but it's a bit
5708 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00005709 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00005710 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5711 precision = (precision * 59 + 195) / 196;
5712 Value.toString(PrettySourceValue, precision);
5713
David Blaikie9b88cc02012-05-15 17:18:27 +00005714 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00005715 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5716 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5717 else
David Blaikie9b88cc02012-05-15 17:18:27 +00005718 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00005719
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005720 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00005721 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5722 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00005723}
5724
John McCall18a2c2c2010-11-09 22:22:12 +00005725std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5726 if (!Range.Width) return "0";
5727
5728 llvm::APSInt ValueInRange = Value;
5729 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00005730 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00005731 return ValueInRange.toString(10);
5732}
5733
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005734static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5735 if (!isa<ImplicitCastExpr>(Ex))
5736 return false;
5737
5738 Expr *InnerE = Ex->IgnoreParenImpCasts();
5739 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5740 const Type *Source =
5741 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5742 if (Target->isDependentType())
5743 return false;
5744
5745 const BuiltinType *FloatCandidateBT =
5746 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5747 const Type *BoolCandidateType = ToBool ? Target : Source;
5748
5749 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5750 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5751}
5752
5753void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5754 SourceLocation CC) {
5755 unsigned NumArgs = TheCall->getNumArgs();
5756 for (unsigned i = 0; i < NumArgs; ++i) {
5757 Expr *CurrA = TheCall->getArg(i);
5758 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5759 continue;
5760
5761 bool IsSwapped = ((i > 0) &&
5762 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5763 IsSwapped |= ((i < (NumArgs - 1)) &&
5764 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5765 if (IsSwapped) {
5766 // Warn on this floating-point to bool conversion.
5767 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5768 CurrA->getType(), CC,
5769 diag::warn_impcast_floating_point_to_bool);
5770 }
5771 }
5772}
5773
John McCallcc7e5bf2010-05-06 08:58:33 +00005774void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005775 SourceLocation CC, bool *ICContext = 0) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005776 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00005777
John McCallcc7e5bf2010-05-06 08:58:33 +00005778 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5779 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5780 if (Source == Target) return;
5781 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00005782
Chandler Carruthc22845a2011-07-26 05:40:03 +00005783 // If the conversion context location is invalid don't complain. We also
5784 // don't want to emit a warning if the issue occurs from the expansion of
5785 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5786 // delay this check as long as possible. Once we detect we are in that
5787 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005788 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00005789 return;
5790
Richard Trieu021baa32011-09-23 20:10:00 +00005791 // Diagnose implicit casts to bool.
5792 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5793 if (isa<StringLiteral>(E))
5794 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00005795 // and expressions, for instance, assert(0 && "error here"), are
5796 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00005797 return DiagnoseImpCast(S, E, T, CC,
5798 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00005799 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
5800 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
5801 // This covers the literal expressions that evaluate to Objective-C
5802 // objects.
5803 return DiagnoseImpCast(S, E, T, CC,
5804 diag::warn_impcast_objective_c_literal_to_bool);
5805 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00005806 if (Source->isPointerType() || Source->canDecayToPointerType()) {
5807 // Warn on pointer to bool conversion that is always true.
5808 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
5809 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00005810 }
Richard Trieu021baa32011-09-23 20:10:00 +00005811 }
John McCall263a48b2010-01-04 23:31:57 +00005812
5813 // Strip vector types.
5814 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005815 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005816 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005817 return;
John McCallacf0ee52010-10-08 02:01:28 +00005818 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005819 }
Chris Lattneree7286f2011-06-14 04:51:15 +00005820
5821 // If the vector cast is cast between two vectors of the same size, it is
5822 // a bitcast, not a conversion.
5823 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5824 return;
John McCall263a48b2010-01-04 23:31:57 +00005825
5826 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5827 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5828 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00005829 if (auto VecTy = dyn_cast<VectorType>(Target))
5830 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00005831
5832 // Strip complex types.
5833 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005834 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005835 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005836 return;
5837
John McCallacf0ee52010-10-08 02:01:28 +00005838 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005839 }
John McCall263a48b2010-01-04 23:31:57 +00005840
5841 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5842 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5843 }
5844
5845 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5846 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5847
5848 // If the source is floating point...
5849 if (SourceBT && SourceBT->isFloatingPoint()) {
5850 // ...and the target is floating point...
5851 if (TargetBT && TargetBT->isFloatingPoint()) {
5852 // ...then warn if we're dropping FP rank.
5853
5854 // Builtin FP kinds are ordered by increasing FP rank.
5855 if (SourceBT->getKind() > TargetBT->getKind()) {
5856 // Don't warn about float constants that are precisely
5857 // representable in the target type.
5858 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005859 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00005860 // Value might be a float, a float vector, or a float complex.
5861 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00005862 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5863 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00005864 return;
5865 }
5866
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005867 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005868 return;
5869
John McCallacf0ee52010-10-08 02:01:28 +00005870 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00005871 }
5872 return;
5873 }
5874
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005875 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00005876 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005877 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005878 return;
5879
Chandler Carruth22c7a792011-02-17 11:05:49 +00005880 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00005881 // We also want to warn on, e.g., "int i = -1.234"
5882 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5883 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5884 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5885
Chandler Carruth016ef402011-04-10 08:36:24 +00005886 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5887 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00005888 } else {
5889 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5890 }
5891 }
John McCall263a48b2010-01-04 23:31:57 +00005892
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005893 // If the target is bool, warn if expr is a function or method call.
5894 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5895 isa<CallExpr>(E)) {
5896 // Check last argument of function call to see if it is an
5897 // implicit cast from a type matching the type the result
5898 // is being cast to.
5899 CallExpr *CEx = cast<CallExpr>(E);
5900 unsigned NumArgs = CEx->getNumArgs();
5901 if (NumArgs > 0) {
5902 Expr *LastA = CEx->getArg(NumArgs - 1);
5903 Expr *InnerE = LastA->IgnoreParenImpCasts();
5904 const Type *InnerType =
5905 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5906 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5907 // Warn on this floating-point to bool conversion
5908 DiagnoseImpCast(S, E, T, CC,
5909 diag::warn_impcast_floating_point_to_bool);
5910 }
5911 }
5912 }
John McCall263a48b2010-01-04 23:31:57 +00005913 return;
5914 }
5915
Richard Trieubeaf3452011-05-29 19:59:02 +00005916 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikie9366d2b2012-06-19 21:19:06 +00005917 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiea1edff02012-11-08 00:41:20 +00005918 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikiebcd4b552013-02-16 00:56:22 +00005919 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieae12b182012-03-16 20:30:12 +00005920 SourceLocation Loc = E->getSourceRange().getBegin();
5921 if (Loc.isMacroID())
5922 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie18e9ac72012-05-15 21:57:38 +00005923 if (!Loc.isMacroID() || CC.isMacroID())
5924 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5925 << T << clang::SourceRange(CC)
Richard Smithf7ec86a2013-09-20 00:27:40 +00005926 << FixItHint::CreateReplacement(Loc,
5927 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieubeaf3452011-05-29 19:59:02 +00005928 }
5929
David Blaikie9366d2b2012-06-19 21:19:06 +00005930 if (!Source->isIntegerType() || !Target->isIntegerType())
5931 return;
5932
David Blaikie7555b6a2012-05-15 16:56:36 +00005933 // TODO: remove this early return once the false positives for constant->bool
5934 // in templates, macros, etc, are reduced or removed.
5935 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5936 return;
5937
John McCallcc7e5bf2010-05-06 08:58:33 +00005938 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00005939 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00005940
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005941 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00005942 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005943 // TODO: this should happen for bitfield stores, too.
5944 llvm::APSInt Value(32);
5945 if (E->isIntegerConstantExpr(Value, S.Context)) {
5946 if (S.SourceMgr.isInSystemMacro(CC))
5947 return;
5948
John McCall18a2c2c2010-11-09 22:22:12 +00005949 std::string PrettySourceValue = Value.toString(10);
5950 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005951
Ted Kremenek33ba9952011-10-22 02:37:33 +00005952 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5953 S.PDiag(diag::warn_impcast_integer_precision_constant)
5954 << PrettySourceValue << PrettyTargetValue
5955 << E->getType() << T << E->getSourceRange()
5956 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00005957 return;
5958 }
5959
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005960 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5961 if (S.SourceMgr.isInSystemMacro(CC))
5962 return;
5963
David Blaikie9455da02012-04-12 22:40:54 +00005964 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00005965 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5966 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00005967 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00005968 }
5969
5970 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5971 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5972 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005973
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005974 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005975 return;
5976
John McCallcc7e5bf2010-05-06 08:58:33 +00005977 unsigned DiagID = diag::warn_impcast_integer_sign;
5978
5979 // Traditionally, gcc has warned about this under -Wsign-compare.
5980 // We also want to warn about it in -Wconversion.
5981 // So if -Wconversion is off, use a completely identical diagnostic
5982 // in the sign-compare group.
5983 // The conditional-checking code will
5984 if (ICContext) {
5985 DiagID = diag::warn_impcast_integer_sign_conditional;
5986 *ICContext = true;
5987 }
5988
John McCallacf0ee52010-10-08 02:01:28 +00005989 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00005990 }
5991
Douglas Gregora78f1932011-02-22 02:45:07 +00005992 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00005993 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5994 // type, to give us better diagnostics.
5995 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005996 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00005997 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5998 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5999 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6000 SourceType = S.Context.getTypeDeclType(Enum);
6001 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6002 }
6003 }
6004
Douglas Gregora78f1932011-02-22 02:45:07 +00006005 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6006 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006007 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6008 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006009 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006010 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006011 return;
6012
Douglas Gregor364f7db2011-03-12 00:14:31 +00006013 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006014 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006015 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006016
John McCall263a48b2010-01-04 23:31:57 +00006017 return;
6018}
6019
David Blaikie18e9ac72012-05-15 21:57:38 +00006020void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6021 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006022
6023void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006024 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006025 E = E->IgnoreParenImpCasts();
6026
6027 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006028 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006029
John McCallacf0ee52010-10-08 02:01:28 +00006030 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006031 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006032 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006033 return;
6034}
6035
David Blaikie18e9ac72012-05-15 21:57:38 +00006036void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6037 SourceLocation CC, QualType T) {
John McCallacf0ee52010-10-08 02:01:28 +00006038 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006039
6040 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006041 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6042 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006043
6044 // If -Wconversion would have warned about either of the candidates
6045 // for a signedness conversion to the context type...
6046 if (!Suspicious) return;
6047
6048 // ...but it's currently ignored...
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00006049 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
6050 CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006051 return;
6052
John McCallcc7e5bf2010-05-06 08:58:33 +00006053 // ...then check whether it would have warned about either of the
6054 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006055 if (E->getType() == T) return;
6056
6057 Suspicious = false;
6058 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6059 E->getType(), CC, &Suspicious);
6060 if (!Suspicious)
6061 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006062 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006063}
6064
6065/// AnalyzeImplicitConversions - Find and report any interesting
6066/// implicit conversions in the given expression. There are a couple
6067/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006068void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006069 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006070 Expr *E = OrigE->IgnoreParenImpCasts();
6071
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006072 if (E->isTypeDependent() || E->isValueDependent())
6073 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006074
John McCallcc7e5bf2010-05-06 08:58:33 +00006075 // For conditional operators, we analyze the arguments as if they
6076 // were being fed directly into the output.
6077 if (isa<ConditionalOperator>(E)) {
6078 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006079 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006080 return;
6081 }
6082
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006083 // Check implicit argument conversions for function calls.
6084 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6085 CheckImplicitArgumentConversions(S, Call, CC);
6086
John McCallcc7e5bf2010-05-06 08:58:33 +00006087 // Go ahead and check any implicit conversions we might have skipped.
6088 // The non-canonical typecheck is just an optimization;
6089 // CheckImplicitConversion will filter out dead implicit conversions.
6090 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006091 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006092
6093 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006094
6095 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006096 if (POE->getResultExpr())
6097 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006098 }
6099
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006100 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6101 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6102
John McCallcc7e5bf2010-05-06 08:58:33 +00006103 // Skip past explicit casts.
6104 if (isa<ExplicitCastExpr>(E)) {
6105 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006106 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006107 }
6108
John McCalld2a53122010-11-09 23:24:47 +00006109 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6110 // Do a somewhat different check with comparison operators.
6111 if (BO->isComparisonOp())
6112 return AnalyzeComparison(S, BO);
6113
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006114 // And with simple assignments.
6115 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006116 return AnalyzeAssignment(S, BO);
6117 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006118
6119 // These break the otherwise-useful invariant below. Fortunately,
6120 // we don't really need to recurse into them, because any internal
6121 // expressions should have been analyzed already when they were
6122 // built into statements.
6123 if (isa<StmtExpr>(E)) return;
6124
6125 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006126 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006127
6128 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006129 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006130 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006131 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006132 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006133 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006134 if (!ChildExpr)
6135 continue;
6136
Richard Trieu955231d2014-01-25 01:10:35 +00006137 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006138 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006139 // Ignore checking string literals that are in logical and operators.
6140 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006141 continue;
6142 AnalyzeImplicitConversions(S, ChildExpr, CC);
6143 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006144}
6145
6146} // end anonymous namespace
6147
Richard Trieu3bb8b562014-02-26 02:36:06 +00006148enum {
6149 AddressOf,
6150 FunctionPointer,
6151 ArrayPointer
6152};
6153
6154/// \brief Diagnose pointers that are always non-null.
6155/// \param E the expression containing the pointer
6156/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6157/// compared to a null pointer
6158/// \param IsEqual True when the comparison is equal to a null pointer
6159/// \param Range Extra SourceRange to highlight in the diagnostic
6160void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6161 Expr::NullPointerConstantKind NullKind,
6162 bool IsEqual, SourceRange Range) {
6163
6164 // Don't warn inside macros.
6165 if (E->getExprLoc().isMacroID())
6166 return;
6167 E = E->IgnoreImpCasts();
6168
6169 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6170
6171 bool IsAddressOf = false;
6172
6173 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6174 if (UO->getOpcode() != UO_AddrOf)
6175 return;
6176 IsAddressOf = true;
6177 E = UO->getSubExpr();
6178 }
6179
6180 // Expect to find a single Decl. Skip anything more complicated.
6181 ValueDecl *D = 0;
6182 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6183 D = R->getDecl();
6184 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6185 D = M->getMemberDecl();
6186 }
6187
6188 // Weak Decls can be null.
6189 if (!D || D->isWeak())
6190 return;
6191
6192 QualType T = D->getType();
6193 const bool IsArray = T->isArrayType();
6194 const bool IsFunction = T->isFunctionType();
6195
6196 if (IsAddressOf) {
6197 // Address of function is used to silence the function warning.
6198 if (IsFunction)
6199 return;
6200 // Address of reference can be null.
6201 if (T->isReferenceType())
6202 return;
6203 }
6204
6205 // Found nothing.
6206 if (!IsAddressOf && !IsFunction && !IsArray)
6207 return;
6208
6209 // Pretty print the expression for the diagnostic.
6210 std::string Str;
6211 llvm::raw_string_ostream S(Str);
6212 E->printPretty(S, 0, getPrintingPolicy());
6213
6214 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6215 : diag::warn_impcast_pointer_to_bool;
6216 unsigned DiagType;
6217 if (IsAddressOf)
6218 DiagType = AddressOf;
6219 else if (IsFunction)
6220 DiagType = FunctionPointer;
6221 else if (IsArray)
6222 DiagType = ArrayPointer;
6223 else
6224 llvm_unreachable("Could not determine diagnostic.");
6225 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6226 << Range << IsEqual;
6227
6228 if (!IsFunction)
6229 return;
6230
6231 // Suggest '&' to silence the function warning.
6232 Diag(E->getExprLoc(), diag::note_function_warning_silence)
6233 << FixItHint::CreateInsertion(E->getLocStart(), "&");
6234
6235 // Check to see if '()' fixit should be emitted.
6236 QualType ReturnType;
6237 UnresolvedSet<4> NonTemplateOverloads;
6238 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6239 if (ReturnType.isNull())
6240 return;
6241
6242 if (IsCompare) {
6243 // There are two cases here. If there is null constant, the only suggest
6244 // for a pointer return type. If the null is 0, then suggest if the return
6245 // type is a pointer or an integer type.
6246 if (!ReturnType->isPointerType()) {
6247 if (NullKind == Expr::NPCK_ZeroExpression ||
6248 NullKind == Expr::NPCK_ZeroLiteral) {
6249 if (!ReturnType->isIntegerType())
6250 return;
6251 } else {
6252 return;
6253 }
6254 }
6255 } else { // !IsCompare
6256 // For function to bool, only suggest if the function pointer has bool
6257 // return type.
6258 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6259 return;
6260 }
6261 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006262 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00006263}
6264
6265
John McCallcc7e5bf2010-05-06 08:58:33 +00006266/// Diagnoses "dangerous" implicit conversions within the given
6267/// expression (which is a full expression). Implements -Wconversion
6268/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006269///
6270/// \param CC the "context" location of the implicit conversion, i.e.
6271/// the most location of the syntactic entity requiring the implicit
6272/// conversion
6273void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006274 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00006275 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00006276 return;
6277
6278 // Don't diagnose for value- or type-dependent expressions.
6279 if (E->isTypeDependent() || E->isValueDependent())
6280 return;
6281
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006282 // Check for array bounds violations in cases where the check isn't triggered
6283 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6284 // ArraySubscriptExpr is on the RHS of a variable initialization.
6285 CheckArrayAccess(E);
6286
John McCallacf0ee52010-10-08 02:01:28 +00006287 // This is not the right CC for (e.g.) a variable initialization.
6288 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006289}
6290
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006291/// Diagnose when expression is an integer constant expression and its evaluation
6292/// results in integer overflow
6293void Sema::CheckForIntOverflow (Expr *E) {
Richard Smithe9ff7702013-11-05 22:23:30 +00006294 if (isa<BinaryOperator>(E->IgnoreParens()))
6295 E->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006296}
6297
Richard Smithc406cb72013-01-17 01:17:56 +00006298namespace {
6299/// \brief Visitor for expressions which looks for unsequenced operations on the
6300/// same object.
6301class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006302 typedef EvaluatedExprVisitor<SequenceChecker> Base;
6303
Richard Smithc406cb72013-01-17 01:17:56 +00006304 /// \brief A tree of sequenced regions within an expression. Two regions are
6305 /// unsequenced if one is an ancestor or a descendent of the other. When we
6306 /// finish processing an expression with sequencing, such as a comma
6307 /// expression, we fold its tree nodes into its parent, since they are
6308 /// unsequenced with respect to nodes we will visit later.
6309 class SequenceTree {
6310 struct Value {
6311 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6312 unsigned Parent : 31;
6313 bool Merged : 1;
6314 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006315 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00006316
6317 public:
6318 /// \brief A region within an expression which may be sequenced with respect
6319 /// to some other region.
6320 class Seq {
6321 explicit Seq(unsigned N) : Index(N) {}
6322 unsigned Index;
6323 friend class SequenceTree;
6324 public:
6325 Seq() : Index(0) {}
6326 };
6327
6328 SequenceTree() { Values.push_back(Value(0)); }
6329 Seq root() const { return Seq(0); }
6330
6331 /// \brief Create a new sequence of operations, which is an unsequenced
6332 /// subset of \p Parent. This sequence of operations is sequenced with
6333 /// respect to other children of \p Parent.
6334 Seq allocate(Seq Parent) {
6335 Values.push_back(Value(Parent.Index));
6336 return Seq(Values.size() - 1);
6337 }
6338
6339 /// \brief Merge a sequence of operations into its parent.
6340 void merge(Seq S) {
6341 Values[S.Index].Merged = true;
6342 }
6343
6344 /// \brief Determine whether two operations are unsequenced. This operation
6345 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
6346 /// should have been merged into its parent as appropriate.
6347 bool isUnsequenced(Seq Cur, Seq Old) {
6348 unsigned C = representative(Cur.Index);
6349 unsigned Target = representative(Old.Index);
6350 while (C >= Target) {
6351 if (C == Target)
6352 return true;
6353 C = Values[C].Parent;
6354 }
6355 return false;
6356 }
6357
6358 private:
6359 /// \brief Pick a representative for a sequence.
6360 unsigned representative(unsigned K) {
6361 if (Values[K].Merged)
6362 // Perform path compression as we go.
6363 return Values[K].Parent = representative(Values[K].Parent);
6364 return K;
6365 }
6366 };
6367
6368 /// An object for which we can track unsequenced uses.
6369 typedef NamedDecl *Object;
6370
6371 /// Different flavors of object usage which we track. We only track the
6372 /// least-sequenced usage of each kind.
6373 enum UsageKind {
6374 /// A read of an object. Multiple unsequenced reads are OK.
6375 UK_Use,
6376 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00006377 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00006378 UK_ModAsValue,
6379 /// A modification of an object which is not sequenced before the value
6380 /// computation of the expression, such as n++.
6381 UK_ModAsSideEffect,
6382
6383 UK_Count = UK_ModAsSideEffect + 1
6384 };
6385
6386 struct Usage {
6387 Usage() : Use(0), Seq() {}
6388 Expr *Use;
6389 SequenceTree::Seq Seq;
6390 };
6391
6392 struct UsageInfo {
6393 UsageInfo() : Diagnosed(false) {}
6394 Usage Uses[UK_Count];
6395 /// Have we issued a diagnostic for this variable already?
6396 bool Diagnosed;
6397 };
6398 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
6399
6400 Sema &SemaRef;
6401 /// Sequenced regions within the expression.
6402 SequenceTree Tree;
6403 /// Declaration modifications and references which we have seen.
6404 UsageInfoMap UsageMap;
6405 /// The region we are currently within.
6406 SequenceTree::Seq Region;
6407 /// Filled in with declarations which were modified as a side-effect
6408 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006409 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00006410 /// Expressions to check later. We defer checking these to reduce
6411 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006412 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00006413
6414 /// RAII object wrapping the visitation of a sequenced subexpression of an
6415 /// expression. At the end of this process, the side-effects of the evaluation
6416 /// become sequenced with respect to the value computation of the result, so
6417 /// we downgrade any UK_ModAsSideEffect within the evaluation to
6418 /// UK_ModAsValue.
6419 struct SequencedSubexpression {
6420 SequencedSubexpression(SequenceChecker &Self)
6421 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
6422 Self.ModAsSideEffect = &ModAsSideEffect;
6423 }
6424 ~SequencedSubexpression() {
6425 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
6426 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
6427 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
6428 Self.addUsage(U, ModAsSideEffect[I].first,
6429 ModAsSideEffect[I].second.Use, UK_ModAsValue);
6430 }
6431 Self.ModAsSideEffect = OldModAsSideEffect;
6432 }
6433
6434 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006435 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
6436 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00006437 };
6438
Richard Smith40238f02013-06-20 22:21:56 +00006439 /// RAII object wrapping the visitation of a subexpression which we might
6440 /// choose to evaluate as a constant. If any subexpression is evaluated and
6441 /// found to be non-constant, this allows us to suppress the evaluation of
6442 /// the outer expression.
6443 class EvaluationTracker {
6444 public:
6445 EvaluationTracker(SequenceChecker &Self)
6446 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
6447 Self.EvalTracker = this;
6448 }
6449 ~EvaluationTracker() {
6450 Self.EvalTracker = Prev;
6451 if (Prev)
6452 Prev->EvalOK &= EvalOK;
6453 }
6454
6455 bool evaluate(const Expr *E, bool &Result) {
6456 if (!EvalOK || E->isValueDependent())
6457 return false;
6458 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
6459 return EvalOK;
6460 }
6461
6462 private:
6463 SequenceChecker &Self;
6464 EvaluationTracker *Prev;
6465 bool EvalOK;
6466 } *EvalTracker;
6467
Richard Smithc406cb72013-01-17 01:17:56 +00006468 /// \brief Find the object which is produced by the specified expression,
6469 /// if any.
6470 Object getObject(Expr *E, bool Mod) const {
6471 E = E->IgnoreParenCasts();
6472 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6473 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
6474 return getObject(UO->getSubExpr(), Mod);
6475 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6476 if (BO->getOpcode() == BO_Comma)
6477 return getObject(BO->getRHS(), Mod);
6478 if (Mod && BO->isAssignmentOp())
6479 return getObject(BO->getLHS(), Mod);
6480 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6481 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
6482 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
6483 return ME->getMemberDecl();
6484 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6485 // FIXME: If this is a reference, map through to its value.
6486 return DRE->getDecl();
6487 return 0;
6488 }
6489
6490 /// \brief Note that an object was modified or used by an expression.
6491 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
6492 Usage &U = UI.Uses[UK];
6493 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
6494 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
6495 ModAsSideEffect->push_back(std::make_pair(O, U));
6496 U.Use = Ref;
6497 U.Seq = Region;
6498 }
6499 }
6500 /// \brief Check whether a modification or use conflicts with a prior usage.
6501 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
6502 bool IsModMod) {
6503 if (UI.Diagnosed)
6504 return;
6505
6506 const Usage &U = UI.Uses[OtherKind];
6507 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
6508 return;
6509
6510 Expr *Mod = U.Use;
6511 Expr *ModOrUse = Ref;
6512 if (OtherKind == UK_Use)
6513 std::swap(Mod, ModOrUse);
6514
6515 SemaRef.Diag(Mod->getExprLoc(),
6516 IsModMod ? diag::warn_unsequenced_mod_mod
6517 : diag::warn_unsequenced_mod_use)
6518 << O << SourceRange(ModOrUse->getExprLoc());
6519 UI.Diagnosed = true;
6520 }
6521
6522 void notePreUse(Object O, Expr *Use) {
6523 UsageInfo &U = UsageMap[O];
6524 // Uses conflict with other modifications.
6525 checkUsage(O, U, Use, UK_ModAsValue, false);
6526 }
6527 void notePostUse(Object O, Expr *Use) {
6528 UsageInfo &U = UsageMap[O];
6529 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
6530 addUsage(U, O, Use, UK_Use);
6531 }
6532
6533 void notePreMod(Object O, Expr *Mod) {
6534 UsageInfo &U = UsageMap[O];
6535 // Modifications conflict with other modifications and with uses.
6536 checkUsage(O, U, Mod, UK_ModAsValue, true);
6537 checkUsage(O, U, Mod, UK_Use, false);
6538 }
6539 void notePostMod(Object O, Expr *Use, UsageKind UK) {
6540 UsageInfo &U = UsageMap[O];
6541 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
6542 addUsage(U, O, Use, UK);
6543 }
6544
6545public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006546 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
6547 : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
6548 WorkList(WorkList), EvalTracker(0) {
Richard Smithc406cb72013-01-17 01:17:56 +00006549 Visit(E);
6550 }
6551
6552 void VisitStmt(Stmt *S) {
6553 // Skip all statements which aren't expressions for now.
6554 }
6555
6556 void VisitExpr(Expr *E) {
6557 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00006558 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006559 }
6560
6561 void VisitCastExpr(CastExpr *E) {
6562 Object O = Object();
6563 if (E->getCastKind() == CK_LValueToRValue)
6564 O = getObject(E->getSubExpr(), false);
6565
6566 if (O)
6567 notePreUse(O, E);
6568 VisitExpr(E);
6569 if (O)
6570 notePostUse(O, E);
6571 }
6572
6573 void VisitBinComma(BinaryOperator *BO) {
6574 // C++11 [expr.comma]p1:
6575 // Every value computation and side effect associated with the left
6576 // expression is sequenced before every value computation and side
6577 // effect associated with the right expression.
6578 SequenceTree::Seq LHS = Tree.allocate(Region);
6579 SequenceTree::Seq RHS = Tree.allocate(Region);
6580 SequenceTree::Seq OldRegion = Region;
6581
6582 {
6583 SequencedSubexpression SeqLHS(*this);
6584 Region = LHS;
6585 Visit(BO->getLHS());
6586 }
6587
6588 Region = RHS;
6589 Visit(BO->getRHS());
6590
6591 Region = OldRegion;
6592
6593 // Forget that LHS and RHS are sequenced. They are both unsequenced
6594 // with respect to other stuff.
6595 Tree.merge(LHS);
6596 Tree.merge(RHS);
6597 }
6598
6599 void VisitBinAssign(BinaryOperator *BO) {
6600 // The modification is sequenced after the value computation of the LHS
6601 // and RHS, so check it before inspecting the operands and update the
6602 // map afterwards.
6603 Object O = getObject(BO->getLHS(), true);
6604 if (!O)
6605 return VisitExpr(BO);
6606
6607 notePreMod(O, BO);
6608
6609 // C++11 [expr.ass]p7:
6610 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
6611 // only once.
6612 //
6613 // Therefore, for a compound assignment operator, O is considered used
6614 // everywhere except within the evaluation of E1 itself.
6615 if (isa<CompoundAssignOperator>(BO))
6616 notePreUse(O, BO);
6617
6618 Visit(BO->getLHS());
6619
6620 if (isa<CompoundAssignOperator>(BO))
6621 notePostUse(O, BO);
6622
6623 Visit(BO->getRHS());
6624
Richard Smith83e37bee2013-06-26 23:16:51 +00006625 // C++11 [expr.ass]p1:
6626 // the assignment is sequenced [...] before the value computation of the
6627 // assignment expression.
6628 // C11 6.5.16/3 has no such rule.
6629 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6630 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006631 }
6632 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6633 VisitBinAssign(CAO);
6634 }
6635
6636 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6637 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6638 void VisitUnaryPreIncDec(UnaryOperator *UO) {
6639 Object O = getObject(UO->getSubExpr(), true);
6640 if (!O)
6641 return VisitExpr(UO);
6642
6643 notePreMod(O, UO);
6644 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00006645 // C++11 [expr.pre.incr]p1:
6646 // the expression ++x is equivalent to x+=1
6647 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6648 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006649 }
6650
6651 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6652 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6653 void VisitUnaryPostIncDec(UnaryOperator *UO) {
6654 Object O = getObject(UO->getSubExpr(), true);
6655 if (!O)
6656 return VisitExpr(UO);
6657
6658 notePreMod(O, UO);
6659 Visit(UO->getSubExpr());
6660 notePostMod(O, UO, UK_ModAsSideEffect);
6661 }
6662
6663 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6664 void VisitBinLOr(BinaryOperator *BO) {
6665 // The side-effects of the LHS of an '&&' are sequenced before the
6666 // value computation of the RHS, and hence before the value computation
6667 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6668 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00006669 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006670 {
6671 SequencedSubexpression Sequenced(*this);
6672 Visit(BO->getLHS());
6673 }
6674
6675 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006676 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006677 if (!Result)
6678 Visit(BO->getRHS());
6679 } else {
6680 // Check for unsequenced operations in the RHS, treating it as an
6681 // entirely separate evaluation.
6682 //
6683 // FIXME: If there are operations in the RHS which are unsequenced
6684 // with respect to operations outside the RHS, and those operations
6685 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00006686 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006687 }
Richard Smithc406cb72013-01-17 01:17:56 +00006688 }
6689 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00006690 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006691 {
6692 SequencedSubexpression Sequenced(*this);
6693 Visit(BO->getLHS());
6694 }
6695
6696 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006697 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006698 if (Result)
6699 Visit(BO->getRHS());
6700 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00006701 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006702 }
Richard Smithc406cb72013-01-17 01:17:56 +00006703 }
6704
6705 // Only visit the condition, unless we can be sure which subexpression will
6706 // be chosen.
6707 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00006708 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00006709 {
6710 SequencedSubexpression Sequenced(*this);
6711 Visit(CO->getCond());
6712 }
Richard Smithc406cb72013-01-17 01:17:56 +00006713
6714 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006715 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00006716 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006717 else {
Richard Smithd33f5202013-01-17 23:18:09 +00006718 WorkList.push_back(CO->getTrueExpr());
6719 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006720 }
Richard Smithc406cb72013-01-17 01:17:56 +00006721 }
6722
Richard Smithe3dbfe02013-06-30 10:40:20 +00006723 void VisitCallExpr(CallExpr *CE) {
6724 // C++11 [intro.execution]p15:
6725 // When calling a function [...], every value computation and side effect
6726 // associated with any argument expression, or with the postfix expression
6727 // designating the called function, is sequenced before execution of every
6728 // expression or statement in the body of the function [and thus before
6729 // the value computation of its result].
6730 SequencedSubexpression Sequenced(*this);
6731 Base::VisitCallExpr(CE);
6732
6733 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6734 }
6735
Richard Smithc406cb72013-01-17 01:17:56 +00006736 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006737 // This is a call, so all subexpressions are sequenced before the result.
6738 SequencedSubexpression Sequenced(*this);
6739
Richard Smithc406cb72013-01-17 01:17:56 +00006740 if (!CCE->isListInitialization())
6741 return VisitExpr(CCE);
6742
6743 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006744 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006745 SequenceTree::Seq Parent = Region;
6746 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6747 E = CCE->arg_end();
6748 I != E; ++I) {
6749 Region = Tree.allocate(Parent);
6750 Elts.push_back(Region);
6751 Visit(*I);
6752 }
6753
6754 // Forget that the initializers are sequenced.
6755 Region = Parent;
6756 for (unsigned I = 0; I < Elts.size(); ++I)
6757 Tree.merge(Elts[I]);
6758 }
6759
6760 void VisitInitListExpr(InitListExpr *ILE) {
6761 if (!SemaRef.getLangOpts().CPlusPlus11)
6762 return VisitExpr(ILE);
6763
6764 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006765 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006766 SequenceTree::Seq Parent = Region;
6767 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6768 Expr *E = ILE->getInit(I);
6769 if (!E) continue;
6770 Region = Tree.allocate(Parent);
6771 Elts.push_back(Region);
6772 Visit(E);
6773 }
6774
6775 // Forget that the initializers are sequenced.
6776 Region = Parent;
6777 for (unsigned I = 0; I < Elts.size(); ++I)
6778 Tree.merge(Elts[I]);
6779 }
6780};
6781}
6782
6783void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006784 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00006785 WorkList.push_back(E);
6786 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00006787 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00006788 SequenceChecker(*this, Item, WorkList);
6789 }
Richard Smithc406cb72013-01-17 01:17:56 +00006790}
6791
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006792void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6793 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006794 CheckImplicitConversions(E, CheckLoc);
6795 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006796 if (!IsConstexpr && !E->isValueDependent())
6797 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006798}
6799
John McCall1f425642010-11-11 03:21:53 +00006800void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6801 FieldDecl *BitField,
6802 Expr *Init) {
6803 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6804}
6805
Mike Stump0c2ec772010-01-21 03:59:47 +00006806/// CheckParmsForFunctionDef - Check that the parameters of the given
6807/// function are appropriate for the definition of a function. This
6808/// takes care of any checks that cannot be performed on the
6809/// declaration itself, e.g., that the types of each of the function
6810/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00006811bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6812 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00006813 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006814 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00006815 for (; P != PEnd; ++P) {
6816 ParmVarDecl *Param = *P;
6817
Mike Stump0c2ec772010-01-21 03:59:47 +00006818 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6819 // function declarator that is part of a function definition of
6820 // that function shall not have incomplete type.
6821 //
6822 // This is also C++ [dcl.fct]p6.
6823 if (!Param->isInvalidDecl() &&
6824 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006825 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006826 Param->setInvalidDecl();
6827 HasInvalidParm = true;
6828 }
6829
6830 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6831 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00006832 if (CheckParameterNames &&
6833 Param->getIdentifier() == 0 &&
Mike Stump0c2ec772010-01-21 03:59:47 +00006834 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006835 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00006836 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00006837
6838 // C99 6.7.5.3p12:
6839 // If the function declarator is not part of a definition of that
6840 // function, parameters may have incomplete type and may use the [*]
6841 // notation in their sequences of declarator specifiers to specify
6842 // variable length array types.
6843 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006844 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00006845 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00006846 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00006847 // information is added for it.
6848 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006849 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00006850 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006851 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00006852 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006853
6854 // MSVC destroys objects passed by value in the callee. Therefore a
6855 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006856 // object's destructor. However, we don't perform any direct access check
6857 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00006858 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
6859 .getCXXABI()
6860 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00006861 if (!Param->isInvalidDecl()) {
6862 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
6863 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
6864 if (!ClassDecl->isInvalidDecl() &&
6865 !ClassDecl->hasIrrelevantDestructor() &&
6866 !ClassDecl->isDependentContext()) {
6867 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6868 MarkFunctionReferenced(Param->getLocation(), Destructor);
6869 DiagnoseUseOfDecl(Destructor, Param->getLocation());
6870 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006871 }
6872 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006873 }
Mike Stump0c2ec772010-01-21 03:59:47 +00006874 }
6875
6876 return HasInvalidParm;
6877}
John McCall2b5c1b22010-08-12 21:44:57 +00006878
6879/// CheckCastAlign - Implements -Wcast-align, which warns when a
6880/// pointer cast increases the alignment requirements.
6881void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6882 // This is actually a lot of work to potentially be doing on every
6883 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00006884 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6885 TRange.getBegin())
David Blaikie9c902b52011-09-25 23:23:43 +00006886 == DiagnosticsEngine::Ignored)
John McCall2b5c1b22010-08-12 21:44:57 +00006887 return;
6888
6889 // Ignore dependent types.
6890 if (T->isDependentType() || Op->getType()->isDependentType())
6891 return;
6892
6893 // Require that the destination be a pointer type.
6894 const PointerType *DestPtr = T->getAs<PointerType>();
6895 if (!DestPtr) return;
6896
6897 // If the destination has alignment 1, we're done.
6898 QualType DestPointee = DestPtr->getPointeeType();
6899 if (DestPointee->isIncompleteType()) return;
6900 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6901 if (DestAlign.isOne()) return;
6902
6903 // Require that the source be a pointer type.
6904 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6905 if (!SrcPtr) return;
6906 QualType SrcPointee = SrcPtr->getPointeeType();
6907
6908 // Whitelist casts from cv void*. We already implicitly
6909 // whitelisted casts to cv void*, since they have alignment 1.
6910 // Also whitelist casts involving incomplete types, which implicitly
6911 // includes 'void'.
6912 if (SrcPointee->isIncompleteType()) return;
6913
6914 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6915 if (SrcAlign >= DestAlign) return;
6916
6917 Diag(TRange.getBegin(), diag::warn_cast_align)
6918 << Op->getType() << T
6919 << static_cast<unsigned>(SrcAlign.getQuantity())
6920 << static_cast<unsigned>(DestAlign.getQuantity())
6921 << TRange << Op->getSourceRange();
6922}
6923
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006924static const Type* getElementType(const Expr *BaseExpr) {
6925 const Type* EltType = BaseExpr->getType().getTypePtr();
6926 if (EltType->isAnyPointerType())
6927 return EltType->getPointeeType().getTypePtr();
6928 else if (EltType->isArrayType())
6929 return EltType->getBaseElementTypeUnsafe();
6930 return EltType;
6931}
6932
Chandler Carruth28389f02011-08-05 09:10:50 +00006933/// \brief Check whether this array fits the idiom of a size-one tail padded
6934/// array member of a struct.
6935///
6936/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6937/// commonly used to emulate flexible arrays in C89 code.
6938static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6939 const NamedDecl *ND) {
6940 if (Size != 1 || !ND) return false;
6941
6942 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6943 if (!FD) return false;
6944
6945 // Don't consider sizes resulting from macro expansions or template argument
6946 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00006947
6948 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006949 while (TInfo) {
6950 TypeLoc TL = TInfo->getTypeLoc();
6951 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00006952 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6953 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006954 TInfo = TDL->getTypeSourceInfo();
6955 continue;
6956 }
David Blaikie6adc78e2013-02-18 22:06:02 +00006957 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6958 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00006959 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6960 return false;
6961 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006962 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00006963 }
Chandler Carruth28389f02011-08-05 09:10:50 +00006964
6965 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00006966 if (!RD) return false;
6967 if (RD->isUnion()) return false;
6968 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6969 if (!CRD->isStandardLayout()) return false;
6970 }
Chandler Carruth28389f02011-08-05 09:10:50 +00006971
Benjamin Kramer8c543672011-08-06 03:04:42 +00006972 // See if this is the last field decl in the record.
6973 const Decl *D = FD;
6974 while ((D = D->getNextDeclInContext()))
6975 if (isa<FieldDecl>(D))
6976 return false;
6977 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00006978}
6979
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006980void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006981 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00006982 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006983 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006984 if (IndexExpr->isValueDependent())
6985 return;
6986
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00006987 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006988 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006989 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006990 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006991 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00006992 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00006993
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006994 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006995 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00006996 return;
Richard Smith13f67182011-12-16 19:31:14 +00006997 if (IndexNegated)
6998 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00006999
Chandler Carruth126b1552011-08-05 08:07:29 +00007000 const NamedDecl *ND = NULL;
Chandler Carruth126b1552011-08-05 08:07:29 +00007001 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7002 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007003 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007004 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007005
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007006 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007007 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007008 if (!size.isStrictlyPositive())
7009 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007010
7011 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007012 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007013 // Make sure we're comparing apples to apples when comparing index to size
7014 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7015 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007016 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007017 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007018 if (ptrarith_typesize != array_typesize) {
7019 // There's a cast to a different size type involved
7020 uint64_t ratio = array_typesize / ptrarith_typesize;
7021 // TODO: Be smarter about handling cases where array_typesize is not a
7022 // multiple of ptrarith_typesize
7023 if (ptrarith_typesize * ratio == array_typesize)
7024 size *= llvm::APInt(size.getBitWidth(), ratio);
7025 }
7026 }
7027
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007028 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007029 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007030 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007031 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007032
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007033 // For array subscripting the index must be less than size, but for pointer
7034 // arithmetic also allow the index (offset) to be equal to size since
7035 // computing the next address after the end of the array is legal and
7036 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007037 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007038 return;
7039
7040 // Also don't warn for arrays of size 1 which are members of some
7041 // structure. These are often used to approximate flexible arrays in C89
7042 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007043 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007044 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007045
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007046 // Suppress the warning if the subscript expression (as identified by the
7047 // ']' location) and the index expression are both from macro expansions
7048 // within a system header.
7049 if (ASE) {
7050 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7051 ASE->getRBracketLoc());
7052 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7053 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7054 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007055 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007056 return;
7057 }
7058 }
7059
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007060 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007061 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007062 DiagID = diag::warn_array_index_exceeds_bounds;
7063
7064 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7065 PDiag(DiagID) << index.toString(10, true)
7066 << size.toString(10, true)
7067 << (unsigned)size.getLimitedValue(~0U)
7068 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007069 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007070 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007071 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007072 DiagID = diag::warn_ptr_arith_precedes_bounds;
7073 if (index.isNegative()) index = -index;
7074 }
7075
7076 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7077 PDiag(DiagID) << index.toString(10, true)
7078 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007079 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007080
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007081 if (!ND) {
7082 // Try harder to find a NamedDecl to point at in the note.
7083 while (const ArraySubscriptExpr *ASE =
7084 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7085 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7086 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7087 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7088 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7089 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7090 }
7091
Chandler Carruth1af88f12011-02-17 21:10:52 +00007092 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007093 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7094 PDiag(diag::note_array_index_out_of_bounds)
7095 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007096}
7097
Ted Kremenekdf26df72011-03-01 18:41:00 +00007098void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007099 int AllowOnePastEnd = 0;
7100 while (expr) {
7101 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007102 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007103 case Stmt::ArraySubscriptExprClass: {
7104 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007105 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007106 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007107 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007108 }
7109 case Stmt::UnaryOperatorClass: {
7110 // Only unwrap the * and & unary operators
7111 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7112 expr = UO->getSubExpr();
7113 switch (UO->getOpcode()) {
7114 case UO_AddrOf:
7115 AllowOnePastEnd++;
7116 break;
7117 case UO_Deref:
7118 AllowOnePastEnd--;
7119 break;
7120 default:
7121 return;
7122 }
7123 break;
7124 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007125 case Stmt::ConditionalOperatorClass: {
7126 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7127 if (const Expr *lhs = cond->getLHS())
7128 CheckArrayAccess(lhs);
7129 if (const Expr *rhs = cond->getRHS())
7130 CheckArrayAccess(rhs);
7131 return;
7132 }
7133 default:
7134 return;
7135 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007136 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007137}
John McCall31168b02011-06-15 23:02:42 +00007138
7139//===--- CHECK: Objective-C retain cycles ----------------------------------//
7140
7141namespace {
7142 struct RetainCycleOwner {
7143 RetainCycleOwner() : Variable(0), Indirect(false) {}
7144 VarDecl *Variable;
7145 SourceRange Range;
7146 SourceLocation Loc;
7147 bool Indirect;
7148
7149 void setLocsFrom(Expr *e) {
7150 Loc = e->getExprLoc();
7151 Range = e->getSourceRange();
7152 }
7153 };
7154}
7155
7156/// Consider whether capturing the given variable can possibly lead to
7157/// a retain cycle.
7158static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007159 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007160 // lifetime. In MRR, it's captured strongly if the variable is
7161 // __block and has an appropriate type.
7162 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7163 return false;
7164
7165 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007166 if (ref)
7167 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007168 return true;
7169}
7170
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007171static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007172 while (true) {
7173 e = e->IgnoreParens();
7174 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7175 switch (cast->getCastKind()) {
7176 case CK_BitCast:
7177 case CK_LValueBitCast:
7178 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007179 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007180 e = cast->getSubExpr();
7181 continue;
7182
John McCall31168b02011-06-15 23:02:42 +00007183 default:
7184 return false;
7185 }
7186 }
7187
7188 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7189 ObjCIvarDecl *ivar = ref->getDecl();
7190 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7191 return false;
7192
7193 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007194 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00007195 return false;
7196
7197 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7198 owner.Indirect = true;
7199 return true;
7200 }
7201
7202 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7203 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7204 if (!var) return false;
7205 return considerVariable(var, ref, owner);
7206 }
7207
John McCall31168b02011-06-15 23:02:42 +00007208 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7209 if (member->isArrow()) return false;
7210
7211 // Don't count this as an indirect ownership.
7212 e = member->getBase();
7213 continue;
7214 }
7215
John McCallfe96e0b2011-11-06 09:01:30 +00007216 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7217 // Only pay attention to pseudo-objects on property references.
7218 ObjCPropertyRefExpr *pre
7219 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7220 ->IgnoreParens());
7221 if (!pre) return false;
7222 if (pre->isImplicitProperty()) return false;
7223 ObjCPropertyDecl *property = pre->getExplicitProperty();
7224 if (!property->isRetaining() &&
7225 !(property->getPropertyIvarDecl() &&
7226 property->getPropertyIvarDecl()->getType()
7227 .getObjCLifetime() == Qualifiers::OCL_Strong))
7228 return false;
7229
7230 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007231 if (pre->isSuperReceiver()) {
7232 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7233 if (!owner.Variable)
7234 return false;
7235 owner.Loc = pre->getLocation();
7236 owner.Range = pre->getSourceRange();
7237 return true;
7238 }
John McCallfe96e0b2011-11-06 09:01:30 +00007239 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7240 ->getSourceExpr());
7241 continue;
7242 }
7243
John McCall31168b02011-06-15 23:02:42 +00007244 // Array ivars?
7245
7246 return false;
7247 }
7248}
7249
7250namespace {
7251 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7252 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7253 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
7254 Variable(variable), Capturer(0) {}
7255
7256 VarDecl *Variable;
7257 Expr *Capturer;
7258
7259 void VisitDeclRefExpr(DeclRefExpr *ref) {
7260 if (ref->getDecl() == Variable && !Capturer)
7261 Capturer = ref;
7262 }
7263
John McCall31168b02011-06-15 23:02:42 +00007264 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7265 if (Capturer) return;
7266 Visit(ref->getBase());
7267 if (Capturer && ref->isFreeIvar())
7268 Capturer = ref;
7269 }
7270
7271 void VisitBlockExpr(BlockExpr *block) {
7272 // Look inside nested blocks
7273 if (block->getBlockDecl()->capturesVariable(Variable))
7274 Visit(block->getBlockDecl()->getBody());
7275 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00007276
7277 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7278 if (Capturer) return;
7279 if (OVE->getSourceExpr())
7280 Visit(OVE->getSourceExpr());
7281 }
John McCall31168b02011-06-15 23:02:42 +00007282 };
7283}
7284
7285/// Check whether the given argument is a block which captures a
7286/// variable.
7287static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7288 assert(owner.Variable && owner.Loc.isValid());
7289
7290 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00007291
7292 // Look through [^{...} copy] and Block_copy(^{...}).
7293 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7294 Selector Cmd = ME->getSelector();
7295 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7296 e = ME->getInstanceReceiver();
7297 if (!e)
7298 return 0;
7299 e = e->IgnoreParenCasts();
7300 }
7301 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7302 if (CE->getNumArgs() == 1) {
7303 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00007304 if (Fn) {
7305 const IdentifierInfo *FnI = Fn->getIdentifier();
7306 if (FnI && FnI->isStr("_Block_copy")) {
7307 e = CE->getArg(0)->IgnoreParenCasts();
7308 }
7309 }
Jordan Rose67e887c2012-09-17 17:54:30 +00007310 }
7311 }
7312
John McCall31168b02011-06-15 23:02:42 +00007313 BlockExpr *block = dyn_cast<BlockExpr>(e);
7314 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
7315 return 0;
7316
7317 FindCaptureVisitor visitor(S.Context, owner.Variable);
7318 visitor.Visit(block->getBlockDecl()->getBody());
7319 return visitor.Capturer;
7320}
7321
7322static void diagnoseRetainCycle(Sema &S, Expr *capturer,
7323 RetainCycleOwner &owner) {
7324 assert(capturer);
7325 assert(owner.Variable && owner.Loc.isValid());
7326
7327 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
7328 << owner.Variable << capturer->getSourceRange();
7329 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
7330 << owner.Indirect << owner.Range;
7331}
7332
7333/// Check for a keyword selector that starts with the word 'add' or
7334/// 'set'.
7335static bool isSetterLikeSelector(Selector sel) {
7336 if (sel.isUnarySelector()) return false;
7337
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007338 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00007339 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007340 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00007341 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007342 else if (str.startswith("add")) {
7343 // Specially whitelist 'addOperationWithBlock:'.
7344 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
7345 return false;
7346 str = str.substr(3);
7347 }
John McCall31168b02011-06-15 23:02:42 +00007348 else
7349 return false;
7350
7351 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00007352 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00007353}
7354
7355/// Check a message send to see if it's likely to cause a retain cycle.
7356void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
7357 // Only check instance methods whose selector looks like a setter.
7358 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
7359 return;
7360
7361 // Try to find a variable that the receiver is strongly owned by.
7362 RetainCycleOwner owner;
7363 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007364 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00007365 return;
7366 } else {
7367 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
7368 owner.Variable = getCurMethodDecl()->getSelfDecl();
7369 owner.Loc = msg->getSuperLoc();
7370 owner.Range = msg->getSuperLoc();
7371 }
7372
7373 // Check whether the receiver is captured by any of the arguments.
7374 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
7375 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
7376 return diagnoseRetainCycle(*this, capturer, owner);
7377}
7378
7379/// Check a property assign to see if it's likely to cause a retain cycle.
7380void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
7381 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007382 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00007383 return;
7384
7385 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
7386 diagnoseRetainCycle(*this, capturer, owner);
7387}
7388
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007389void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
7390 RetainCycleOwner Owner;
7391 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
7392 return;
7393
7394 // Because we don't have an expression for the variable, we have to set the
7395 // location explicitly here.
7396 Owner.Loc = Var->getLocation();
7397 Owner.Range = Var->getSourceRange();
7398
7399 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
7400 diagnoseRetainCycle(*this, Capturer, Owner);
7401}
7402
Ted Kremenek9304da92012-12-21 08:04:28 +00007403static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
7404 Expr *RHS, bool isProperty) {
7405 // Check if RHS is an Objective-C object literal, which also can get
7406 // immediately zapped in a weak reference. Note that we explicitly
7407 // allow ObjCStringLiterals, since those are designed to never really die.
7408 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007409
Ted Kremenek64873352012-12-21 22:46:35 +00007410 // This enum needs to match with the 'select' in
7411 // warn_objc_arc_literal_assign (off-by-1).
7412 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
7413 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
7414 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007415
7416 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00007417 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00007418 << (isProperty ? 0 : 1)
7419 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007420
7421 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00007422}
7423
Ted Kremenekc1f014a2012-12-21 19:45:30 +00007424static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
7425 Qualifiers::ObjCLifetime LT,
7426 Expr *RHS, bool isProperty) {
7427 // Strip off any implicit cast added to get to the one ARC-specific.
7428 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7429 if (cast->getCastKind() == CK_ARCConsumeObject) {
7430 S.Diag(Loc, diag::warn_arc_retained_assign)
7431 << (LT == Qualifiers::OCL_ExplicitNone)
7432 << (isProperty ? 0 : 1)
7433 << RHS->getSourceRange();
7434 return true;
7435 }
7436 RHS = cast->getSubExpr();
7437 }
7438
7439 if (LT == Qualifiers::OCL_Weak &&
7440 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
7441 return true;
7442
7443 return false;
7444}
7445
Ted Kremenekb36234d2012-12-21 08:04:20 +00007446bool Sema::checkUnsafeAssigns(SourceLocation Loc,
7447 QualType LHS, Expr *RHS) {
7448 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
7449
7450 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
7451 return false;
7452
7453 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
7454 return true;
7455
7456 return false;
7457}
7458
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007459void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
7460 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007461 QualType LHSType;
7462 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00007463 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007464 ObjCPropertyRefExpr *PRE
7465 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
7466 if (PRE && !PRE->isImplicitProperty()) {
7467 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7468 if (PD)
7469 LHSType = PD->getType();
7470 }
7471
7472 if (LHSType.isNull())
7473 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00007474
7475 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
7476
7477 if (LT == Qualifiers::OCL_Weak) {
7478 DiagnosticsEngine::Level Level =
7479 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
7480 if (Level != DiagnosticsEngine::Ignored)
7481 getCurFunction()->markSafeWeakUse(LHS);
7482 }
7483
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007484 if (checkUnsafeAssigns(Loc, LHSType, RHS))
7485 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00007486
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007487 // FIXME. Check for other life times.
7488 if (LT != Qualifiers::OCL_None)
7489 return;
7490
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007491 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007492 if (PRE->isImplicitProperty())
7493 return;
7494 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7495 if (!PD)
7496 return;
7497
Bill Wendling44426052012-12-20 19:22:21 +00007498 unsigned Attributes = PD->getPropertyAttributes();
7499 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007500 // when 'assign' attribute was not explicitly specified
7501 // by user, ignore it and rely on property type itself
7502 // for lifetime info.
7503 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
7504 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
7505 LHSType->isObjCRetainableType())
7506 return;
7507
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007508 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00007509 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007510 Diag(Loc, diag::warn_arc_retained_property_assign)
7511 << RHS->getSourceRange();
7512 return;
7513 }
7514 RHS = cast->getSubExpr();
7515 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007516 }
Bill Wendling44426052012-12-20 19:22:21 +00007517 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00007518 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
7519 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00007520 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007521 }
7522}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00007523
7524//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
7525
7526namespace {
7527bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
7528 SourceLocation StmtLoc,
7529 const NullStmt *Body) {
7530 // Do not warn if the body is a macro that expands to nothing, e.g:
7531 //
7532 // #define CALL(x)
7533 // if (condition)
7534 // CALL(0);
7535 //
7536 if (Body->hasLeadingEmptyMacro())
7537 return false;
7538
7539 // Get line numbers of statement and body.
7540 bool StmtLineInvalid;
7541 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
7542 &StmtLineInvalid);
7543 if (StmtLineInvalid)
7544 return false;
7545
7546 bool BodyLineInvalid;
7547 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
7548 &BodyLineInvalid);
7549 if (BodyLineInvalid)
7550 return false;
7551
7552 // Warn if null statement and body are on the same line.
7553 if (StmtLine != BodyLine)
7554 return false;
7555
7556 return true;
7557}
7558} // Unnamed namespace
7559
7560void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
7561 const Stmt *Body,
7562 unsigned DiagID) {
7563 // Since this is a syntactic check, don't emit diagnostic for template
7564 // instantiations, this just adds noise.
7565 if (CurrentInstantiationScope)
7566 return;
7567
7568 // The body should be a null statement.
7569 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7570 if (!NBody)
7571 return;
7572
7573 // Do the usual checks.
7574 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7575 return;
7576
7577 Diag(NBody->getSemiLoc(), DiagID);
7578 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7579}
7580
7581void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
7582 const Stmt *PossibleBody) {
7583 assert(!CurrentInstantiationScope); // Ensured by caller
7584
7585 SourceLocation StmtLoc;
7586 const Stmt *Body;
7587 unsigned DiagID;
7588 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
7589 StmtLoc = FS->getRParenLoc();
7590 Body = FS->getBody();
7591 DiagID = diag::warn_empty_for_body;
7592 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
7593 StmtLoc = WS->getCond()->getSourceRange().getEnd();
7594 Body = WS->getBody();
7595 DiagID = diag::warn_empty_while_body;
7596 } else
7597 return; // Neither `for' nor `while'.
7598
7599 // The body should be a null statement.
7600 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7601 if (!NBody)
7602 return;
7603
7604 // Skip expensive checks if diagnostic is disabled.
7605 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
7606 DiagnosticsEngine::Ignored)
7607 return;
7608
7609 // Do the usual checks.
7610 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7611 return;
7612
7613 // `for(...);' and `while(...);' are popular idioms, so in order to keep
7614 // noise level low, emit diagnostics only if for/while is followed by a
7615 // CompoundStmt, e.g.:
7616 // for (int i = 0; i < n; i++);
7617 // {
7618 // a(i);
7619 // }
7620 // or if for/while is followed by a statement with more indentation
7621 // than for/while itself:
7622 // for (int i = 0; i < n; i++);
7623 // a(i);
7624 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
7625 if (!ProbableTypo) {
7626 bool BodyColInvalid;
7627 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
7628 PossibleBody->getLocStart(),
7629 &BodyColInvalid);
7630 if (BodyColInvalid)
7631 return;
7632
7633 bool StmtColInvalid;
7634 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7635 S->getLocStart(),
7636 &StmtColInvalid);
7637 if (StmtColInvalid)
7638 return;
7639
7640 if (BodyCol > StmtCol)
7641 ProbableTypo = true;
7642 }
7643
7644 if (ProbableTypo) {
7645 Diag(NBody->getSemiLoc(), DiagID);
7646 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7647 }
7648}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007649
7650//===--- Layout compatibility ----------------------------------------------//
7651
7652namespace {
7653
7654bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7655
7656/// \brief Check if two enumeration types are layout-compatible.
7657bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7658 // C++11 [dcl.enum] p8:
7659 // Two enumeration types are layout-compatible if they have the same
7660 // underlying type.
7661 return ED1->isComplete() && ED2->isComplete() &&
7662 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7663}
7664
7665/// \brief Check if two fields are layout-compatible.
7666bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7667 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7668 return false;
7669
7670 if (Field1->isBitField() != Field2->isBitField())
7671 return false;
7672
7673 if (Field1->isBitField()) {
7674 // Make sure that the bit-fields are the same length.
7675 unsigned Bits1 = Field1->getBitWidthValue(C);
7676 unsigned Bits2 = Field2->getBitWidthValue(C);
7677
7678 if (Bits1 != Bits2)
7679 return false;
7680 }
7681
7682 return true;
7683}
7684
7685/// \brief Check if two standard-layout structs are layout-compatible.
7686/// (C++11 [class.mem] p17)
7687bool isLayoutCompatibleStruct(ASTContext &C,
7688 RecordDecl *RD1,
7689 RecordDecl *RD2) {
7690 // If both records are C++ classes, check that base classes match.
7691 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7692 // If one of records is a CXXRecordDecl we are in C++ mode,
7693 // thus the other one is a CXXRecordDecl, too.
7694 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7695 // Check number of base classes.
7696 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7697 return false;
7698
7699 // Check the base classes.
7700 for (CXXRecordDecl::base_class_const_iterator
7701 Base1 = D1CXX->bases_begin(),
7702 BaseEnd1 = D1CXX->bases_end(),
7703 Base2 = D2CXX->bases_begin();
7704 Base1 != BaseEnd1;
7705 ++Base1, ++Base2) {
7706 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7707 return false;
7708 }
7709 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7710 // If only RD2 is a C++ class, it should have zero base classes.
7711 if (D2CXX->getNumBases() > 0)
7712 return false;
7713 }
7714
7715 // Check the fields.
7716 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7717 Field2End = RD2->field_end(),
7718 Field1 = RD1->field_begin(),
7719 Field1End = RD1->field_end();
7720 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7721 if (!isLayoutCompatible(C, *Field1, *Field2))
7722 return false;
7723 }
7724 if (Field1 != Field1End || Field2 != Field2End)
7725 return false;
7726
7727 return true;
7728}
7729
7730/// \brief Check if two standard-layout unions are layout-compatible.
7731/// (C++11 [class.mem] p18)
7732bool isLayoutCompatibleUnion(ASTContext &C,
7733 RecordDecl *RD1,
7734 RecordDecl *RD2) {
7735 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007736 for (auto *Field2 : RD2->fields())
7737 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007738
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007739 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007740 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7741 I = UnmatchedFields.begin(),
7742 E = UnmatchedFields.end();
7743
7744 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007745 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007746 bool Result = UnmatchedFields.erase(*I);
7747 (void) Result;
7748 assert(Result);
7749 break;
7750 }
7751 }
7752 if (I == E)
7753 return false;
7754 }
7755
7756 return UnmatchedFields.empty();
7757}
7758
7759bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7760 if (RD1->isUnion() != RD2->isUnion())
7761 return false;
7762
7763 if (RD1->isUnion())
7764 return isLayoutCompatibleUnion(C, RD1, RD2);
7765 else
7766 return isLayoutCompatibleStruct(C, RD1, RD2);
7767}
7768
7769/// \brief Check if two types are layout-compatible in C++11 sense.
7770bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7771 if (T1.isNull() || T2.isNull())
7772 return false;
7773
7774 // C++11 [basic.types] p11:
7775 // If two types T1 and T2 are the same type, then T1 and T2 are
7776 // layout-compatible types.
7777 if (C.hasSameType(T1, T2))
7778 return true;
7779
7780 T1 = T1.getCanonicalType().getUnqualifiedType();
7781 T2 = T2.getCanonicalType().getUnqualifiedType();
7782
7783 const Type::TypeClass TC1 = T1->getTypeClass();
7784 const Type::TypeClass TC2 = T2->getTypeClass();
7785
7786 if (TC1 != TC2)
7787 return false;
7788
7789 if (TC1 == Type::Enum) {
7790 return isLayoutCompatible(C,
7791 cast<EnumType>(T1)->getDecl(),
7792 cast<EnumType>(T2)->getDecl());
7793 } else if (TC1 == Type::Record) {
7794 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7795 return false;
7796
7797 return isLayoutCompatible(C,
7798 cast<RecordType>(T1)->getDecl(),
7799 cast<RecordType>(T2)->getDecl());
7800 }
7801
7802 return false;
7803}
7804}
7805
7806//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7807
7808namespace {
7809/// \brief Given a type tag expression find the type tag itself.
7810///
7811/// \param TypeExpr Type tag expression, as it appears in user's code.
7812///
7813/// \param VD Declaration of an identifier that appears in a type tag.
7814///
7815/// \param MagicValue Type tag magic value.
7816bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7817 const ValueDecl **VD, uint64_t *MagicValue) {
7818 while(true) {
7819 if (!TypeExpr)
7820 return false;
7821
7822 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7823
7824 switch (TypeExpr->getStmtClass()) {
7825 case Stmt::UnaryOperatorClass: {
7826 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7827 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7828 TypeExpr = UO->getSubExpr();
7829 continue;
7830 }
7831 return false;
7832 }
7833
7834 case Stmt::DeclRefExprClass: {
7835 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7836 *VD = DRE->getDecl();
7837 return true;
7838 }
7839
7840 case Stmt::IntegerLiteralClass: {
7841 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7842 llvm::APInt MagicValueAPInt = IL->getValue();
7843 if (MagicValueAPInt.getActiveBits() <= 64) {
7844 *MagicValue = MagicValueAPInt.getZExtValue();
7845 return true;
7846 } else
7847 return false;
7848 }
7849
7850 case Stmt::BinaryConditionalOperatorClass:
7851 case Stmt::ConditionalOperatorClass: {
7852 const AbstractConditionalOperator *ACO =
7853 cast<AbstractConditionalOperator>(TypeExpr);
7854 bool Result;
7855 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7856 if (Result)
7857 TypeExpr = ACO->getTrueExpr();
7858 else
7859 TypeExpr = ACO->getFalseExpr();
7860 continue;
7861 }
7862 return false;
7863 }
7864
7865 case Stmt::BinaryOperatorClass: {
7866 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7867 if (BO->getOpcode() == BO_Comma) {
7868 TypeExpr = BO->getRHS();
7869 continue;
7870 }
7871 return false;
7872 }
7873
7874 default:
7875 return false;
7876 }
7877 }
7878}
7879
7880/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7881///
7882/// \param TypeExpr Expression that specifies a type tag.
7883///
7884/// \param MagicValues Registered magic values.
7885///
7886/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7887/// kind.
7888///
7889/// \param TypeInfo Information about the corresponding C type.
7890///
7891/// \returns true if the corresponding C type was found.
7892bool GetMatchingCType(
7893 const IdentifierInfo *ArgumentKind,
7894 const Expr *TypeExpr, const ASTContext &Ctx,
7895 const llvm::DenseMap<Sema::TypeTagMagicValue,
7896 Sema::TypeTagData> *MagicValues,
7897 bool &FoundWrongKind,
7898 Sema::TypeTagData &TypeInfo) {
7899 FoundWrongKind = false;
7900
7901 // Variable declaration that has type_tag_for_datatype attribute.
7902 const ValueDecl *VD = NULL;
7903
7904 uint64_t MagicValue;
7905
7906 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7907 return false;
7908
7909 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00007910 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007911 if (I->getArgumentKind() != ArgumentKind) {
7912 FoundWrongKind = true;
7913 return false;
7914 }
7915 TypeInfo.Type = I->getMatchingCType();
7916 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7917 TypeInfo.MustBeNull = I->getMustBeNull();
7918 return true;
7919 }
7920 return false;
7921 }
7922
7923 if (!MagicValues)
7924 return false;
7925
7926 llvm::DenseMap<Sema::TypeTagMagicValue,
7927 Sema::TypeTagData>::const_iterator I =
7928 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7929 if (I == MagicValues->end())
7930 return false;
7931
7932 TypeInfo = I->second;
7933 return true;
7934}
7935} // unnamed namespace
7936
7937void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7938 uint64_t MagicValue, QualType Type,
7939 bool LayoutCompatible,
7940 bool MustBeNull) {
7941 if (!TypeTagForDatatypeMagicValues)
7942 TypeTagForDatatypeMagicValues.reset(
7943 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7944
7945 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7946 (*TypeTagForDatatypeMagicValues)[Magic] =
7947 TypeTagData(Type, LayoutCompatible, MustBeNull);
7948}
7949
7950namespace {
7951bool IsSameCharType(QualType T1, QualType T2) {
7952 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7953 if (!BT1)
7954 return false;
7955
7956 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7957 if (!BT2)
7958 return false;
7959
7960 BuiltinType::Kind T1Kind = BT1->getKind();
7961 BuiltinType::Kind T2Kind = BT2->getKind();
7962
7963 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
7964 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
7965 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7966 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7967}
7968} // unnamed namespace
7969
7970void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7971 const Expr * const *ExprArgs) {
7972 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7973 bool IsPointerAttr = Attr->getIsPointer();
7974
7975 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7976 bool FoundWrongKind;
7977 TypeTagData TypeInfo;
7978 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7979 TypeTagForDatatypeMagicValues.get(),
7980 FoundWrongKind, TypeInfo)) {
7981 if (FoundWrongKind)
7982 Diag(TypeTagExpr->getExprLoc(),
7983 diag::warn_type_tag_for_datatype_wrong_kind)
7984 << TypeTagExpr->getSourceRange();
7985 return;
7986 }
7987
7988 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7989 if (IsPointerAttr) {
7990 // Skip implicit cast of pointer to `void *' (as a function argument).
7991 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00007992 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00007993 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007994 ArgumentExpr = ICE->getSubExpr();
7995 }
7996 QualType ArgumentType = ArgumentExpr->getType();
7997
7998 // Passing a `void*' pointer shouldn't trigger a warning.
7999 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8000 return;
8001
8002 if (TypeInfo.MustBeNull) {
8003 // Type tag with matching void type requires a null pointer.
8004 if (!ArgumentExpr->isNullPointerConstant(Context,
8005 Expr::NPC_ValueDependentIsNotNull)) {
8006 Diag(ArgumentExpr->getExprLoc(),
8007 diag::warn_type_safety_null_pointer_required)
8008 << ArgumentKind->getName()
8009 << ArgumentExpr->getSourceRange()
8010 << TypeTagExpr->getSourceRange();
8011 }
8012 return;
8013 }
8014
8015 QualType RequiredType = TypeInfo.Type;
8016 if (IsPointerAttr)
8017 RequiredType = Context.getPointerType(RequiredType);
8018
8019 bool mismatch = false;
8020 if (!TypeInfo.LayoutCompatible) {
8021 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8022
8023 // C++11 [basic.fundamental] p1:
8024 // Plain char, signed char, and unsigned char are three distinct types.
8025 //
8026 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8027 // char' depending on the current char signedness mode.
8028 if (mismatch)
8029 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8030 RequiredType->getPointeeType())) ||
8031 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8032 mismatch = false;
8033 } else
8034 if (IsPointerAttr)
8035 mismatch = !isLayoutCompatible(Context,
8036 ArgumentType->getPointeeType(),
8037 RequiredType->getPointeeType());
8038 else
8039 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8040
8041 if (mismatch)
8042 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00008043 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008044 << TypeInfo.LayoutCompatible << RequiredType
8045 << ArgumentExpr->getSourceRange()
8046 << TypeTagExpr->getSourceRange();
8047}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008048