blob: 2cf25feae2edf8d23ceda9015a7e7b5969e1f281 [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
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000104 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
107 return true;
108
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000109 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000110 TheCall->setType(ResultType);
111 return false;
112}
113
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000114static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
115 CallExpr *TheCall, unsigned SizeIdx,
116 unsigned DstSizeIdx) {
117 if (TheCall->getNumArgs() <= SizeIdx ||
118 TheCall->getNumArgs() <= DstSizeIdx)
119 return;
120
121 const Expr *SizeArg = TheCall->getArg(SizeIdx);
122 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
123
124 llvm::APSInt Size, DstSize;
125
126 // find out if both sizes are known at compile time
127 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
128 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
129 return;
130
131 if (Size.ule(DstSize))
132 return;
133
134 // confirmed overflow so generate the diagnostic.
135 IdentifierInfo *FnName = FDecl->getIdentifier();
136 SourceLocation SL = TheCall->getLocStart();
137 SourceRange SR = TheCall->getSourceRange();
138
139 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
140}
141
John McCalldadc5752010-08-24 06:29:42 +0000142ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000143Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
144 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000145 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000146
Chris Lattner3be167f2010-10-01 23:23:24 +0000147 // Find out if any arguments are required to be integer constant expressions.
148 unsigned ICEArguments = 0;
149 ASTContext::GetBuiltinTypeError Error;
150 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
151 if (Error != ASTContext::GE_None)
152 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
153
154 // If any arguments are required to be ICE's, check and diagnose.
155 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
156 // Skip arguments not required to be ICE's.
157 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
158
159 llvm::APSInt Result;
160 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
161 return true;
162 ICEArguments &= ~(1 << ArgNo);
163 }
164
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000165 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000166 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000167 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000168 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000169 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000170 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000171 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000172 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000173 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000174 if (SemaBuiltinVAStart(TheCall))
175 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000176 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000177 case Builtin::BI__va_start: {
178 switch (Context.getTargetInfo().getTriple().getArch()) {
179 case llvm::Triple::arm:
180 case llvm::Triple::thumb:
181 if (SemaBuiltinVAStartARM(TheCall))
182 return ExprError();
183 break;
184 default:
185 if (SemaBuiltinVAStart(TheCall))
186 return ExprError();
187 break;
188 }
189 break;
190 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000191 case Builtin::BI__builtin_isgreater:
192 case Builtin::BI__builtin_isgreaterequal:
193 case Builtin::BI__builtin_isless:
194 case Builtin::BI__builtin_islessequal:
195 case Builtin::BI__builtin_islessgreater:
196 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000197 if (SemaBuiltinUnorderedCompare(TheCall))
198 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000199 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000200 case Builtin::BI__builtin_fpclassify:
201 if (SemaBuiltinFPClassification(TheCall, 6))
202 return ExprError();
203 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000204 case Builtin::BI__builtin_isfinite:
205 case Builtin::BI__builtin_isinf:
206 case Builtin::BI__builtin_isinf_sign:
207 case Builtin::BI__builtin_isnan:
208 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000209 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000210 return ExprError();
211 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000212 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000213 return SemaBuiltinShuffleVector(TheCall);
214 // TheCall will be freed by the smart pointer here, but that's fine, since
215 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000216 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000217 if (SemaBuiltinPrefetch(TheCall))
218 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000219 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000220 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000221 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000222 if (SemaBuiltinAssume(TheCall))
223 return ExprError();
224 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000225 case Builtin::BI__builtin_assume_aligned:
226 if (SemaBuiltinAssumeAligned(TheCall))
227 return ExprError();
228 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000229 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000230 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000231 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000232 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000233 case Builtin::BI__builtin_longjmp:
234 if (SemaBuiltinLongjmp(TheCall))
235 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000236 break;
John McCallbebede42011-02-26 05:39:39 +0000237
238 case Builtin::BI__builtin_classify_type:
239 if (checkArgCount(*this, TheCall, 1)) return true;
240 TheCall->setType(Context.IntTy);
241 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000242 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000243 if (checkArgCount(*this, TheCall, 1)) return true;
244 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000245 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000246 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000247 case Builtin::BI__sync_fetch_and_add_1:
248 case Builtin::BI__sync_fetch_and_add_2:
249 case Builtin::BI__sync_fetch_and_add_4:
250 case Builtin::BI__sync_fetch_and_add_8:
251 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000252 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000253 case Builtin::BI__sync_fetch_and_sub_1:
254 case Builtin::BI__sync_fetch_and_sub_2:
255 case Builtin::BI__sync_fetch_and_sub_4:
256 case Builtin::BI__sync_fetch_and_sub_8:
257 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000258 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000259 case Builtin::BI__sync_fetch_and_or_1:
260 case Builtin::BI__sync_fetch_and_or_2:
261 case Builtin::BI__sync_fetch_and_or_4:
262 case Builtin::BI__sync_fetch_and_or_8:
263 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000264 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000265 case Builtin::BI__sync_fetch_and_and_1:
266 case Builtin::BI__sync_fetch_and_and_2:
267 case Builtin::BI__sync_fetch_and_and_4:
268 case Builtin::BI__sync_fetch_and_and_8:
269 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000270 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000271 case Builtin::BI__sync_fetch_and_xor_1:
272 case Builtin::BI__sync_fetch_and_xor_2:
273 case Builtin::BI__sync_fetch_and_xor_4:
274 case Builtin::BI__sync_fetch_and_xor_8:
275 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000276 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000277 case Builtin::BI__sync_add_and_fetch_1:
278 case Builtin::BI__sync_add_and_fetch_2:
279 case Builtin::BI__sync_add_and_fetch_4:
280 case Builtin::BI__sync_add_and_fetch_8:
281 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000282 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000283 case Builtin::BI__sync_sub_and_fetch_1:
284 case Builtin::BI__sync_sub_and_fetch_2:
285 case Builtin::BI__sync_sub_and_fetch_4:
286 case Builtin::BI__sync_sub_and_fetch_8:
287 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000288 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000289 case Builtin::BI__sync_and_and_fetch_1:
290 case Builtin::BI__sync_and_and_fetch_2:
291 case Builtin::BI__sync_and_and_fetch_4:
292 case Builtin::BI__sync_and_and_fetch_8:
293 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000294 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000295 case Builtin::BI__sync_or_and_fetch_1:
296 case Builtin::BI__sync_or_and_fetch_2:
297 case Builtin::BI__sync_or_and_fetch_4:
298 case Builtin::BI__sync_or_and_fetch_8:
299 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000300 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000301 case Builtin::BI__sync_xor_and_fetch_1:
302 case Builtin::BI__sync_xor_and_fetch_2:
303 case Builtin::BI__sync_xor_and_fetch_4:
304 case Builtin::BI__sync_xor_and_fetch_8:
305 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000306 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000307 case Builtin::BI__sync_val_compare_and_swap_1:
308 case Builtin::BI__sync_val_compare_and_swap_2:
309 case Builtin::BI__sync_val_compare_and_swap_4:
310 case Builtin::BI__sync_val_compare_and_swap_8:
311 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000312 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000313 case Builtin::BI__sync_bool_compare_and_swap_1:
314 case Builtin::BI__sync_bool_compare_and_swap_2:
315 case Builtin::BI__sync_bool_compare_and_swap_4:
316 case Builtin::BI__sync_bool_compare_and_swap_8:
317 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000318 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000319 case Builtin::BI__sync_lock_test_and_set_1:
320 case Builtin::BI__sync_lock_test_and_set_2:
321 case Builtin::BI__sync_lock_test_and_set_4:
322 case Builtin::BI__sync_lock_test_and_set_8:
323 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000324 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000325 case Builtin::BI__sync_lock_release_1:
326 case Builtin::BI__sync_lock_release_2:
327 case Builtin::BI__sync_lock_release_4:
328 case Builtin::BI__sync_lock_release_8:
329 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000330 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000331 case Builtin::BI__sync_swap_1:
332 case Builtin::BI__sync_swap_2:
333 case Builtin::BI__sync_swap_4:
334 case Builtin::BI__sync_swap_8:
335 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000336 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000337#define BUILTIN(ID, TYPE, ATTRS)
338#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
339 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000340 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000341#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000342 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000343 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000344 return ExprError();
345 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000346 case Builtin::BI__builtin_addressof:
347 if (SemaBuiltinAddressof(*this, TheCall))
348 return ExprError();
349 break;
Richard Smith760520b2014-06-03 23:27:44 +0000350 case Builtin::BI__builtin_operator_new:
351 case Builtin::BI__builtin_operator_delete:
352 if (!getLangOpts().CPlusPlus) {
353 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
354 << (BuiltinID == Builtin::BI__builtin_operator_new
355 ? "__builtin_operator_new"
356 : "__builtin_operator_delete")
357 << "C++";
358 return ExprError();
359 }
360 // CodeGen assumes it can find the global new and delete to call,
361 // so ensure that they are declared.
362 DeclareGlobalNewDelete();
363 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000364
365 // check secure string manipulation functions where overflows
366 // are detectable at compile time
367 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000368 case Builtin::BI__builtin___memmove_chk:
369 case Builtin::BI__builtin___memset_chk:
370 case Builtin::BI__builtin___strlcat_chk:
371 case Builtin::BI__builtin___strlcpy_chk:
372 case Builtin::BI__builtin___strncat_chk:
373 case Builtin::BI__builtin___strncpy_chk:
374 case Builtin::BI__builtin___stpncpy_chk:
375 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
376 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000377 case Builtin::BI__builtin___memccpy_chk:
378 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
379 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000380 case Builtin::BI__builtin___snprintf_chk:
381 case Builtin::BI__builtin___vsnprintf_chk:
382 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
383 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000384 }
Richard Smith760520b2014-06-03 23:27:44 +0000385
Nate Begeman4904e322010-06-08 02:47:44 +0000386 // Since the target specific builtins for each arch overlap, only check those
387 // of the arch we are compiling for.
388 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000389 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000390 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000391 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000392 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000393 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000394 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
395 return ExprError();
396 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000397 case llvm::Triple::aarch64:
398 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000399 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000400 return ExprError();
401 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000402 case llvm::Triple::mips:
403 case llvm::Triple::mipsel:
404 case llvm::Triple::mips64:
405 case llvm::Triple::mips64el:
406 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
407 return ExprError();
408 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000409 case llvm::Triple::x86:
410 case llvm::Triple::x86_64:
411 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
412 return ExprError();
413 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000414 default:
415 break;
416 }
417 }
418
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000419 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000420}
421
Nate Begeman91e1fea2010-06-14 05:21:25 +0000422// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000423static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000424 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000425 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000426 switch (Type.getEltType()) {
427 case NeonTypeFlags::Int8:
428 case NeonTypeFlags::Poly8:
429 return shift ? 7 : (8 << IsQuad) - 1;
430 case NeonTypeFlags::Int16:
431 case NeonTypeFlags::Poly16:
432 return shift ? 15 : (4 << IsQuad) - 1;
433 case NeonTypeFlags::Int32:
434 return shift ? 31 : (2 << IsQuad) - 1;
435 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000436 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000437 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000438 case NeonTypeFlags::Poly128:
439 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000440 case NeonTypeFlags::Float16:
441 assert(!shift && "cannot shift float types!");
442 return (4 << IsQuad) - 1;
443 case NeonTypeFlags::Float32:
444 assert(!shift && "cannot shift float types!");
445 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000446 case NeonTypeFlags::Float64:
447 assert(!shift && "cannot shift float types!");
448 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000449 }
David Blaikie8a40f702012-01-17 06:56:22 +0000450 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000451}
452
Bob Wilsone4d77232011-11-08 05:04:11 +0000453/// getNeonEltType - Return the QualType corresponding to the elements of
454/// the vector type specified by the NeonTypeFlags. This is used to check
455/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000456static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000457 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000458 switch (Flags.getEltType()) {
459 case NeonTypeFlags::Int8:
460 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
461 case NeonTypeFlags::Int16:
462 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
463 case NeonTypeFlags::Int32:
464 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
465 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000466 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000467 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
468 else
469 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
470 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000471 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000472 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000473 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000474 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000475 case NeonTypeFlags::Poly64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000476 return Context.UnsignedLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000477 case NeonTypeFlags::Poly128:
478 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000479 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000480 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000481 case NeonTypeFlags::Float32:
482 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000483 case NeonTypeFlags::Float64:
484 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000485 }
David Blaikie8a40f702012-01-17 06:56:22 +0000486 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000487}
488
Tim Northover12670412014-02-19 10:37:05 +0000489bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000490 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000491 uint64_t mask = 0;
492 unsigned TV = 0;
493 int PtrArgNum = -1;
494 bool HasConstPtr = false;
495 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000496#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000497#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000498#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000499 }
500
501 // For NEON intrinsics which are overloaded on vector element type, validate
502 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000503 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000504 if (mask) {
505 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
506 return true;
507
508 TV = Result.getLimitedValue(64);
509 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
510 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000511 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000512 }
513
514 if (PtrArgNum >= 0) {
515 // Check that pointer arguments have the specified type.
516 Expr *Arg = TheCall->getArg(PtrArgNum);
517 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
518 Arg = ICE->getSubExpr();
519 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
520 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000521
Tim Northovera2ee4332014-03-29 15:09:45 +0000522 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000523 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000524 bool IsInt64Long =
525 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
526 QualType EltTy =
527 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000528 if (HasConstPtr)
529 EltTy = EltTy.withConst();
530 QualType LHSTy = Context.getPointerType(EltTy);
531 AssignConvertType ConvTy;
532 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
533 if (RHS.isInvalid())
534 return true;
535 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
536 RHS.get(), AA_Assigning))
537 return true;
538 }
539
540 // For NEON intrinsics which take an immediate value as part of the
541 // instruction, range check them here.
542 unsigned i = 0, l = 0, u = 0;
543 switch (BuiltinID) {
544 default:
545 return false;
Tim Northover12670412014-02-19 10:37:05 +0000546#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000547#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000548#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000549 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000550
Richard Sandiford28940af2014-04-16 08:47:51 +0000551 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000552}
553
Tim Northovera2ee4332014-03-29 15:09:45 +0000554bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
555 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000556 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000557 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000558 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000559 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000560 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000561 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
562 BuiltinID == AArch64::BI__builtin_arm_strex ||
563 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000564 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000565 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000566 BuiltinID == ARM::BI__builtin_arm_ldaex ||
567 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
568 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000569
570 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
571
572 // Ensure that we have the proper number of arguments.
573 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
574 return true;
575
576 // Inspect the pointer argument of the atomic builtin. This should always be
577 // a pointer type, whose element is an integral scalar or pointer type.
578 // Because it is a pointer type, we don't have to worry about any implicit
579 // casts here.
580 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
581 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
582 if (PointerArgRes.isInvalid())
583 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000584 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000585
586 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
587 if (!pointerType) {
588 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
589 << PointerArg->getType() << PointerArg->getSourceRange();
590 return true;
591 }
592
593 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
594 // task is to insert the appropriate casts into the AST. First work out just
595 // what the appropriate type is.
596 QualType ValType = pointerType->getPointeeType();
597 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
598 if (IsLdrex)
599 AddrType.addConst();
600
601 // Issue a warning if the cast is dodgy.
602 CastKind CastNeeded = CK_NoOp;
603 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
604 CastNeeded = CK_BitCast;
605 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
606 << PointerArg->getType()
607 << Context.getPointerType(AddrType)
608 << AA_Passing << PointerArg->getSourceRange();
609 }
610
611 // Finally, do the cast and replace the argument with the corrected version.
612 AddrType = Context.getPointerType(AddrType);
613 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
614 if (PointerArgRes.isInvalid())
615 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000616 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000617
618 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
619
620 // In general, we allow ints, floats and pointers to be loaded and stored.
621 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
622 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
623 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
624 << PointerArg->getType() << PointerArg->getSourceRange();
625 return true;
626 }
627
628 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000629 if (Context.getTypeSize(ValType) > MaxWidth) {
630 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000631 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
632 << PointerArg->getType() << PointerArg->getSourceRange();
633 return true;
634 }
635
636 switch (ValType.getObjCLifetime()) {
637 case Qualifiers::OCL_None:
638 case Qualifiers::OCL_ExplicitNone:
639 // okay
640 break;
641
642 case Qualifiers::OCL_Weak:
643 case Qualifiers::OCL_Strong:
644 case Qualifiers::OCL_Autoreleasing:
645 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
646 << ValType << PointerArg->getSourceRange();
647 return true;
648 }
649
650
651 if (IsLdrex) {
652 TheCall->setType(ValType);
653 return false;
654 }
655
656 // Initialize the argument to be stored.
657 ExprResult ValArg = TheCall->getArg(0);
658 InitializedEntity Entity = InitializedEntity::InitializeParameter(
659 Context, ValType, /*consume*/ false);
660 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
661 if (ValArg.isInvalid())
662 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000663 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000664
665 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
666 // but the custom checker bypasses all default analysis.
667 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000668 return false;
669}
670
Nate Begeman4904e322010-06-08 02:47:44 +0000671bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000672 llvm::APSInt Result;
673
Tim Northover6aacd492013-07-16 09:47:53 +0000674 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000675 BuiltinID == ARM::BI__builtin_arm_ldaex ||
676 BuiltinID == ARM::BI__builtin_arm_strex ||
677 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000678 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000679 }
680
Yi Kong26d104a2014-08-13 19:18:14 +0000681 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
682 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
683 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
684 }
685
Tim Northover12670412014-02-19 10:37:05 +0000686 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
687 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000688
Yi Kong4efadfb2014-07-03 16:01:25 +0000689 // For intrinsics which take an immediate value as part of the instruction,
690 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000691 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000692 switch (BuiltinID) {
693 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000694 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
695 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000696 case ARM::BI__builtin_arm_vcvtr_f:
697 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000698 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +0000699 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +0000700 case ARM::BI__builtin_arm_isb:
701 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000702 }
Nate Begemand773fe62010-06-13 04:47:52 +0000703
Nate Begemanf568b072010-08-03 21:32:34 +0000704 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000705 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000706}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000707
Tim Northover573cbee2014-05-24 12:52:07 +0000708bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000709 CallExpr *TheCall) {
710 llvm::APSInt Result;
711
Tim Northover573cbee2014-05-24 12:52:07 +0000712 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000713 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
714 BuiltinID == AArch64::BI__builtin_arm_strex ||
715 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000716 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
717 }
718
Yi Konga5548432014-08-13 19:18:20 +0000719 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
720 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
721 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
722 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
723 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
724 }
725
Tim Northovera2ee4332014-03-29 15:09:45 +0000726 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
727 return true;
728
Yi Kong19a29ac2014-07-17 10:52:06 +0000729 // For intrinsics which take an immediate value as part of the instruction,
730 // range check them here.
731 unsigned i = 0, l = 0, u = 0;
732 switch (BuiltinID) {
733 default: return false;
734 case AArch64::BI__builtin_arm_dmb:
735 case AArch64::BI__builtin_arm_dsb:
736 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
737 }
738
Yi Kong19a29ac2014-07-17 10:52:06 +0000739 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +0000740}
741
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000742bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
743 unsigned i = 0, l = 0, u = 0;
744 switch (BuiltinID) {
745 default: return false;
746 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
747 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000748 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
749 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
750 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
751 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
752 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000753 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000754
Richard Sandiford28940af2014-04-16 08:47:51 +0000755 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000756}
757
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000758bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
759 switch (BuiltinID) {
760 case X86::BI_mm_prefetch:
Richard Sandiford28940af2014-04-16 08:47:51 +0000761 // This is declared to take (const char*, int)
762 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000763 }
764 return false;
765}
766
Richard Smith55ce3522012-06-25 20:30:08 +0000767/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
768/// parameter with the FormatAttr's correct format_idx and firstDataArg.
769/// Returns true when the format fits the function and the FormatStringInfo has
770/// been populated.
771bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
772 FormatStringInfo *FSI) {
773 FSI->HasVAListArg = Format->getFirstArg() == 0;
774 FSI->FormatIdx = Format->getFormatIdx() - 1;
775 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000776
Richard Smith55ce3522012-06-25 20:30:08 +0000777 // The way the format attribute works in GCC, the implicit this argument
778 // of member functions is counted. However, it doesn't appear in our own
779 // lists, so decrement format_idx in that case.
780 if (IsCXXMember) {
781 if(FSI->FormatIdx == 0)
782 return false;
783 --FSI->FormatIdx;
784 if (FSI->FirstDataArg != 0)
785 --FSI->FirstDataArg;
786 }
787 return true;
788}
Mike Stump11289f42009-09-09 15:08:12 +0000789
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000790/// Checks if a the given expression evaluates to null.
791///
792/// \brief Returns true if the value evaluates to null.
793static bool CheckNonNullExpr(Sema &S,
794 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000795 // As a special case, transparent unions initialized with zero are
796 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000797 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000798 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
799 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000800 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000801 if (const InitListExpr *ILE =
802 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000803 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000804 }
805
806 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000807 return (!Expr->isValueDependent() &&
808 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
809 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000810}
811
812static void CheckNonNullArgument(Sema &S,
813 const Expr *ArgExpr,
814 SourceLocation CallSiteLoc) {
815 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000816 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
817}
818
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000819bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
820 FormatStringInfo FSI;
821 if ((GetFormatStringType(Format) == FST_NSString) &&
822 getFormatStringInfo(Format, false, &FSI)) {
823 Idx = FSI.FormatIdx;
824 return true;
825 }
826 return false;
827}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000828/// \brief Diagnose use of %s directive in an NSString which is being passed
829/// as formatting string to formatting method.
830static void
831DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
832 const NamedDecl *FDecl,
833 Expr **Args,
834 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000835 unsigned Idx = 0;
836 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000837 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
838 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000839 Idx = 2;
840 Format = true;
841 }
842 else
843 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
844 if (S.GetFormatNSStringIdx(I, Idx)) {
845 Format = true;
846 break;
847 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000848 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000849 if (!Format || NumArgs <= Idx)
850 return;
851 const Expr *FormatExpr = Args[Idx];
852 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
853 FormatExpr = CSCE->getSubExpr();
854 const StringLiteral *FormatString;
855 if (const ObjCStringLiteral *OSL =
856 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
857 FormatString = OSL->getString();
858 else
859 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
860 if (!FormatString)
861 return;
862 if (S.FormatStringHasSArg(FormatString)) {
863 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
864 << "%s" << 1 << 1;
865 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
866 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000867 }
868}
869
Ted Kremenek2bc73332014-01-17 06:24:43 +0000870static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +0000871 const NamedDecl *FDecl,
Richard Smith588bd9b2014-08-27 04:59:42 +0000872 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +0000873 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000874 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +0000875 llvm::SmallBitVector NonNullArgs;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000876 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Richard Smith588bd9b2014-08-27 04:59:42 +0000877 if (!NonNull->args_size()) {
878 // Easy case: all pointer arguments are nonnull.
879 for (const auto *Arg : Args)
Hal Finkelee90a222014-09-26 05:04:30 +0000880 if (S.isValidPointerAttrType(Arg->getType()))
Richard Smith588bd9b2014-08-27 04:59:42 +0000881 CheckNonNullArgument(S, Arg, CallSiteLoc);
882 return;
883 }
884
885 for (unsigned Val : NonNull->args()) {
886 if (Val >= Args.size())
887 continue;
888 if (NonNullArgs.empty())
889 NonNullArgs.resize(Args.size());
890 NonNullArgs.set(Val);
891 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000892 }
Ted Kremenek9aedc152014-01-17 06:24:56 +0000893
894 // Check the attributes on the parameters.
895 ArrayRef<ParmVarDecl*> parms;
896 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
897 parms = FD->parameters();
898 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
899 parms = MD->parameters();
900
Richard Smith588bd9b2014-08-27 04:59:42 +0000901 unsigned ArgIndex = 0;
Ted Kremenek9aedc152014-01-17 06:24:56 +0000902 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
Richard Smith588bd9b2014-08-27 04:59:42 +0000903 I != E; ++I, ++ArgIndex) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000904 const ParmVarDecl *PVD = *I;
Richard Smith588bd9b2014-08-27 04:59:42 +0000905 if (PVD->hasAttr<NonNullAttr>() ||
906 (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
907 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek9aedc152014-01-17 06:24:56 +0000908 }
Richard Smith588bd9b2014-08-27 04:59:42 +0000909
910 // In case this is a variadic call, check any remaining arguments.
911 for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
912 if (NonNullArgs[ArgIndex])
913 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +0000914}
915
Richard Smith55ce3522012-06-25 20:30:08 +0000916/// Handles the checks for format strings, non-POD arguments to vararg
917/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000918void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
919 unsigned NumParams, bool IsMemberFunction,
920 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +0000921 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +0000922 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +0000923 if (CurContext->isDependentContext())
924 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000925
Ted Kremenekb8176da2010-09-09 04:33:05 +0000926 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +0000927 llvm::SmallBitVector CheckedVarArgs;
928 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000929 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000930 // Only create vector if there are format attributes.
931 CheckedVarArgs.resize(Args.size());
932
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000933 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000934 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000935 }
Richard Smithd7293d72013-08-05 18:49:43 +0000936 }
Richard Smith55ce3522012-06-25 20:30:08 +0000937
938 // Refuse POD arguments that weren't caught by the format string
939 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +0000940 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000941 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000942 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +0000943 if (const Expr *Arg = Args[ArgIdx]) {
944 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
945 checkVariadicArgument(Arg, CallType);
946 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000947 }
Richard Smithd7293d72013-08-05 18:49:43 +0000948 }
Mike Stump11289f42009-09-09 15:08:12 +0000949
Richard Trieu41bc0992013-06-22 00:20:41 +0000950 if (FDecl) {
Richard Smith588bd9b2014-08-27 04:59:42 +0000951 CheckNonNullArguments(*this, FDecl, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000952
Richard Trieu41bc0992013-06-22 00:20:41 +0000953 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000954 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
955 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000956 }
Richard Smith55ce3522012-06-25 20:30:08 +0000957}
958
959/// CheckConstructorCall - Check a constructor call for correctness and safety
960/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000961void Sema::CheckConstructorCall(FunctionDecl *FDecl,
962 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +0000963 const FunctionProtoType *Proto,
964 SourceLocation Loc) {
965 VariadicCallType CallType =
966 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +0000967 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +0000968 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
969}
970
971/// CheckFunctionCall - Check a direct function call for various correctness
972/// and safety properties not strictly enforced by the C type system.
973bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
974 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000975 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
976 isa<CXXMethodDecl>(FDecl);
977 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
978 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +0000979 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
980 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000981 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +0000982 Expr** Args = TheCall->getArgs();
983 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +0000984 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000985 // If this is a call to a member operator, hide the first argument
986 // from checkCall.
987 // FIXME: Our choice of AST representation here is less than ideal.
988 ++Args;
989 --NumArgs;
990 }
Craig Topper8c2a2a02014-08-30 16:55:39 +0000991 checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +0000992 IsMemberFunction, TheCall->getRParenLoc(),
993 TheCall->getCallee()->getSourceRange(), CallType);
994
995 IdentifierInfo *FnInfo = FDecl->getIdentifier();
996 // None of the checks below are needed for functions that don't have
997 // simple names (e.g., C++ conversion functions).
998 if (!FnInfo)
999 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001000
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001001 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001002 if (getLangOpts().ObjC1)
1003 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001004
Anna Zaks22122702012-01-17 00:37:07 +00001005 unsigned CMId = FDecl->getMemoryFunctionKind();
1006 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001007 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001008
Anna Zaks201d4892012-01-13 21:52:01 +00001009 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001010 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001011 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001012 else if (CMId == Builtin::BIstrncat)
1013 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001014 else
Anna Zaks22122702012-01-17 00:37:07 +00001015 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001016
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001017 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001018}
1019
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001020bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001021 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001022 VariadicCallType CallType =
1023 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001024
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001025 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +00001026 /*IsMemberFunction=*/false,
1027 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001028
1029 return false;
1030}
1031
Richard Trieu664c4c62013-06-20 21:03:13 +00001032bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1033 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001034 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
1035 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001036 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001037
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001038 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +00001039 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001040 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001041
Richard Trieu664c4c62013-06-20 21:03:13 +00001042 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001043 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001044 CallType = VariadicDoesNotApply;
1045 } else if (Ty->isBlockPointerType()) {
1046 CallType = VariadicBlock;
1047 } else { // Ty->isFunctionPointerType()
1048 CallType = VariadicFunction;
1049 }
Alp Toker9cacbab2014-01-20 20:26:09 +00001050 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001051
Craig Topper8c2a2a02014-08-30 16:55:39 +00001052 checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
1053 TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001054 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001055 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001056
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001057 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001058}
1059
Richard Trieu41bc0992013-06-22 00:20:41 +00001060/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1061/// such as function pointers returned from functions.
1062bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001063 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001064 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001065 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +00001066
Craig Topperc3ec1492014-05-26 06:22:03 +00001067 checkCall(/*FDecl=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001068 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001069 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001070 TheCall->getCallee()->getSourceRange(), CallType);
1071
1072 return false;
1073}
1074
Tim Northovere94a34c2014-03-11 10:49:14 +00001075static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1076 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1077 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1078 return false;
1079
1080 switch (Op) {
1081 case AtomicExpr::AO__c11_atomic_init:
1082 llvm_unreachable("There is no ordering argument for an init");
1083
1084 case AtomicExpr::AO__c11_atomic_load:
1085 case AtomicExpr::AO__atomic_load_n:
1086 case AtomicExpr::AO__atomic_load:
1087 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1088 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1089
1090 case AtomicExpr::AO__c11_atomic_store:
1091 case AtomicExpr::AO__atomic_store:
1092 case AtomicExpr::AO__atomic_store_n:
1093 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1094 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1095 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1096
1097 default:
1098 return true;
1099 }
1100}
1101
Richard Smithfeea8832012-04-12 05:08:17 +00001102ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1103 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001104 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1105 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001106
Richard Smithfeea8832012-04-12 05:08:17 +00001107 // All these operations take one of the following forms:
1108 enum {
1109 // C __c11_atomic_init(A *, C)
1110 Init,
1111 // C __c11_atomic_load(A *, int)
1112 Load,
1113 // void __atomic_load(A *, CP, int)
1114 Copy,
1115 // C __c11_atomic_add(A *, M, int)
1116 Arithmetic,
1117 // C __atomic_exchange_n(A *, CP, int)
1118 Xchg,
1119 // void __atomic_exchange(A *, C *, CP, int)
1120 GNUXchg,
1121 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1122 C11CmpXchg,
1123 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1124 GNUCmpXchg
1125 } Form = Init;
1126 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1127 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1128 // where:
1129 // C is an appropriate type,
1130 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1131 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1132 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1133 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001134
Richard Smithfeea8832012-04-12 05:08:17 +00001135 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1136 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
1137 && "need to update code for modified C11 atomics");
1138 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1139 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1140 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1141 Op == AtomicExpr::AO__atomic_store_n ||
1142 Op == AtomicExpr::AO__atomic_exchange_n ||
1143 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1144 bool IsAddSub = false;
1145
1146 switch (Op) {
1147 case AtomicExpr::AO__c11_atomic_init:
1148 Form = Init;
1149 break;
1150
1151 case AtomicExpr::AO__c11_atomic_load:
1152 case AtomicExpr::AO__atomic_load_n:
1153 Form = Load;
1154 break;
1155
1156 case AtomicExpr::AO__c11_atomic_store:
1157 case AtomicExpr::AO__atomic_load:
1158 case AtomicExpr::AO__atomic_store:
1159 case AtomicExpr::AO__atomic_store_n:
1160 Form = Copy;
1161 break;
1162
1163 case AtomicExpr::AO__c11_atomic_fetch_add:
1164 case AtomicExpr::AO__c11_atomic_fetch_sub:
1165 case AtomicExpr::AO__atomic_fetch_add:
1166 case AtomicExpr::AO__atomic_fetch_sub:
1167 case AtomicExpr::AO__atomic_add_fetch:
1168 case AtomicExpr::AO__atomic_sub_fetch:
1169 IsAddSub = true;
1170 // Fall through.
1171 case AtomicExpr::AO__c11_atomic_fetch_and:
1172 case AtomicExpr::AO__c11_atomic_fetch_or:
1173 case AtomicExpr::AO__c11_atomic_fetch_xor:
1174 case AtomicExpr::AO__atomic_fetch_and:
1175 case AtomicExpr::AO__atomic_fetch_or:
1176 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001177 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001178 case AtomicExpr::AO__atomic_and_fetch:
1179 case AtomicExpr::AO__atomic_or_fetch:
1180 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001181 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001182 Form = Arithmetic;
1183 break;
1184
1185 case AtomicExpr::AO__c11_atomic_exchange:
1186 case AtomicExpr::AO__atomic_exchange_n:
1187 Form = Xchg;
1188 break;
1189
1190 case AtomicExpr::AO__atomic_exchange:
1191 Form = GNUXchg;
1192 break;
1193
1194 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1195 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1196 Form = C11CmpXchg;
1197 break;
1198
1199 case AtomicExpr::AO__atomic_compare_exchange:
1200 case AtomicExpr::AO__atomic_compare_exchange_n:
1201 Form = GNUCmpXchg;
1202 break;
1203 }
1204
1205 // Check we have the right number of arguments.
1206 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001207 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001208 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001209 << TheCall->getCallee()->getSourceRange();
1210 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001211 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1212 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001213 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001214 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001215 << TheCall->getCallee()->getSourceRange();
1216 return ExprError();
1217 }
1218
Richard Smithfeea8832012-04-12 05:08:17 +00001219 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001220 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001221 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1222 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1223 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001224 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001225 << Ptr->getType() << Ptr->getSourceRange();
1226 return ExprError();
1227 }
1228
Richard Smithfeea8832012-04-12 05:08:17 +00001229 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1230 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1231 QualType ValType = AtomTy; // 'C'
1232 if (IsC11) {
1233 if (!AtomTy->isAtomicType()) {
1234 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1235 << Ptr->getType() << Ptr->getSourceRange();
1236 return ExprError();
1237 }
Richard Smithe00921a2012-09-15 06:09:58 +00001238 if (AtomTy.isConstQualified()) {
1239 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1240 << Ptr->getType() << Ptr->getSourceRange();
1241 return ExprError();
1242 }
Richard Smithfeea8832012-04-12 05:08:17 +00001243 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001244 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001245
Richard Smithfeea8832012-04-12 05:08:17 +00001246 // For an arithmetic operation, the implied arithmetic must be well-formed.
1247 if (Form == Arithmetic) {
1248 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1249 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1250 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1251 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1252 return ExprError();
1253 }
1254 if (!IsAddSub && !ValType->isIntegerType()) {
1255 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1256 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1257 return ExprError();
1258 }
1259 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1260 // For __atomic_*_n operations, the value type must be a scalar integral or
1261 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001262 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001263 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1264 return ExprError();
1265 }
1266
Eli Friedmanaa769812013-09-11 03:49:34 +00001267 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1268 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001269 // For GNU atomics, require a trivially-copyable type. This is not part of
1270 // the GNU atomics specification, but we enforce it for sanity.
1271 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001272 << Ptr->getType() << Ptr->getSourceRange();
1273 return ExprError();
1274 }
1275
Richard Smithfeea8832012-04-12 05:08:17 +00001276 // FIXME: For any builtin other than a load, the ValType must not be
1277 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001278
1279 switch (ValType.getObjCLifetime()) {
1280 case Qualifiers::OCL_None:
1281 case Qualifiers::OCL_ExplicitNone:
1282 // okay
1283 break;
1284
1285 case Qualifiers::OCL_Weak:
1286 case Qualifiers::OCL_Strong:
1287 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001288 // FIXME: Can this happen? By this point, ValType should be known
1289 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001290 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1291 << ValType << Ptr->getSourceRange();
1292 return ExprError();
1293 }
1294
1295 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001296 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001297 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001298 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001299 ResultType = Context.BoolTy;
1300
Richard Smithfeea8832012-04-12 05:08:17 +00001301 // The type of a parameter passed 'by value'. In the GNU atomics, such
1302 // arguments are actually passed as pointers.
1303 QualType ByValType = ValType; // 'CP'
1304 if (!IsC11 && !IsN)
1305 ByValType = Ptr->getType();
1306
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001307 // The first argument --- the pointer --- has a fixed type; we
1308 // deduce the types of the rest of the arguments accordingly. Walk
1309 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001310 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001311 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001312 if (i < NumVals[Form] + 1) {
1313 switch (i) {
1314 case 1:
1315 // The second argument is the non-atomic operand. For arithmetic, this
1316 // is always passed by value, and for a compare_exchange it is always
1317 // passed by address. For the rest, GNU uses by-address and C11 uses
1318 // by-value.
1319 assert(Form != Load);
1320 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1321 Ty = ValType;
1322 else if (Form == Copy || Form == Xchg)
1323 Ty = ByValType;
1324 else if (Form == Arithmetic)
1325 Ty = Context.getPointerDiffType();
1326 else
1327 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1328 break;
1329 case 2:
1330 // The third argument to compare_exchange / GNU exchange is a
1331 // (pointer to a) desired value.
1332 Ty = ByValType;
1333 break;
1334 case 3:
1335 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1336 Ty = Context.BoolTy;
1337 break;
1338 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001339 } else {
1340 // The order(s) are always converted to int.
1341 Ty = Context.IntTy;
1342 }
Richard Smithfeea8832012-04-12 05:08:17 +00001343
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001344 InitializedEntity Entity =
1345 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001346 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001347 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1348 if (Arg.isInvalid())
1349 return true;
1350 TheCall->setArg(i, Arg.get());
1351 }
1352
Richard Smithfeea8832012-04-12 05:08:17 +00001353 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001354 SmallVector<Expr*, 5> SubExprs;
1355 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001356 switch (Form) {
1357 case Init:
1358 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001359 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001360 break;
1361 case Load:
1362 SubExprs.push_back(TheCall->getArg(1)); // Order
1363 break;
1364 case Copy:
1365 case Arithmetic:
1366 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001367 SubExprs.push_back(TheCall->getArg(2)); // Order
1368 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001369 break;
1370 case GNUXchg:
1371 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1372 SubExprs.push_back(TheCall->getArg(3)); // Order
1373 SubExprs.push_back(TheCall->getArg(1)); // Val1
1374 SubExprs.push_back(TheCall->getArg(2)); // Val2
1375 break;
1376 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001377 SubExprs.push_back(TheCall->getArg(3)); // Order
1378 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001379 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001380 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001381 break;
1382 case GNUCmpXchg:
1383 SubExprs.push_back(TheCall->getArg(4)); // Order
1384 SubExprs.push_back(TheCall->getArg(1)); // Val1
1385 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1386 SubExprs.push_back(TheCall->getArg(2)); // Val2
1387 SubExprs.push_back(TheCall->getArg(3)); // Weak
1388 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001389 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001390
1391 if (SubExprs.size() >= 2 && Form != Init) {
1392 llvm::APSInt Result(32);
1393 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1394 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001395 Diag(SubExprs[1]->getLocStart(),
1396 diag::warn_atomic_op_has_invalid_memory_order)
1397 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001398 }
1399
Fariborz Jahanian615de762013-05-28 17:37:39 +00001400 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1401 SubExprs, ResultType, Op,
1402 TheCall->getRParenLoc());
1403
1404 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1405 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1406 Context.AtomicUsesUnsupportedLibcall(AE))
1407 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1408 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001409
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001410 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001411}
1412
1413
John McCall29ad95b2011-08-27 01:09:30 +00001414/// checkBuiltinArgument - Given a call to a builtin function, perform
1415/// normal type-checking on the given argument, updating the call in
1416/// place. This is useful when a builtin function requires custom
1417/// type-checking for some of its arguments but not necessarily all of
1418/// them.
1419///
1420/// Returns true on error.
1421static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1422 FunctionDecl *Fn = E->getDirectCallee();
1423 assert(Fn && "builtin call without direct callee!");
1424
1425 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1426 InitializedEntity Entity =
1427 InitializedEntity::InitializeParameter(S.Context, Param);
1428
1429 ExprResult Arg = E->getArg(0);
1430 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1431 if (Arg.isInvalid())
1432 return true;
1433
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001434 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001435 return false;
1436}
1437
Chris Lattnerdc046542009-05-08 06:58:22 +00001438/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1439/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1440/// type of its first argument. The main ActOnCallExpr routines have already
1441/// promoted the types of arguments because all of these calls are prototyped as
1442/// void(...).
1443///
1444/// This function goes through and does final semantic checking for these
1445/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001446ExprResult
1447Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001448 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001449 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1450 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1451
1452 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001453 if (TheCall->getNumArgs() < 1) {
1454 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1455 << 0 << 1 << TheCall->getNumArgs()
1456 << TheCall->getCallee()->getSourceRange();
1457 return ExprError();
1458 }
Mike Stump11289f42009-09-09 15:08:12 +00001459
Chris Lattnerdc046542009-05-08 06:58:22 +00001460 // Inspect the first argument of the atomic builtin. This should always be
1461 // a pointer type, whose element is an integral scalar or pointer type.
1462 // Because it is a pointer type, we don't have to worry about any implicit
1463 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001464 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001465 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001466 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1467 if (FirstArgResult.isInvalid())
1468 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001469 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001470 TheCall->setArg(0, FirstArg);
1471
John McCall31168b02011-06-15 23:02:42 +00001472 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1473 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001474 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1475 << FirstArg->getType() << FirstArg->getSourceRange();
1476 return ExprError();
1477 }
Mike Stump11289f42009-09-09 15:08:12 +00001478
John McCall31168b02011-06-15 23:02:42 +00001479 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001480 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001481 !ValType->isBlockPointerType()) {
1482 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1483 << FirstArg->getType() << FirstArg->getSourceRange();
1484 return ExprError();
1485 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001486
John McCall31168b02011-06-15 23:02:42 +00001487 switch (ValType.getObjCLifetime()) {
1488 case Qualifiers::OCL_None:
1489 case Qualifiers::OCL_ExplicitNone:
1490 // okay
1491 break;
1492
1493 case Qualifiers::OCL_Weak:
1494 case Qualifiers::OCL_Strong:
1495 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001496 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001497 << ValType << FirstArg->getSourceRange();
1498 return ExprError();
1499 }
1500
John McCallb50451a2011-10-05 07:41:44 +00001501 // Strip any qualifiers off ValType.
1502 ValType = ValType.getUnqualifiedType();
1503
Chandler Carruth3973af72010-07-18 20:54:12 +00001504 // The majority of builtins return a value, but a few have special return
1505 // types, so allow them to override appropriately below.
1506 QualType ResultType = ValType;
1507
Chris Lattnerdc046542009-05-08 06:58:22 +00001508 // We need to figure out which concrete builtin this maps onto. For example,
1509 // __sync_fetch_and_add with a 2 byte object turns into
1510 // __sync_fetch_and_add_2.
1511#define BUILTIN_ROW(x) \
1512 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1513 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001514
Chris Lattnerdc046542009-05-08 06:58:22 +00001515 static const unsigned BuiltinIndices[][5] = {
1516 BUILTIN_ROW(__sync_fetch_and_add),
1517 BUILTIN_ROW(__sync_fetch_and_sub),
1518 BUILTIN_ROW(__sync_fetch_and_or),
1519 BUILTIN_ROW(__sync_fetch_and_and),
1520 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +00001521
Chris Lattnerdc046542009-05-08 06:58:22 +00001522 BUILTIN_ROW(__sync_add_and_fetch),
1523 BUILTIN_ROW(__sync_sub_and_fetch),
1524 BUILTIN_ROW(__sync_and_and_fetch),
1525 BUILTIN_ROW(__sync_or_and_fetch),
1526 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001527
Chris Lattnerdc046542009-05-08 06:58:22 +00001528 BUILTIN_ROW(__sync_val_compare_and_swap),
1529 BUILTIN_ROW(__sync_bool_compare_and_swap),
1530 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001531 BUILTIN_ROW(__sync_lock_release),
1532 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001533 };
Mike Stump11289f42009-09-09 15:08:12 +00001534#undef BUILTIN_ROW
1535
Chris Lattnerdc046542009-05-08 06:58:22 +00001536 // Determine the index of the size.
1537 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001538 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001539 case 1: SizeIndex = 0; break;
1540 case 2: SizeIndex = 1; break;
1541 case 4: SizeIndex = 2; break;
1542 case 8: SizeIndex = 3; break;
1543 case 16: SizeIndex = 4; break;
1544 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001545 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1546 << FirstArg->getType() << FirstArg->getSourceRange();
1547 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001548 }
Mike Stump11289f42009-09-09 15:08:12 +00001549
Chris Lattnerdc046542009-05-08 06:58:22 +00001550 // Each of these builtins has one pointer argument, followed by some number of
1551 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1552 // that we ignore. Find out which row of BuiltinIndices to read from as well
1553 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001554 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001555 unsigned BuiltinIndex, NumFixed = 1;
1556 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001557 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001558 case Builtin::BI__sync_fetch_and_add:
1559 case Builtin::BI__sync_fetch_and_add_1:
1560 case Builtin::BI__sync_fetch_and_add_2:
1561 case Builtin::BI__sync_fetch_and_add_4:
1562 case Builtin::BI__sync_fetch_and_add_8:
1563 case Builtin::BI__sync_fetch_and_add_16:
1564 BuiltinIndex = 0;
1565 break;
1566
1567 case Builtin::BI__sync_fetch_and_sub:
1568 case Builtin::BI__sync_fetch_and_sub_1:
1569 case Builtin::BI__sync_fetch_and_sub_2:
1570 case Builtin::BI__sync_fetch_and_sub_4:
1571 case Builtin::BI__sync_fetch_and_sub_8:
1572 case Builtin::BI__sync_fetch_and_sub_16:
1573 BuiltinIndex = 1;
1574 break;
1575
1576 case Builtin::BI__sync_fetch_and_or:
1577 case Builtin::BI__sync_fetch_and_or_1:
1578 case Builtin::BI__sync_fetch_and_or_2:
1579 case Builtin::BI__sync_fetch_and_or_4:
1580 case Builtin::BI__sync_fetch_and_or_8:
1581 case Builtin::BI__sync_fetch_and_or_16:
1582 BuiltinIndex = 2;
1583 break;
1584
1585 case Builtin::BI__sync_fetch_and_and:
1586 case Builtin::BI__sync_fetch_and_and_1:
1587 case Builtin::BI__sync_fetch_and_and_2:
1588 case Builtin::BI__sync_fetch_and_and_4:
1589 case Builtin::BI__sync_fetch_and_and_8:
1590 case Builtin::BI__sync_fetch_and_and_16:
1591 BuiltinIndex = 3;
1592 break;
Mike Stump11289f42009-09-09 15:08:12 +00001593
Douglas Gregor73722482011-11-28 16:30:08 +00001594 case Builtin::BI__sync_fetch_and_xor:
1595 case Builtin::BI__sync_fetch_and_xor_1:
1596 case Builtin::BI__sync_fetch_and_xor_2:
1597 case Builtin::BI__sync_fetch_and_xor_4:
1598 case Builtin::BI__sync_fetch_and_xor_8:
1599 case Builtin::BI__sync_fetch_and_xor_16:
1600 BuiltinIndex = 4;
1601 break;
1602
1603 case Builtin::BI__sync_add_and_fetch:
1604 case Builtin::BI__sync_add_and_fetch_1:
1605 case Builtin::BI__sync_add_and_fetch_2:
1606 case Builtin::BI__sync_add_and_fetch_4:
1607 case Builtin::BI__sync_add_and_fetch_8:
1608 case Builtin::BI__sync_add_and_fetch_16:
1609 BuiltinIndex = 5;
1610 break;
1611
1612 case Builtin::BI__sync_sub_and_fetch:
1613 case Builtin::BI__sync_sub_and_fetch_1:
1614 case Builtin::BI__sync_sub_and_fetch_2:
1615 case Builtin::BI__sync_sub_and_fetch_4:
1616 case Builtin::BI__sync_sub_and_fetch_8:
1617 case Builtin::BI__sync_sub_and_fetch_16:
1618 BuiltinIndex = 6;
1619 break;
1620
1621 case Builtin::BI__sync_and_and_fetch:
1622 case Builtin::BI__sync_and_and_fetch_1:
1623 case Builtin::BI__sync_and_and_fetch_2:
1624 case Builtin::BI__sync_and_and_fetch_4:
1625 case Builtin::BI__sync_and_and_fetch_8:
1626 case Builtin::BI__sync_and_and_fetch_16:
1627 BuiltinIndex = 7;
1628 break;
1629
1630 case Builtin::BI__sync_or_and_fetch:
1631 case Builtin::BI__sync_or_and_fetch_1:
1632 case Builtin::BI__sync_or_and_fetch_2:
1633 case Builtin::BI__sync_or_and_fetch_4:
1634 case Builtin::BI__sync_or_and_fetch_8:
1635 case Builtin::BI__sync_or_and_fetch_16:
1636 BuiltinIndex = 8;
1637 break;
1638
1639 case Builtin::BI__sync_xor_and_fetch:
1640 case Builtin::BI__sync_xor_and_fetch_1:
1641 case Builtin::BI__sync_xor_and_fetch_2:
1642 case Builtin::BI__sync_xor_and_fetch_4:
1643 case Builtin::BI__sync_xor_and_fetch_8:
1644 case Builtin::BI__sync_xor_and_fetch_16:
1645 BuiltinIndex = 9;
1646 break;
Mike Stump11289f42009-09-09 15:08:12 +00001647
Chris Lattnerdc046542009-05-08 06:58:22 +00001648 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001649 case Builtin::BI__sync_val_compare_and_swap_1:
1650 case Builtin::BI__sync_val_compare_and_swap_2:
1651 case Builtin::BI__sync_val_compare_and_swap_4:
1652 case Builtin::BI__sync_val_compare_and_swap_8:
1653 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001654 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +00001655 NumFixed = 2;
1656 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001657
Chris Lattnerdc046542009-05-08 06:58:22 +00001658 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001659 case Builtin::BI__sync_bool_compare_and_swap_1:
1660 case Builtin::BI__sync_bool_compare_and_swap_2:
1661 case Builtin::BI__sync_bool_compare_and_swap_4:
1662 case Builtin::BI__sync_bool_compare_and_swap_8:
1663 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001664 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +00001665 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001666 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001667 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001668
1669 case Builtin::BI__sync_lock_test_and_set:
1670 case Builtin::BI__sync_lock_test_and_set_1:
1671 case Builtin::BI__sync_lock_test_and_set_2:
1672 case Builtin::BI__sync_lock_test_and_set_4:
1673 case Builtin::BI__sync_lock_test_and_set_8:
1674 case Builtin::BI__sync_lock_test_and_set_16:
1675 BuiltinIndex = 12;
1676 break;
1677
Chris Lattnerdc046542009-05-08 06:58:22 +00001678 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001679 case Builtin::BI__sync_lock_release_1:
1680 case Builtin::BI__sync_lock_release_2:
1681 case Builtin::BI__sync_lock_release_4:
1682 case Builtin::BI__sync_lock_release_8:
1683 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001684 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001685 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001686 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001687 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001688
1689 case Builtin::BI__sync_swap:
1690 case Builtin::BI__sync_swap_1:
1691 case Builtin::BI__sync_swap_2:
1692 case Builtin::BI__sync_swap_4:
1693 case Builtin::BI__sync_swap_8:
1694 case Builtin::BI__sync_swap_16:
1695 BuiltinIndex = 14;
1696 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001697 }
Mike Stump11289f42009-09-09 15:08:12 +00001698
Chris Lattnerdc046542009-05-08 06:58:22 +00001699 // Now that we know how many fixed arguments we expect, first check that we
1700 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001701 if (TheCall->getNumArgs() < 1+NumFixed) {
1702 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1703 << 0 << 1+NumFixed << TheCall->getNumArgs()
1704 << TheCall->getCallee()->getSourceRange();
1705 return ExprError();
1706 }
Mike Stump11289f42009-09-09 15:08:12 +00001707
Chris Lattner5b9241b2009-05-08 15:36:58 +00001708 // Get the decl for the concrete builtin from this, we can tell what the
1709 // concrete integer type we should convert to is.
1710 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1711 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001712 FunctionDecl *NewBuiltinDecl;
1713 if (NewBuiltinID == BuiltinID)
1714 NewBuiltinDecl = FDecl;
1715 else {
1716 // Perform builtin lookup to avoid redeclaring it.
1717 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1718 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1719 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1720 assert(Res.getFoundDecl());
1721 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00001722 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001723 return ExprError();
1724 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001725
John McCallcf142162010-08-07 06:22:56 +00001726 // The first argument --- the pointer --- has a fixed type; we
1727 // deduce the types of the rest of the arguments accordingly. Walk
1728 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001729 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001730 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001731
Chris Lattnerdc046542009-05-08 06:58:22 +00001732 // GCC does an implicit conversion to the pointer or integer ValType. This
1733 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001734 // Initialize the argument.
1735 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1736 ValType, /*consume*/ false);
1737 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001738 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001739 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001740
Chris Lattnerdc046542009-05-08 06:58:22 +00001741 // Okay, we have something that *can* be converted to the right type. Check
1742 // to see if there is a potentially weird extension going on here. This can
1743 // happen when you do an atomic operation on something like an char* and
1744 // pass in 42. The 42 gets converted to char. This is even more strange
1745 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001746 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001747 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00001748 }
Mike Stump11289f42009-09-09 15:08:12 +00001749
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001750 ASTContext& Context = this->getASTContext();
1751
1752 // Create a new DeclRefExpr to refer to the new decl.
1753 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1754 Context,
1755 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001756 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001757 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001758 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001759 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001760 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001761 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001762
Chris Lattnerdc046542009-05-08 06:58:22 +00001763 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001764 // FIXME: This loses syntactic information.
1765 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1766 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1767 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001768 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00001769
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001770 // Change the result type of the call to match the original value type. This
1771 // is arbitrary, but the codegen for these builtins ins design to handle it
1772 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001773 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001774
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001775 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001776}
1777
Chris Lattner6436fb62009-02-18 06:01:06 +00001778/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001779/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001780/// Note: It might also make sense to do the UTF-16 conversion here (would
1781/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001782bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001783 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001784 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1785
Douglas Gregorfb65e592011-07-27 05:40:30 +00001786 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001787 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1788 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001789 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001790 }
Mike Stump11289f42009-09-09 15:08:12 +00001791
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001792 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001793 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001794 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001795 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001796 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001797 UTF16 *ToPtr = &ToBuf[0];
1798
1799 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1800 &ToPtr, ToPtr + NumBytes,
1801 strictConversion);
1802 // Check for conversion failure.
1803 if (Result != conversionOK)
1804 Diag(Arg->getLocStart(),
1805 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1806 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001807 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001808}
1809
Chris Lattnere202e6a2007-12-20 00:05:45 +00001810/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1811/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001812bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1813 Expr *Fn = TheCall->getCallee();
1814 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001815 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001816 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001817 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1818 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001819 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001820 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001821 return true;
1822 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001823
1824 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001825 return Diag(TheCall->getLocEnd(),
1826 diag::err_typecheck_call_too_few_args_at_least)
1827 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001828 }
1829
John McCall29ad95b2011-08-27 01:09:30 +00001830 // Type-check the first argument normally.
1831 if (checkBuiltinArgument(*this, TheCall, 0))
1832 return true;
1833
Chris Lattnere202e6a2007-12-20 00:05:45 +00001834 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001835 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001836 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001837 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001838 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001839 else if (FunctionDecl *FD = getCurFunctionDecl())
1840 isVariadic = FD->isVariadic();
1841 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001842 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001843
Chris Lattnere202e6a2007-12-20 00:05:45 +00001844 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001845 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1846 return true;
1847 }
Mike Stump11289f42009-09-09 15:08:12 +00001848
Chris Lattner43be2e62007-12-19 23:59:04 +00001849 // Verify that the second argument to the builtin is the last argument of the
1850 // current function or method.
1851 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001852 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001853
Nico Weber9eea7642013-05-24 23:31:57 +00001854 // These are valid if SecondArgIsLastNamedArgument is false after the next
1855 // block.
1856 QualType Type;
1857 SourceLocation ParamLoc;
1858
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001859 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1860 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001861 // FIXME: This isn't correct for methods (results in bogus warning).
1862 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001863 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001864 if (CurBlock)
1865 LastArg = *(CurBlock->TheDecl->param_end()-1);
1866 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001867 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001868 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001869 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001870 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00001871
1872 Type = PV->getType();
1873 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00001874 }
1875 }
Mike Stump11289f42009-09-09 15:08:12 +00001876
Chris Lattner43be2e62007-12-19 23:59:04 +00001877 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001878 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001879 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00001880 else if (Type->isReferenceType()) {
1881 Diag(Arg->getLocStart(),
1882 diag::warn_va_start_of_reference_type_is_undefined);
1883 Diag(ParamLoc, diag::note_parameter_type) << Type;
1884 }
1885
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00001886 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00001887 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001888}
Chris Lattner43be2e62007-12-19 23:59:04 +00001889
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00001890bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
1891 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
1892 // const char *named_addr);
1893
1894 Expr *Func = Call->getCallee();
1895
1896 if (Call->getNumArgs() < 3)
1897 return Diag(Call->getLocEnd(),
1898 diag::err_typecheck_call_too_few_args_at_least)
1899 << 0 /*function call*/ << 3 << Call->getNumArgs();
1900
1901 // Determine whether the current function is variadic or not.
1902 bool IsVariadic;
1903 if (BlockScopeInfo *CurBlock = getCurBlock())
1904 IsVariadic = CurBlock->TheDecl->isVariadic();
1905 else if (FunctionDecl *FD = getCurFunctionDecl())
1906 IsVariadic = FD->isVariadic();
1907 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1908 IsVariadic = MD->isVariadic();
1909 else
1910 llvm_unreachable("unexpected statement type");
1911
1912 if (!IsVariadic) {
1913 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1914 return true;
1915 }
1916
1917 // Type-check the first argument normally.
1918 if (checkBuiltinArgument(*this, Call, 0))
1919 return true;
1920
1921 static const struct {
1922 unsigned ArgNo;
1923 QualType Type;
1924 } ArgumentTypes[] = {
1925 { 1, Context.getPointerType(Context.CharTy.withConst()) },
1926 { 2, Context.getSizeType() },
1927 };
1928
1929 for (const auto &AT : ArgumentTypes) {
1930 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
1931 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
1932 continue;
1933 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
1934 << Arg->getType() << AT.Type << 1 /* different class */
1935 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
1936 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
1937 }
1938
1939 return false;
1940}
1941
Chris Lattner2da14fb2007-12-20 00:26:33 +00001942/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1943/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001944bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1945 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001946 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001947 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001948 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001949 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001950 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001951 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001952 << SourceRange(TheCall->getArg(2)->getLocStart(),
1953 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001954
John Wiegley01296292011-04-08 18:41:53 +00001955 ExprResult OrigArg0 = TheCall->getArg(0);
1956 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001957
Chris Lattner2da14fb2007-12-20 00:26:33 +00001958 // Do standard promotions between the two arguments, returning their common
1959 // type.
Chris Lattner08464942007-12-28 05:29:59 +00001960 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00001961 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1962 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00001963
1964 // Make sure any conversions are pushed back into the call; this is
1965 // type safe since unordered compare builtins are declared as "_Bool
1966 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00001967 TheCall->setArg(0, OrigArg0.get());
1968 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00001969
John Wiegley01296292011-04-08 18:41:53 +00001970 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00001971 return false;
1972
Chris Lattner2da14fb2007-12-20 00:26:33 +00001973 // If the common type isn't a real floating type, then the arguments were
1974 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001975 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00001976 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001977 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00001978 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1979 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001980
Chris Lattner2da14fb2007-12-20 00:26:33 +00001981 return false;
1982}
1983
Benjamin Kramer634fc102010-02-15 22:42:31 +00001984/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1985/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001986/// to check everything. We expect the last argument to be a floating point
1987/// value.
1988bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1989 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001990 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001991 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001992 if (TheCall->getNumArgs() > NumArgs)
1993 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001994 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001995 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001996 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001997 (*(TheCall->arg_end()-1))->getLocEnd());
1998
Benjamin Kramer64aae502010-02-16 10:07:31 +00001999 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002000
Eli Friedman7e4faac2009-08-31 20:06:00 +00002001 if (OrigArg->isTypeDependent())
2002 return false;
2003
Chris Lattner68784ef2010-05-06 05:50:07 +00002004 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002005 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002006 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002007 diag::err_typecheck_call_invalid_unary_fp)
2008 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002009
Chris Lattner68784ef2010-05-06 05:50:07 +00002010 // If this is an implicit conversion from float -> double, remove it.
2011 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2012 Expr *CastArg = Cast->getSubExpr();
2013 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2014 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2015 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002016 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002017 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002018 }
2019 }
2020
Eli Friedman7e4faac2009-08-31 20:06:00 +00002021 return false;
2022}
2023
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002024/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2025// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002026ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002027 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002028 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002029 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002030 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2031 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002032
Nate Begemana0110022010-06-08 00:16:34 +00002033 // Determine which of the following types of shufflevector we're checking:
2034 // 1) unary, vector mask: (lhs, mask)
2035 // 2) binary, vector mask: (lhs, rhs, mask)
2036 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2037 QualType resType = TheCall->getArg(0)->getType();
2038 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002039
Douglas Gregorc25f7662009-05-19 22:10:17 +00002040 if (!TheCall->getArg(0)->isTypeDependent() &&
2041 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002042 QualType LHSType = TheCall->getArg(0)->getType();
2043 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002044
Craig Topperbaca3892013-07-29 06:47:04 +00002045 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2046 return ExprError(Diag(TheCall->getLocStart(),
2047 diag::err_shufflevector_non_vector)
2048 << SourceRange(TheCall->getArg(0)->getLocStart(),
2049 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002050
Nate Begemana0110022010-06-08 00:16:34 +00002051 numElements = LHSType->getAs<VectorType>()->getNumElements();
2052 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002053
Nate Begemana0110022010-06-08 00:16:34 +00002054 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2055 // with mask. If so, verify that RHS is an integer vector type with the
2056 // same number of elts as lhs.
2057 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002058 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002059 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002060 return ExprError(Diag(TheCall->getLocStart(),
2061 diag::err_shufflevector_incompatible_vector)
2062 << SourceRange(TheCall->getArg(1)->getLocStart(),
2063 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002064 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002065 return ExprError(Diag(TheCall->getLocStart(),
2066 diag::err_shufflevector_incompatible_vector)
2067 << SourceRange(TheCall->getArg(0)->getLocStart(),
2068 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002069 } else if (numElements != numResElements) {
2070 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002071 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002072 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002073 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002074 }
2075
2076 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002077 if (TheCall->getArg(i)->isTypeDependent() ||
2078 TheCall->getArg(i)->isValueDependent())
2079 continue;
2080
Nate Begemana0110022010-06-08 00:16:34 +00002081 llvm::APSInt Result(32);
2082 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2083 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002084 diag::err_shufflevector_nonconstant_argument)
2085 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002086
Craig Topper50ad5b72013-08-03 17:40:38 +00002087 // Allow -1 which will be translated to undef in the IR.
2088 if (Result.isSigned() && Result.isAllOnesValue())
2089 continue;
2090
Chris Lattner7ab824e2008-08-10 02:05:13 +00002091 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002092 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002093 diag::err_shufflevector_argument_too_large)
2094 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002095 }
2096
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002097 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002098
Chris Lattner7ab824e2008-08-10 02:05:13 +00002099 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002100 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002101 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002102 }
2103
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002104 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2105 TheCall->getCallee()->getLocStart(),
2106 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002107}
Chris Lattner43be2e62007-12-19 23:59:04 +00002108
Hal Finkelc4d7c822013-09-18 03:29:45 +00002109/// SemaConvertVectorExpr - Handle __builtin_convertvector
2110ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2111 SourceLocation BuiltinLoc,
2112 SourceLocation RParenLoc) {
2113 ExprValueKind VK = VK_RValue;
2114 ExprObjectKind OK = OK_Ordinary;
2115 QualType DstTy = TInfo->getType();
2116 QualType SrcTy = E->getType();
2117
2118 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2119 return ExprError(Diag(BuiltinLoc,
2120 diag::err_convertvector_non_vector)
2121 << E->getSourceRange());
2122 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2123 return ExprError(Diag(BuiltinLoc,
2124 diag::err_convertvector_non_vector_type));
2125
2126 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2127 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2128 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2129 if (SrcElts != DstElts)
2130 return ExprError(Diag(BuiltinLoc,
2131 diag::err_convertvector_incompatible_vector)
2132 << E->getSourceRange());
2133 }
2134
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002135 return new (Context)
2136 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002137}
2138
Daniel Dunbarb7257262008-07-21 22:59:13 +00002139/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2140// This is declared to take (const void*, ...) and can take two
2141// optional constant int args.
2142bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002143 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002144
Chris Lattner3b054132008-11-19 05:08:23 +00002145 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002146 return Diag(TheCall->getLocEnd(),
2147 diag::err_typecheck_call_too_many_args_at_most)
2148 << 0 /*function call*/ << 3 << NumArgs
2149 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002150
2151 // Argument 0 is checked for us and the remaining arguments must be
2152 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002153 for (unsigned i = 1; i != NumArgs; ++i)
2154 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002155 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002156
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002157 return false;
2158}
2159
Hal Finkelf0417332014-07-17 14:25:55 +00002160/// SemaBuiltinAssume - Handle __assume (MS Extension).
2161// __assume does not evaluate its arguments, and should warn if its argument
2162// has side effects.
2163bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2164 Expr *Arg = TheCall->getArg(0);
2165 if (Arg->isInstantiationDependent()) return false;
2166
2167 if (Arg->HasSideEffects(Context))
2168 return Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002169 << Arg->getSourceRange()
2170 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2171
2172 return false;
2173}
2174
2175/// Handle __builtin_assume_aligned. This is declared
2176/// as (const void*, size_t, ...) and can take one optional constant int arg.
2177bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2178 unsigned NumArgs = TheCall->getNumArgs();
2179
2180 if (NumArgs > 3)
2181 return Diag(TheCall->getLocEnd(),
2182 diag::err_typecheck_call_too_many_args_at_most)
2183 << 0 /*function call*/ << 3 << NumArgs
2184 << TheCall->getSourceRange();
2185
2186 // The alignment must be a constant integer.
2187 Expr *Arg = TheCall->getArg(1);
2188
2189 // We can't check the value of a dependent argument.
2190 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2191 llvm::APSInt Result;
2192 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2193 return true;
2194
2195 if (!Result.isPowerOf2())
2196 return Diag(TheCall->getLocStart(),
2197 diag::err_alignment_not_power_of_two)
2198 << Arg->getSourceRange();
2199 }
2200
2201 if (NumArgs > 2) {
2202 ExprResult Arg(TheCall->getArg(2));
2203 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2204 Context.getSizeType(), false);
2205 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2206 if (Arg.isInvalid()) return true;
2207 TheCall->setArg(2, Arg.get());
2208 }
Hal Finkelf0417332014-07-17 14:25:55 +00002209
2210 return false;
2211}
2212
Eric Christopher8d0c6212010-04-17 02:26:23 +00002213/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2214/// TheCall is a constant expression.
2215bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2216 llvm::APSInt &Result) {
2217 Expr *Arg = TheCall->getArg(ArgNum);
2218 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2219 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2220
2221 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2222
2223 if (!Arg->isIntegerConstantExpr(Result, Context))
2224 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002225 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002226
Chris Lattnerd545ad12009-09-23 06:06:36 +00002227 return false;
2228}
2229
Richard Sandiford28940af2014-04-16 08:47:51 +00002230/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2231/// TheCall is a constant expression in the range [Low, High].
2232bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2233 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002234 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002235
2236 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002237 Expr *Arg = TheCall->getArg(ArgNum);
2238 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002239 return false;
2240
Eric Christopher8d0c6212010-04-17 02:26:23 +00002241 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002242 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002243 return true;
2244
Richard Sandiford28940af2014-04-16 08:47:51 +00002245 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002246 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002247 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002248
2249 return false;
2250}
2251
Eli Friedmanc97d0142009-05-03 06:04:26 +00002252/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002253/// This checks that val is a constant 1.
2254bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2255 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002256 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002257
Eric Christopher8d0c6212010-04-17 02:26:23 +00002258 // TODO: This is less than ideal. Overload this to take a value.
2259 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2260 return true;
2261
2262 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002263 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2264 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2265
2266 return false;
2267}
2268
Richard Smithd7293d72013-08-05 18:49:43 +00002269namespace {
2270enum StringLiteralCheckType {
2271 SLCT_NotALiteral,
2272 SLCT_UncheckedLiteral,
2273 SLCT_CheckedLiteral
2274};
2275}
2276
Richard Smith55ce3522012-06-25 20:30:08 +00002277// Determine if an expression is a string literal or constant string.
2278// If this function returns false on the arguments to a function expecting a
2279// format string, we will usually need to emit a warning.
2280// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002281static StringLiteralCheckType
2282checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2283 bool HasVAListArg, unsigned format_idx,
2284 unsigned firstDataArg, Sema::FormatStringType Type,
2285 Sema::VariadicCallType CallType, bool InFunctionCall,
2286 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002287 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002288 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002289 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002290
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002291 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002292
Richard Smithd7293d72013-08-05 18:49:43 +00002293 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002294 // Technically -Wformat-nonliteral does not warn about this case.
2295 // The behavior of printf and friends in this case is implementation
2296 // dependent. Ideally if the format string cannot be null then
2297 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002298 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002299
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002300 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002301 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002302 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002303 // The expression is a literal if both sub-expressions were, and it was
2304 // completely checked only if both sub-expressions were checked.
2305 const AbstractConditionalOperator *C =
2306 cast<AbstractConditionalOperator>(E);
2307 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002308 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002309 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002310 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002311 if (Left == SLCT_NotALiteral)
2312 return SLCT_NotALiteral;
2313 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002314 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002315 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002316 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002317 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002318 }
2319
2320 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002321 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2322 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002323 }
2324
John McCallc07a0c72011-02-17 10:25:35 +00002325 case Stmt::OpaqueValueExprClass:
2326 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2327 E = src;
2328 goto tryAgain;
2329 }
Richard Smith55ce3522012-06-25 20:30:08 +00002330 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002331
Ted Kremeneka8890832011-02-24 23:03:04 +00002332 case Stmt::PredefinedExprClass:
2333 // While __func__, etc., are technically not string literals, they
2334 // cannot contain format specifiers and thus are not a security
2335 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002336 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002337
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002338 case Stmt::DeclRefExprClass: {
2339 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002340
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002341 // As an exception, do not flag errors for variables binding to
2342 // const string literals.
2343 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2344 bool isConstant = false;
2345 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002346
Richard Smithd7293d72013-08-05 18:49:43 +00002347 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2348 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002349 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002350 isConstant = T.isConstant(S.Context) &&
2351 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002352 } else if (T->isObjCObjectPointerType()) {
2353 // In ObjC, there is usually no "const ObjectPointer" type,
2354 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002355 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002356 }
Mike Stump11289f42009-09-09 15:08:12 +00002357
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002358 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002359 if (const Expr *Init = VD->getAnyInitializer()) {
2360 // Look through initializers like const char c[] = { "foo" }
2361 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2362 if (InitList->isStringLiteralInit())
2363 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2364 }
Richard Smithd7293d72013-08-05 18:49:43 +00002365 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002366 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002367 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002368 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002369 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002370 }
Mike Stump11289f42009-09-09 15:08:12 +00002371
Anders Carlssonb012ca92009-06-28 19:55:58 +00002372 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2373 // special check to see if the format string is a function parameter
2374 // of the function calling the printf function. If the function
2375 // has an attribute indicating it is a printf-like function, then we
2376 // should suppress warnings concerning non-literals being used in a call
2377 // to a vprintf function. For example:
2378 //
2379 // void
2380 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2381 // va_list ap;
2382 // va_start(ap, fmt);
2383 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2384 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002385 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002386 if (HasVAListArg) {
2387 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2388 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2389 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002390 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002391 // adjust for implicit parameter
2392 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2393 if (MD->isInstance())
2394 ++PVIndex;
2395 // We also check if the formats are compatible.
2396 // We can't pass a 'scanf' string to a 'printf' function.
2397 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002398 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002399 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002400 }
2401 }
2402 }
2403 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002404 }
Mike Stump11289f42009-09-09 15:08:12 +00002405
Richard Smith55ce3522012-06-25 20:30:08 +00002406 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002407 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002408
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002409 case Stmt::CallExprClass:
2410 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002411 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002412 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2413 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2414 unsigned ArgIndex = FA->getFormatIdx();
2415 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2416 if (MD->isInstance())
2417 --ArgIndex;
2418 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002419
Richard Smithd7293d72013-08-05 18:49:43 +00002420 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002421 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002422 Type, CallType, InFunctionCall,
2423 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002424 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2425 unsigned BuiltinID = FD->getBuiltinID();
2426 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2427 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2428 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002429 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002430 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002431 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002432 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002433 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002434 }
2435 }
Mike Stump11289f42009-09-09 15:08:12 +00002436
Richard Smith55ce3522012-06-25 20:30:08 +00002437 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002438 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002439 case Stmt::ObjCStringLiteralClass:
2440 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002441 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002442
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002443 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002444 StrE = ObjCFExpr->getString();
2445 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002446 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002447
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002448 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002449 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2450 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002451 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002452 }
Mike Stump11289f42009-09-09 15:08:12 +00002453
Richard Smith55ce3522012-06-25 20:30:08 +00002454 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002455 }
Mike Stump11289f42009-09-09 15:08:12 +00002456
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002457 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002458 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002459 }
2460}
2461
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002462Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002463 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002464 .Case("scanf", FST_Scanf)
2465 .Cases("printf", "printf0", FST_Printf)
2466 .Cases("NSString", "CFString", FST_NSString)
2467 .Case("strftime", FST_Strftime)
2468 .Case("strfmon", FST_Strfmon)
2469 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2470 .Default(FST_Unknown);
2471}
2472
Jordan Rose3e0ec582012-07-19 18:10:23 +00002473/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002474/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002475/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002476bool Sema::CheckFormatArguments(const FormatAttr *Format,
2477 ArrayRef<const Expr *> Args,
2478 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002479 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002480 SourceLocation Loc, SourceRange Range,
2481 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002482 FormatStringInfo FSI;
2483 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002484 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002485 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002486 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002487 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002488}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002489
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002490bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002491 bool HasVAListArg, unsigned format_idx,
2492 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002493 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002494 SourceLocation Loc, SourceRange Range,
2495 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002496 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002497 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002498 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002499 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002500 }
Mike Stump11289f42009-09-09 15:08:12 +00002501
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002502 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002503
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002504 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002505 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002506 // Dynamically generated format strings are difficult to
2507 // automatically vet at compile time. Requiring that format strings
2508 // are string literals: (1) permits the checking of format strings by
2509 // the compiler and thereby (2) can practically remove the source of
2510 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002511
Mike Stump11289f42009-09-09 15:08:12 +00002512 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002513 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002514 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002515 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002516 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002517 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2518 format_idx, firstDataArg, Type, CallType,
2519 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002520 if (CT != SLCT_NotALiteral)
2521 // Literal format string found, check done!
2522 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002523
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002524 // Strftime is particular as it always uses a single 'time' argument,
2525 // so it is safe to pass a non-literal string.
2526 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002527 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002528
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002529 // Do not emit diag when the string param is a macro expansion and the
2530 // format is either NSString or CFString. This is a hack to prevent
2531 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2532 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002533 if (Type == FST_NSString &&
2534 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002535 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002536
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002537 // If there are no arguments specified, warn with -Wformat-security, otherwise
2538 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002539 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002540 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002541 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002542 << OrigFormatExpr->getSourceRange();
2543 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002544 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002545 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002546 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002547 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002548}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002549
Ted Kremenekab278de2010-01-28 23:39:18 +00002550namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002551class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2552protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002553 Sema &S;
2554 const StringLiteral *FExpr;
2555 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002556 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002557 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002558 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002559 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002560 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002561 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002562 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002563 bool usesPositionalArgs;
2564 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002565 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002566 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002567 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002568public:
Ted Kremenek02087932010-07-16 02:11:22 +00002569 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002570 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002571 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002572 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002573 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002574 Sema::VariadicCallType callType,
2575 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002576 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002577 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2578 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002579 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002580 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002581 inFunctionCall(inFunctionCall), CallType(callType),
2582 CheckedVarArgs(CheckedVarArgs) {
2583 CoveredArgs.resize(numDataArgs);
2584 CoveredArgs.reset();
2585 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002586
Ted Kremenek019d2242010-01-29 01:50:07 +00002587 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002588
Ted Kremenek02087932010-07-16 02:11:22 +00002589 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002590 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002591
Jordan Rose92303592012-09-08 04:00:03 +00002592 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002593 const analyze_format_string::FormatSpecifier &FS,
2594 const analyze_format_string::ConversionSpecifier &CS,
2595 const char *startSpecifier, unsigned specifierLen,
2596 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002597
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002598 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002599 const analyze_format_string::FormatSpecifier &FS,
2600 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002601
2602 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002603 const analyze_format_string::ConversionSpecifier &CS,
2604 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002605
Craig Toppere14c0f82014-03-12 04:55:44 +00002606 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002607
Craig Toppere14c0f82014-03-12 04:55:44 +00002608 void HandleInvalidPosition(const char *startSpecifier,
2609 unsigned specifierLen,
2610 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002611
Craig Toppere14c0f82014-03-12 04:55:44 +00002612 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002613
Craig Toppere14c0f82014-03-12 04:55:44 +00002614 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002615
Richard Trieu03cf7b72011-10-28 00:41:25 +00002616 template <typename Range>
2617 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2618 const Expr *ArgumentExpr,
2619 PartialDiagnostic PDiag,
2620 SourceLocation StringLoc,
2621 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002622 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002623
Ted Kremenek02087932010-07-16 02:11:22 +00002624protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002625 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2626 const char *startSpec,
2627 unsigned specifierLen,
2628 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002629
2630 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2631 const char *startSpec,
2632 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002633
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002634 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002635 CharSourceRange getSpecifierRange(const char *startSpecifier,
2636 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002637 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002638
Ted Kremenek5739de72010-01-29 01:06:55 +00002639 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002640
2641 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2642 const analyze_format_string::ConversionSpecifier &CS,
2643 const char *startSpecifier, unsigned specifierLen,
2644 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002645
2646 template <typename Range>
2647 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2648 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002649 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002650};
2651}
2652
Ted Kremenek02087932010-07-16 02:11:22 +00002653SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002654 return OrigFormatExpr->getSourceRange();
2655}
2656
Ted Kremenek02087932010-07-16 02:11:22 +00002657CharSourceRange CheckFormatHandler::
2658getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002659 SourceLocation Start = getLocationOfByte(startSpecifier);
2660 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2661
2662 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002663 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002664
2665 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002666}
2667
Ted Kremenek02087932010-07-16 02:11:22 +00002668SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002669 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002670}
2671
Ted Kremenek02087932010-07-16 02:11:22 +00002672void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2673 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002674 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2675 getLocationOfByte(startSpecifier),
2676 /*IsStringLocation*/true,
2677 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002678}
2679
Jordan Rose92303592012-09-08 04:00:03 +00002680void CheckFormatHandler::HandleInvalidLengthModifier(
2681 const analyze_format_string::FormatSpecifier &FS,
2682 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002683 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002684 using namespace analyze_format_string;
2685
2686 const LengthModifier &LM = FS.getLengthModifier();
2687 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2688
2689 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002690 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002691 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002692 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002693 getLocationOfByte(LM.getStart()),
2694 /*IsStringLocation*/true,
2695 getSpecifierRange(startSpecifier, specifierLen));
2696
2697 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2698 << FixedLM->toString()
2699 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2700
2701 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002702 FixItHint Hint;
2703 if (DiagID == diag::warn_format_nonsensical_length)
2704 Hint = FixItHint::CreateRemoval(LMRange);
2705
2706 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002707 getLocationOfByte(LM.getStart()),
2708 /*IsStringLocation*/true,
2709 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002710 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002711 }
2712}
2713
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002714void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002715 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002716 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002717 using namespace analyze_format_string;
2718
2719 const LengthModifier &LM = FS.getLengthModifier();
2720 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2721
2722 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002723 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002724 if (FixedLM) {
2725 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2726 << LM.toString() << 0,
2727 getLocationOfByte(LM.getStart()),
2728 /*IsStringLocation*/true,
2729 getSpecifierRange(startSpecifier, specifierLen));
2730
2731 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2732 << FixedLM->toString()
2733 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2734
2735 } else {
2736 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2737 << LM.toString() << 0,
2738 getLocationOfByte(LM.getStart()),
2739 /*IsStringLocation*/true,
2740 getSpecifierRange(startSpecifier, specifierLen));
2741 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002742}
2743
2744void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2745 const analyze_format_string::ConversionSpecifier &CS,
2746 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002747 using namespace analyze_format_string;
2748
2749 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002750 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002751 if (FixedCS) {
2752 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2753 << CS.toString() << /*conversion specifier*/1,
2754 getLocationOfByte(CS.getStart()),
2755 /*IsStringLocation*/true,
2756 getSpecifierRange(startSpecifier, specifierLen));
2757
2758 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2759 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2760 << FixedCS->toString()
2761 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2762 } else {
2763 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2764 << CS.toString() << /*conversion specifier*/1,
2765 getLocationOfByte(CS.getStart()),
2766 /*IsStringLocation*/true,
2767 getSpecifierRange(startSpecifier, specifierLen));
2768 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002769}
2770
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002771void CheckFormatHandler::HandlePosition(const char *startPos,
2772 unsigned posLen) {
2773 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2774 getLocationOfByte(startPos),
2775 /*IsStringLocation*/true,
2776 getSpecifierRange(startPos, posLen));
2777}
2778
Ted Kremenekd1668192010-02-27 01:41:03 +00002779void
Ted Kremenek02087932010-07-16 02:11:22 +00002780CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2781 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002782 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2783 << (unsigned) p,
2784 getLocationOfByte(startPos), /*IsStringLocation*/true,
2785 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002786}
2787
Ted Kremenek02087932010-07-16 02:11:22 +00002788void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002789 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002790 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2791 getLocationOfByte(startPos),
2792 /*IsStringLocation*/true,
2793 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002794}
2795
Ted Kremenek02087932010-07-16 02:11:22 +00002796void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002797 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002798 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002799 EmitFormatDiagnostic(
2800 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2801 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2802 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002803 }
Ted Kremenek02087932010-07-16 02:11:22 +00002804}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002805
Jordan Rose58bbe422012-07-19 18:10:08 +00002806// Note that this may return NULL if there was an error parsing or building
2807// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002808const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002809 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002810}
2811
2812void CheckFormatHandler::DoneProcessing() {
2813 // Does the number of data arguments exceed the number of
2814 // format conversions in the format string?
2815 if (!HasVAListArg) {
2816 // Find any arguments that weren't covered.
2817 CoveredArgs.flip();
2818 signed notCoveredArg = CoveredArgs.find_first();
2819 if (notCoveredArg >= 0) {
2820 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002821 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2822 SourceLocation Loc = E->getLocStart();
2823 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2824 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2825 Loc, /*IsStringLocation*/false,
2826 getFormatStringRange());
2827 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002828 }
Ted Kremenek02087932010-07-16 02:11:22 +00002829 }
2830 }
2831}
2832
Ted Kremenekce815422010-07-19 21:25:57 +00002833bool
2834CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2835 SourceLocation Loc,
2836 const char *startSpec,
2837 unsigned specifierLen,
2838 const char *csStart,
2839 unsigned csLen) {
2840
2841 bool keepGoing = true;
2842 if (argIndex < NumDataArgs) {
2843 // Consider the argument coverered, even though the specifier doesn't
2844 // make sense.
2845 CoveredArgs.set(argIndex);
2846 }
2847 else {
2848 // If argIndex exceeds the number of data arguments we
2849 // don't issue a warning because that is just a cascade of warnings (and
2850 // they may have intended '%%' anyway). We don't want to continue processing
2851 // the format string after this point, however, as we will like just get
2852 // gibberish when trying to match arguments.
2853 keepGoing = false;
2854 }
2855
Richard Trieu03cf7b72011-10-28 00:41:25 +00002856 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2857 << StringRef(csStart, csLen),
2858 Loc, /*IsStringLocation*/true,
2859 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00002860
2861 return keepGoing;
2862}
2863
Richard Trieu03cf7b72011-10-28 00:41:25 +00002864void
2865CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2866 const char *startSpec,
2867 unsigned specifierLen) {
2868 EmitFormatDiagnostic(
2869 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2870 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2871}
2872
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002873bool
2874CheckFormatHandler::CheckNumArgs(
2875 const analyze_format_string::FormatSpecifier &FS,
2876 const analyze_format_string::ConversionSpecifier &CS,
2877 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2878
2879 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002880 PartialDiagnostic PDiag = FS.usesPositionalArg()
2881 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2882 << (argIndex+1) << NumDataArgs)
2883 : S.PDiag(diag::warn_printf_insufficient_data_args);
2884 EmitFormatDiagnostic(
2885 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2886 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002887 return false;
2888 }
2889 return true;
2890}
2891
Richard Trieu03cf7b72011-10-28 00:41:25 +00002892template<typename Range>
2893void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2894 SourceLocation Loc,
2895 bool IsStringLocation,
2896 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002897 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002898 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002899 Loc, IsStringLocation, StringRange, FixIt);
2900}
2901
2902/// \brief If the format string is not within the funcion call, emit a note
2903/// so that the function call and string are in diagnostic messages.
2904///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002905/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00002906/// call and only one diagnostic message will be produced. Otherwise, an
2907/// extra note will be emitted pointing to location of the format string.
2908///
2909/// \param ArgumentExpr the expression that is passed as the format string
2910/// argument in the function call. Used for getting locations when two
2911/// diagnostics are emitted.
2912///
2913/// \param PDiag the callee should already have provided any strings for the
2914/// diagnostic message. This function only adds locations and fixits
2915/// to diagnostics.
2916///
2917/// \param Loc primary location for diagnostic. If two diagnostics are
2918/// required, one will be at Loc and a new SourceLocation will be created for
2919/// the other one.
2920///
2921/// \param IsStringLocation if true, Loc points to the format string should be
2922/// used for the note. Otherwise, Loc points to the argument list and will
2923/// be used with PDiag.
2924///
2925/// \param StringRange some or all of the string to highlight. This is
2926/// templated so it can accept either a CharSourceRange or a SourceRange.
2927///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002928/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002929template<typename Range>
2930void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2931 const Expr *ArgumentExpr,
2932 PartialDiagnostic PDiag,
2933 SourceLocation Loc,
2934 bool IsStringLocation,
2935 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002936 ArrayRef<FixItHint> FixIt) {
2937 if (InFunctionCall) {
2938 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2939 D << StringRange;
2940 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2941 I != E; ++I) {
2942 D << *I;
2943 }
2944 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002945 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2946 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00002947
2948 const Sema::SemaDiagnosticBuilder &Note =
2949 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2950 diag::note_format_string_defined);
2951
2952 Note << StringRange;
2953 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2954 I != E; ++I) {
2955 Note << *I;
2956 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00002957 }
2958}
2959
Ted Kremenek02087932010-07-16 02:11:22 +00002960//===--- CHECK: Printf format string checking ------------------------------===//
2961
2962namespace {
2963class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002964 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00002965public:
2966 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2967 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002968 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00002969 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002970 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002971 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002972 Sema::VariadicCallType CallType,
2973 llvm::SmallBitVector &CheckedVarArgs)
2974 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2975 numDataArgs, beg, hasVAListArg, Args,
2976 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2977 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00002978 {}
2979
Craig Toppere14c0f82014-03-12 04:55:44 +00002980
Ted Kremenek02087932010-07-16 02:11:22 +00002981 bool HandleInvalidPrintfConversionSpecifier(
2982 const analyze_printf::PrintfSpecifier &FS,
2983 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002984 unsigned specifierLen) override;
2985
Ted Kremenek02087932010-07-16 02:11:22 +00002986 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2987 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002988 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00002989 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2990 const char *StartSpecifier,
2991 unsigned SpecifierLen,
2992 const Expr *E);
2993
Ted Kremenek02087932010-07-16 02:11:22 +00002994 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2995 const char *startSpecifier, unsigned specifierLen);
2996 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2997 const analyze_printf::OptionalAmount &Amt,
2998 unsigned type,
2999 const char *startSpecifier, unsigned specifierLen);
3000 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3001 const analyze_printf::OptionalFlag &flag,
3002 const char *startSpecifier, unsigned specifierLen);
3003 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3004 const analyze_printf::OptionalFlag &ignoredFlag,
3005 const analyze_printf::OptionalFlag &flag,
3006 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003007 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003008 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00003009
Ted Kremenek02087932010-07-16 02:11:22 +00003010};
3011}
3012
3013bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3014 const analyze_printf::PrintfSpecifier &FS,
3015 const char *startSpecifier,
3016 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003017 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003018 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003019
Ted Kremenekce815422010-07-19 21:25:57 +00003020 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3021 getLocationOfByte(CS.getStart()),
3022 startSpecifier, specifierLen,
3023 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003024}
3025
Ted Kremenek02087932010-07-16 02:11:22 +00003026bool CheckPrintfHandler::HandleAmount(
3027 const analyze_format_string::OptionalAmount &Amt,
3028 unsigned k, const char *startSpecifier,
3029 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003030
3031 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003032 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003033 unsigned argIndex = Amt.getArgIndex();
3034 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003035 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3036 << k,
3037 getLocationOfByte(Amt.getStart()),
3038 /*IsStringLocation*/true,
3039 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003040 // Don't do any more checking. We will just emit
3041 // spurious errors.
3042 return false;
3043 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003044
Ted Kremenek5739de72010-01-29 01:06:55 +00003045 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00003046 // Although not in conformance with C99, we also allow the argument to be
3047 // an 'unsigned int' as that is a reasonably safe case. GCC also
3048 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003049 CoveredArgs.set(argIndex);
3050 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003051 if (!Arg)
3052 return false;
3053
Ted Kremenek5739de72010-01-29 01:06:55 +00003054 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003055
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003056 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3057 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003058
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003059 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003060 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003061 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003062 << T << Arg->getSourceRange(),
3063 getLocationOfByte(Amt.getStart()),
3064 /*IsStringLocation*/true,
3065 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003066 // Don't do any more checking. We will just emit
3067 // spurious errors.
3068 return false;
3069 }
3070 }
3071 }
3072 return true;
3073}
Ted Kremenek5739de72010-01-29 01:06:55 +00003074
Tom Careb49ec692010-06-17 19:00:27 +00003075void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003076 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003077 const analyze_printf::OptionalAmount &Amt,
3078 unsigned type,
3079 const char *startSpecifier,
3080 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003081 const analyze_printf::PrintfConversionSpecifier &CS =
3082 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003083
Richard Trieu03cf7b72011-10-28 00:41:25 +00003084 FixItHint fixit =
3085 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3086 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3087 Amt.getConstantLength()))
3088 : FixItHint();
3089
3090 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3091 << type << CS.toString(),
3092 getLocationOfByte(Amt.getStart()),
3093 /*IsStringLocation*/true,
3094 getSpecifierRange(startSpecifier, specifierLen),
3095 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003096}
3097
Ted Kremenek02087932010-07-16 02:11:22 +00003098void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003099 const analyze_printf::OptionalFlag &flag,
3100 const char *startSpecifier,
3101 unsigned specifierLen) {
3102 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003103 const analyze_printf::PrintfConversionSpecifier &CS =
3104 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003105 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3106 << flag.toString() << CS.toString(),
3107 getLocationOfByte(flag.getPosition()),
3108 /*IsStringLocation*/true,
3109 getSpecifierRange(startSpecifier, specifierLen),
3110 FixItHint::CreateRemoval(
3111 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003112}
3113
3114void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003115 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003116 const analyze_printf::OptionalFlag &ignoredFlag,
3117 const analyze_printf::OptionalFlag &flag,
3118 const char *startSpecifier,
3119 unsigned specifierLen) {
3120 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003121 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3122 << ignoredFlag.toString() << flag.toString(),
3123 getLocationOfByte(ignoredFlag.getPosition()),
3124 /*IsStringLocation*/true,
3125 getSpecifierRange(startSpecifier, specifierLen),
3126 FixItHint::CreateRemoval(
3127 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003128}
3129
Richard Smith55ce3522012-06-25 20:30:08 +00003130// Determines if the specified is a C++ class or struct containing
3131// a member with the specified name and kind (e.g. a CXXMethodDecl named
3132// "c_str()").
3133template<typename MemberKind>
3134static llvm::SmallPtrSet<MemberKind*, 1>
3135CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3136 const RecordType *RT = Ty->getAs<RecordType>();
3137 llvm::SmallPtrSet<MemberKind*, 1> Results;
3138
3139 if (!RT)
3140 return Results;
3141 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003142 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003143 return Results;
3144
Alp Tokerb6cc5922014-05-03 03:45:55 +00003145 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003146 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003147 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003148
3149 // We just need to include all members of the right kind turned up by the
3150 // filter, at this point.
3151 if (S.LookupQualifiedName(R, RT->getDecl()))
3152 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3153 NamedDecl *decl = (*I)->getUnderlyingDecl();
3154 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3155 Results.insert(FK);
3156 }
3157 return Results;
3158}
3159
Richard Smith2868a732014-02-28 01:36:39 +00003160/// Check if we could call '.c_str()' on an object.
3161///
3162/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3163/// allow the call, or if it would be ambiguous).
3164bool Sema::hasCStrMethod(const Expr *E) {
3165 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3166 MethodSet Results =
3167 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3168 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3169 MI != ME; ++MI)
3170 if ((*MI)->getMinRequiredArguments() == 0)
3171 return true;
3172 return false;
3173}
3174
Richard Smith55ce3522012-06-25 20:30:08 +00003175// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003176// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003177// Returns true when a c_str() conversion method is found.
3178bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003179 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003180 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3181
3182 MethodSet Results =
3183 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3184
3185 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3186 MI != ME; ++MI) {
3187 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003188 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003189 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003190 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003191 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003192 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3193 << "c_str()"
3194 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3195 return true;
3196 }
3197 }
3198
3199 return false;
3200}
3201
Ted Kremenekab278de2010-01-28 23:39:18 +00003202bool
Ted Kremenek02087932010-07-16 02:11:22 +00003203CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003204 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003205 const char *startSpecifier,
3206 unsigned specifierLen) {
3207
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003208 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003209 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003210 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003211
Ted Kremenek6cd69422010-07-19 22:01:06 +00003212 if (FS.consumesDataArgument()) {
3213 if (atFirstArg) {
3214 atFirstArg = false;
3215 usesPositionalArgs = FS.usesPositionalArg();
3216 }
3217 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003218 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3219 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003220 return false;
3221 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003222 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003223
Ted Kremenekd1668192010-02-27 01:41:03 +00003224 // First check if the field width, precision, and conversion specifier
3225 // have matching data arguments.
3226 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3227 startSpecifier, specifierLen)) {
3228 return false;
3229 }
3230
3231 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3232 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003233 return false;
3234 }
3235
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003236 if (!CS.consumesDataArgument()) {
3237 // FIXME: Technically specifying a precision or field width here
3238 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003239 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003240 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003241
Ted Kremenek4a49d982010-02-26 19:18:41 +00003242 // Consume the argument.
3243 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003244 if (argIndex < NumDataArgs) {
3245 // The check to see if the argIndex is valid will come later.
3246 // We set the bit here because we may exit early from this
3247 // function if we encounter some other error.
3248 CoveredArgs.set(argIndex);
3249 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003250
3251 // Check for using an Objective-C specific conversion specifier
3252 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003253 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003254 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3255 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003256 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003257
Tom Careb49ec692010-06-17 19:00:27 +00003258 // Check for invalid use of field width
3259 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003260 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003261 startSpecifier, specifierLen);
3262 }
3263
3264 // Check for invalid use of precision
3265 if (!FS.hasValidPrecision()) {
3266 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3267 startSpecifier, specifierLen);
3268 }
3269
3270 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003271 if (!FS.hasValidThousandsGroupingPrefix())
3272 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003273 if (!FS.hasValidLeadingZeros())
3274 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3275 if (!FS.hasValidPlusPrefix())
3276 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003277 if (!FS.hasValidSpacePrefix())
3278 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003279 if (!FS.hasValidAlternativeForm())
3280 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3281 if (!FS.hasValidLeftJustified())
3282 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3283
3284 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003285 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3286 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3287 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003288 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3289 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3290 startSpecifier, specifierLen);
3291
3292 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003293 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003294 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3295 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003296 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003297 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003298 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003299 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3300 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003301
Jordan Rose92303592012-09-08 04:00:03 +00003302 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3303 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3304
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003305 // The remaining checks depend on the data arguments.
3306 if (HasVAListArg)
3307 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003308
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003309 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003310 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003311
Jordan Rose58bbe422012-07-19 18:10:08 +00003312 const Expr *Arg = getDataArg(argIndex);
3313 if (!Arg)
3314 return true;
3315
3316 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003317}
3318
Jordan Roseaee34382012-09-05 22:56:26 +00003319static bool requiresParensToAddCast(const Expr *E) {
3320 // FIXME: We should have a general way to reason about operator
3321 // precedence and whether parens are actually needed here.
3322 // Take care of a few common cases where they aren't.
3323 const Expr *Inside = E->IgnoreImpCasts();
3324 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3325 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3326
3327 switch (Inside->getStmtClass()) {
3328 case Stmt::ArraySubscriptExprClass:
3329 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003330 case Stmt::CharacterLiteralClass:
3331 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003332 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003333 case Stmt::FloatingLiteralClass:
3334 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003335 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003336 case Stmt::ObjCArrayLiteralClass:
3337 case Stmt::ObjCBoolLiteralExprClass:
3338 case Stmt::ObjCBoxedExprClass:
3339 case Stmt::ObjCDictionaryLiteralClass:
3340 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003341 case Stmt::ObjCIvarRefExprClass:
3342 case Stmt::ObjCMessageExprClass:
3343 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003344 case Stmt::ObjCStringLiteralClass:
3345 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003346 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003347 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003348 case Stmt::UnaryOperatorClass:
3349 return false;
3350 default:
3351 return true;
3352 }
3353}
3354
Richard Smith55ce3522012-06-25 20:30:08 +00003355bool
3356CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3357 const char *StartSpecifier,
3358 unsigned SpecifierLen,
3359 const Expr *E) {
3360 using namespace analyze_format_string;
3361 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003362 // Now type check the data expression that matches the
3363 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003364 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3365 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003366 if (!AT.isValid())
3367 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003368
Jordan Rose598ec092012-12-05 18:44:40 +00003369 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003370 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3371 ExprTy = TET->getUnderlyingExpr()->getType();
3372 }
3373
Jordan Rose598ec092012-12-05 18:44:40 +00003374 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003375 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003376
Jordan Rose22b74712012-09-05 22:56:19 +00003377 // Look through argument promotions for our error message's reported type.
3378 // This includes the integral and floating promotions, but excludes array
3379 // and function pointer decay; seeing that an argument intended to be a
3380 // string has type 'char [6]' is probably more confusing than 'char *'.
3381 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3382 if (ICE->getCastKind() == CK_IntegralCast ||
3383 ICE->getCastKind() == CK_FloatingCast) {
3384 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003385 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003386
3387 // Check if we didn't match because of an implicit cast from a 'char'
3388 // or 'short' to an 'int'. This is done because printf is a varargs
3389 // function.
3390 if (ICE->getType() == S.Context.IntTy ||
3391 ICE->getType() == S.Context.UnsignedIntTy) {
3392 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003393 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003394 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003395 }
Jordan Rose98709982012-06-04 22:48:57 +00003396 }
Jordan Rose598ec092012-12-05 18:44:40 +00003397 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3398 // Special case for 'a', which has type 'int' in C.
3399 // Note, however, that we do /not/ want to treat multibyte constants like
3400 // 'MooV' as characters! This form is deprecated but still exists.
3401 if (ExprTy == S.Context.IntTy)
3402 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3403 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003404 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003405
Jordan Rosebc53ed12014-05-31 04:12:14 +00003406 // Look through enums to their underlying type.
3407 bool IsEnum = false;
3408 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3409 ExprTy = EnumTy->getDecl()->getIntegerType();
3410 IsEnum = true;
3411 }
3412
Jordan Rose0e5badd2012-12-05 18:44:49 +00003413 // %C in an Objective-C context prints a unichar, not a wchar_t.
3414 // If the argument is an integer of some kind, believe the %C and suggest
3415 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003416 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003417 if (ObjCContext &&
3418 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3419 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3420 !ExprTy->isCharType()) {
3421 // 'unichar' is defined as a typedef of unsigned short, but we should
3422 // prefer using the typedef if it is visible.
3423 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003424
3425 // While we are here, check if the value is an IntegerLiteral that happens
3426 // to be within the valid range.
3427 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3428 const llvm::APInt &V = IL->getValue();
3429 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3430 return true;
3431 }
3432
Jordan Rose0e5badd2012-12-05 18:44:49 +00003433 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3434 Sema::LookupOrdinaryName);
3435 if (S.LookupName(Result, S.getCurScope())) {
3436 NamedDecl *ND = Result.getFoundDecl();
3437 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3438 if (TD->getUnderlyingType() == IntendedTy)
3439 IntendedTy = S.Context.getTypedefType(TD);
3440 }
3441 }
3442 }
3443
3444 // Special-case some of Darwin's platform-independence types by suggesting
3445 // casts to primitive types that are known to be large enough.
3446 bool ShouldNotPrintDirectly = false;
Jordan Roseaee34382012-09-05 22:56:26 +00003447 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003448 // Use a 'while' to peel off layers of typedefs.
3449 QualType TyTy = IntendedTy;
3450 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseaee34382012-09-05 22:56:26 +00003451 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose0e5badd2012-12-05 18:44:49 +00003452 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseaee34382012-09-05 22:56:26 +00003453 .Case("NSInteger", S.Context.LongTy)
3454 .Case("NSUInteger", S.Context.UnsignedLongTy)
3455 .Case("SInt32", S.Context.IntTy)
3456 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose0e5badd2012-12-05 18:44:49 +00003457 .Default(QualType());
3458
3459 if (!CastTy.isNull()) {
3460 ShouldNotPrintDirectly = true;
3461 IntendedTy = CastTy;
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003462 break;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003463 }
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003464 TyTy = UserTy->desugar();
Jordan Roseaee34382012-09-05 22:56:26 +00003465 }
3466 }
3467
Jordan Rose22b74712012-09-05 22:56:19 +00003468 // We may be able to offer a FixItHint if it is a supported type.
3469 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003470 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003471 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003472
Jordan Rose22b74712012-09-05 22:56:19 +00003473 if (success) {
3474 // Get the fix string from the fixed format specifier
3475 SmallString<16> buf;
3476 llvm::raw_svector_ostream os(buf);
3477 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003478
Jordan Roseaee34382012-09-05 22:56:26 +00003479 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3480
Jordan Rose0e5badd2012-12-05 18:44:49 +00003481 if (IntendedTy == ExprTy) {
3482 // In this case, the specifier is wrong and should be changed to match
3483 // the argument.
3484 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003485 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3486 << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003487 << E->getSourceRange(),
3488 E->getLocStart(),
3489 /*IsStringLocation*/false,
3490 SpecRange,
3491 FixItHint::CreateReplacement(SpecRange, os.str()));
3492
3493 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003494 // The canonical type for formatting this value is different from the
3495 // actual type of the expression. (This occurs, for example, with Darwin's
3496 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3497 // should be printed as 'long' for 64-bit compatibility.)
3498 // Rather than emitting a normal format/argument mismatch, we want to
3499 // add a cast to the recommended type (and correct the format string
3500 // if necessary).
3501 SmallString<16> CastBuf;
3502 llvm::raw_svector_ostream CastFix(CastBuf);
3503 CastFix << "(";
3504 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3505 CastFix << ")";
3506
3507 SmallVector<FixItHint,4> Hints;
3508 if (!AT.matchesType(S.Context, IntendedTy))
3509 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3510
3511 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3512 // If there's already a cast present, just replace it.
3513 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3514 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3515
3516 } else if (!requiresParensToAddCast(E)) {
3517 // If the expression has high enough precedence,
3518 // just write the C-style cast.
3519 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3520 CastFix.str()));
3521 } else {
3522 // Otherwise, add parens around the expression as well as the cast.
3523 CastFix << "(";
3524 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3525 CastFix.str()));
3526
Alp Tokerb6cc5922014-05-03 03:45:55 +00003527 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003528 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3529 }
3530
Jordan Rose0e5badd2012-12-05 18:44:49 +00003531 if (ShouldNotPrintDirectly) {
3532 // The expression has a type that should not be printed directly.
3533 // We extract the name from the typedef because we don't want to show
3534 // the underlying type in the diagnostic.
3535 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseaee34382012-09-05 22:56:26 +00003536
Jordan Rose0e5badd2012-12-05 18:44:49 +00003537 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00003538 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003539 << E->getSourceRange(),
3540 E->getLocStart(), /*IsStringLocation=*/false,
3541 SpecRange, Hints);
3542 } else {
3543 // In this case, the expression could be printed using a different
3544 // specifier, but we've decided that the specifier is probably correct
3545 // and we should cast instead. Just use the normal warning message.
3546 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003547 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3548 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003549 << E->getSourceRange(),
3550 E->getLocStart(), /*IsStringLocation*/false,
3551 SpecRange, Hints);
3552 }
Jordan Roseaee34382012-09-05 22:56:26 +00003553 }
Jordan Rose22b74712012-09-05 22:56:19 +00003554 } else {
3555 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3556 SpecifierLen);
3557 // Since the warning for passing non-POD types to variadic functions
3558 // was deferred until now, we emit a warning for non-POD
3559 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003560 switch (S.isValidVarArgType(ExprTy)) {
3561 case Sema::VAK_Valid:
3562 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003563 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003564 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3565 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Richard Smithd7293d72013-08-05 18:49:43 +00003566 << CSR
3567 << E->getSourceRange(),
3568 E->getLocStart(), /*IsStringLocation*/false, CSR);
3569 break;
3570
3571 case Sema::VAK_Undefined:
3572 EmitFormatDiagnostic(
3573 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003574 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003575 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003576 << CallType
3577 << AT.getRepresentativeTypeName(S.Context)
3578 << CSR
3579 << E->getSourceRange(),
3580 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003581 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003582 break;
3583
3584 case Sema::VAK_Invalid:
3585 if (ExprTy->isObjCObjectType())
3586 EmitFormatDiagnostic(
3587 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3588 << S.getLangOpts().CPlusPlus11
3589 << ExprTy
3590 << CallType
3591 << AT.getRepresentativeTypeName(S.Context)
3592 << CSR
3593 << E->getSourceRange(),
3594 E->getLocStart(), /*IsStringLocation*/false, CSR);
3595 else
3596 // FIXME: If this is an initializer list, suggest removing the braces
3597 // or inserting a cast to the target type.
3598 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3599 << isa<InitListExpr>(E) << ExprTy << CallType
3600 << AT.getRepresentativeTypeName(S.Context)
3601 << E->getSourceRange();
3602 break;
3603 }
3604
3605 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3606 "format string specifier index out of range");
3607 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003608 }
3609
Ted Kremenekab278de2010-01-28 23:39:18 +00003610 return true;
3611}
3612
Ted Kremenek02087932010-07-16 02:11:22 +00003613//===--- CHECK: Scanf format string checking ------------------------------===//
3614
3615namespace {
3616class CheckScanfHandler : public CheckFormatHandler {
3617public:
3618 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3619 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003620 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003621 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003622 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003623 Sema::VariadicCallType CallType,
3624 llvm::SmallBitVector &CheckedVarArgs)
3625 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3626 numDataArgs, beg, hasVAListArg,
3627 Args, formatIdx, inFunctionCall, CallType,
3628 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003629 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003630
3631 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3632 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003633 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003634
3635 bool HandleInvalidScanfConversionSpecifier(
3636 const analyze_scanf::ScanfSpecifier &FS,
3637 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003638 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003639
Craig Toppere14c0f82014-03-12 04:55:44 +00003640 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003641};
Ted Kremenek019d2242010-01-29 01:50:07 +00003642}
Ted Kremenekab278de2010-01-28 23:39:18 +00003643
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003644void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3645 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003646 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3647 getLocationOfByte(end), /*IsStringLocation*/true,
3648 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003649}
3650
Ted Kremenekce815422010-07-19 21:25:57 +00003651bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3652 const analyze_scanf::ScanfSpecifier &FS,
3653 const char *startSpecifier,
3654 unsigned specifierLen) {
3655
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003656 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003657 FS.getConversionSpecifier();
3658
3659 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3660 getLocationOfByte(CS.getStart()),
3661 startSpecifier, specifierLen,
3662 CS.getStart(), CS.getLength());
3663}
3664
Ted Kremenek02087932010-07-16 02:11:22 +00003665bool CheckScanfHandler::HandleScanfSpecifier(
3666 const analyze_scanf::ScanfSpecifier &FS,
3667 const char *startSpecifier,
3668 unsigned specifierLen) {
3669
3670 using namespace analyze_scanf;
3671 using namespace analyze_format_string;
3672
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003673 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003674
Ted Kremenek6cd69422010-07-19 22:01:06 +00003675 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3676 // be used to decide if we are using positional arguments consistently.
3677 if (FS.consumesDataArgument()) {
3678 if (atFirstArg) {
3679 atFirstArg = false;
3680 usesPositionalArgs = FS.usesPositionalArg();
3681 }
3682 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003683 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3684 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003685 return false;
3686 }
Ted Kremenek02087932010-07-16 02:11:22 +00003687 }
3688
3689 // Check if the field with is non-zero.
3690 const OptionalAmount &Amt = FS.getFieldWidth();
3691 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3692 if (Amt.getConstantAmount() == 0) {
3693 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3694 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003695 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3696 getLocationOfByte(Amt.getStart()),
3697 /*IsStringLocation*/true, R,
3698 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003699 }
3700 }
3701
3702 if (!FS.consumesDataArgument()) {
3703 // FIXME: Technically specifying a precision or field width here
3704 // makes no sense. Worth issuing a warning at some point.
3705 return true;
3706 }
3707
3708 // Consume the argument.
3709 unsigned argIndex = FS.getArgIndex();
3710 if (argIndex < NumDataArgs) {
3711 // The check to see if the argIndex is valid will come later.
3712 // We set the bit here because we may exit early from this
3713 // function if we encounter some other error.
3714 CoveredArgs.set(argIndex);
3715 }
3716
Ted Kremenek4407ea42010-07-20 20:04:47 +00003717 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003718 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003719 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3720 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003721 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003722 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003723 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003724 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3725 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003726
Jordan Rose92303592012-09-08 04:00:03 +00003727 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3728 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3729
Ted Kremenek02087932010-07-16 02:11:22 +00003730 // The remaining checks depend on the data arguments.
3731 if (HasVAListArg)
3732 return true;
3733
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003734 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003735 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003736
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003737 // Check that the argument type matches the format specifier.
3738 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003739 if (!Ex)
3740 return true;
3741
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003742 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3743 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003744 ScanfSpecifier fixedFS = FS;
Jordan Rose177b0a32014-03-20 03:32:39 +00003745 bool success = fixedFS.fixType(Ex->getType(),
3746 Ex->IgnoreImpCasts()->getType(),
3747 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003748
3749 if (success) {
3750 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003751 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003752 llvm::raw_svector_ostream os(buf);
3753 fixedFS.toString(os);
3754
3755 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003756 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3757 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003758 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003759 Ex->getLocStart(),
3760 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003761 getSpecifierRange(startSpecifier, specifierLen),
3762 FixItHint::CreateReplacement(
3763 getSpecifierRange(startSpecifier, specifierLen),
3764 os.str()));
3765 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003766 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003767 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3768 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003769 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003770 Ex->getLocStart(),
3771 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003772 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003773 }
3774 }
3775
Ted Kremenek02087932010-07-16 02:11:22 +00003776 return true;
3777}
3778
3779void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003780 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003781 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003782 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003783 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003784 bool inFunctionCall, VariadicCallType CallType,
3785 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003786
Ted Kremenekab278de2010-01-28 23:39:18 +00003787 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003788 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003789 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003790 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003791 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3792 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003793 return;
3794 }
Ted Kremenek02087932010-07-16 02:11:22 +00003795
Ted Kremenekab278de2010-01-28 23:39:18 +00003796 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003797 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003798 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003799 // Account for cases where the string literal is truncated in a declaration.
3800 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3801 assert(T && "String literal not of constant array type!");
3802 size_t TypeSize = T->getSize().getZExtValue();
3803 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003804 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003805
3806 // Emit a warning if the string literal is truncated and does not contain an
3807 // embedded null character.
3808 if (TypeSize <= StrRef.size() &&
3809 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3810 CheckFormatHandler::EmitFormatDiagnostic(
3811 *this, inFunctionCall, Args[format_idx],
3812 PDiag(diag::warn_printf_format_string_not_null_terminated),
3813 FExpr->getLocStart(),
3814 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3815 return;
3816 }
3817
Ted Kremenekab278de2010-01-28 23:39:18 +00003818 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00003819 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003820 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003821 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003822 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3823 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003824 return;
3825 }
Ted Kremenek02087932010-07-16 02:11:22 +00003826
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003827 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00003828 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003829 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003830 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003831 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003832
Hans Wennborg23926bd2011-12-15 10:25:47 +00003833 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003834 getLangOpts(),
3835 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003836 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003837 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003838 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003839 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003840 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003841
Hans Wennborg23926bd2011-12-15 10:25:47 +00003842 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003843 getLangOpts(),
3844 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003845 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003846 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00003847}
3848
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003849bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
3850 // Str - The format string. NOTE: this is NOT null-terminated!
3851 StringRef StrRef = FExpr->getString();
3852 const char *Str = StrRef.data();
3853 // Account for cases where the string literal is truncated in a declaration.
3854 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3855 assert(T && "String literal not of constant array type!");
3856 size_t TypeSize = T->getSize().getZExtValue();
3857 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
3858 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
3859 getLangOpts(),
3860 Context.getTargetInfo());
3861}
3862
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003863//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
3864
3865// Returns the related absolute value function that is larger, of 0 if one
3866// does not exist.
3867static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
3868 switch (AbsFunction) {
3869 default:
3870 return 0;
3871
3872 case Builtin::BI__builtin_abs:
3873 return Builtin::BI__builtin_labs;
3874 case Builtin::BI__builtin_labs:
3875 return Builtin::BI__builtin_llabs;
3876 case Builtin::BI__builtin_llabs:
3877 return 0;
3878
3879 case Builtin::BI__builtin_fabsf:
3880 return Builtin::BI__builtin_fabs;
3881 case Builtin::BI__builtin_fabs:
3882 return Builtin::BI__builtin_fabsl;
3883 case Builtin::BI__builtin_fabsl:
3884 return 0;
3885
3886 case Builtin::BI__builtin_cabsf:
3887 return Builtin::BI__builtin_cabs;
3888 case Builtin::BI__builtin_cabs:
3889 return Builtin::BI__builtin_cabsl;
3890 case Builtin::BI__builtin_cabsl:
3891 return 0;
3892
3893 case Builtin::BIabs:
3894 return Builtin::BIlabs;
3895 case Builtin::BIlabs:
3896 return Builtin::BIllabs;
3897 case Builtin::BIllabs:
3898 return 0;
3899
3900 case Builtin::BIfabsf:
3901 return Builtin::BIfabs;
3902 case Builtin::BIfabs:
3903 return Builtin::BIfabsl;
3904 case Builtin::BIfabsl:
3905 return 0;
3906
3907 case Builtin::BIcabsf:
3908 return Builtin::BIcabs;
3909 case Builtin::BIcabs:
3910 return Builtin::BIcabsl;
3911 case Builtin::BIcabsl:
3912 return 0;
3913 }
3914}
3915
3916// Returns the argument type of the absolute value function.
3917static QualType getAbsoluteValueArgumentType(ASTContext &Context,
3918 unsigned AbsType) {
3919 if (AbsType == 0)
3920 return QualType();
3921
3922 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3923 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
3924 if (Error != ASTContext::GE_None)
3925 return QualType();
3926
3927 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
3928 if (!FT)
3929 return QualType();
3930
3931 if (FT->getNumParams() != 1)
3932 return QualType();
3933
3934 return FT->getParamType(0);
3935}
3936
3937// Returns the best absolute value function, or zero, based on type and
3938// current absolute value function.
3939static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
3940 unsigned AbsFunctionKind) {
3941 unsigned BestKind = 0;
3942 uint64_t ArgSize = Context.getTypeSize(ArgType);
3943 for (unsigned Kind = AbsFunctionKind; Kind != 0;
3944 Kind = getLargerAbsoluteValueFunction(Kind)) {
3945 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
3946 if (Context.getTypeSize(ParamType) >= ArgSize) {
3947 if (BestKind == 0)
3948 BestKind = Kind;
3949 else if (Context.hasSameType(ParamType, ArgType)) {
3950 BestKind = Kind;
3951 break;
3952 }
3953 }
3954 }
3955 return BestKind;
3956}
3957
3958enum AbsoluteValueKind {
3959 AVK_Integer,
3960 AVK_Floating,
3961 AVK_Complex
3962};
3963
3964static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
3965 if (T->isIntegralOrEnumerationType())
3966 return AVK_Integer;
3967 if (T->isRealFloatingType())
3968 return AVK_Floating;
3969 if (T->isAnyComplexType())
3970 return AVK_Complex;
3971
3972 llvm_unreachable("Type not integer, floating, or complex");
3973}
3974
3975// Changes the absolute value function to a different type. Preserves whether
3976// the function is a builtin.
3977static unsigned changeAbsFunction(unsigned AbsKind,
3978 AbsoluteValueKind ValueKind) {
3979 switch (ValueKind) {
3980 case AVK_Integer:
3981 switch (AbsKind) {
3982 default:
3983 return 0;
3984 case Builtin::BI__builtin_fabsf:
3985 case Builtin::BI__builtin_fabs:
3986 case Builtin::BI__builtin_fabsl:
3987 case Builtin::BI__builtin_cabsf:
3988 case Builtin::BI__builtin_cabs:
3989 case Builtin::BI__builtin_cabsl:
3990 return Builtin::BI__builtin_abs;
3991 case Builtin::BIfabsf:
3992 case Builtin::BIfabs:
3993 case Builtin::BIfabsl:
3994 case Builtin::BIcabsf:
3995 case Builtin::BIcabs:
3996 case Builtin::BIcabsl:
3997 return Builtin::BIabs;
3998 }
3999 case AVK_Floating:
4000 switch (AbsKind) {
4001 default:
4002 return 0;
4003 case Builtin::BI__builtin_abs:
4004 case Builtin::BI__builtin_labs:
4005 case Builtin::BI__builtin_llabs:
4006 case Builtin::BI__builtin_cabsf:
4007 case Builtin::BI__builtin_cabs:
4008 case Builtin::BI__builtin_cabsl:
4009 return Builtin::BI__builtin_fabsf;
4010 case Builtin::BIabs:
4011 case Builtin::BIlabs:
4012 case Builtin::BIllabs:
4013 case Builtin::BIcabsf:
4014 case Builtin::BIcabs:
4015 case Builtin::BIcabsl:
4016 return Builtin::BIfabsf;
4017 }
4018 case AVK_Complex:
4019 switch (AbsKind) {
4020 default:
4021 return 0;
4022 case Builtin::BI__builtin_abs:
4023 case Builtin::BI__builtin_labs:
4024 case Builtin::BI__builtin_llabs:
4025 case Builtin::BI__builtin_fabsf:
4026 case Builtin::BI__builtin_fabs:
4027 case Builtin::BI__builtin_fabsl:
4028 return Builtin::BI__builtin_cabsf;
4029 case Builtin::BIabs:
4030 case Builtin::BIlabs:
4031 case Builtin::BIllabs:
4032 case Builtin::BIfabsf:
4033 case Builtin::BIfabs:
4034 case Builtin::BIfabsl:
4035 return Builtin::BIcabsf;
4036 }
4037 }
4038 llvm_unreachable("Unable to convert function");
4039}
4040
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004041static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004042 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4043 if (!FnInfo)
4044 return 0;
4045
4046 switch (FDecl->getBuiltinID()) {
4047 default:
4048 return 0;
4049 case Builtin::BI__builtin_abs:
4050 case Builtin::BI__builtin_fabs:
4051 case Builtin::BI__builtin_fabsf:
4052 case Builtin::BI__builtin_fabsl:
4053 case Builtin::BI__builtin_labs:
4054 case Builtin::BI__builtin_llabs:
4055 case Builtin::BI__builtin_cabs:
4056 case Builtin::BI__builtin_cabsf:
4057 case Builtin::BI__builtin_cabsl:
4058 case Builtin::BIabs:
4059 case Builtin::BIlabs:
4060 case Builtin::BIllabs:
4061 case Builtin::BIfabs:
4062 case Builtin::BIfabsf:
4063 case Builtin::BIfabsl:
4064 case Builtin::BIcabs:
4065 case Builtin::BIcabsf:
4066 case Builtin::BIcabsl:
4067 return FDecl->getBuiltinID();
4068 }
4069 llvm_unreachable("Unknown Builtin type");
4070}
4071
4072// If the replacement is valid, emit a note with replacement function.
4073// Additionally, suggest including the proper header if not already included.
4074static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004075 unsigned AbsKind, QualType ArgType) {
4076 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004077 const char *HeaderName = nullptr;
4078 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004079 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4080 FunctionName = "std::abs";
4081 if (ArgType->isIntegralOrEnumerationType()) {
4082 HeaderName = "cstdlib";
4083 } else if (ArgType->isRealFloatingType()) {
4084 HeaderName = "cmath";
4085 } else {
4086 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004087 }
Richard Trieubeffb832014-04-15 23:47:53 +00004088
4089 // Lookup all std::abs
4090 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004091 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004092 R.suppressDiagnostics();
4093 S.LookupQualifiedName(R, Std);
4094
4095 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004096 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004097 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4098 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4099 } else {
4100 FDecl = dyn_cast<FunctionDecl>(I);
4101 }
4102 if (!FDecl)
4103 continue;
4104
4105 // Found std::abs(), check that they are the right ones.
4106 if (FDecl->getNumParams() != 1)
4107 continue;
4108
4109 // Check that the parameter type can handle the argument.
4110 QualType ParamType = FDecl->getParamDecl(0)->getType();
4111 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4112 S.Context.getTypeSize(ArgType) <=
4113 S.Context.getTypeSize(ParamType)) {
4114 // Found a function, don't need the header hint.
4115 EmitHeaderHint = false;
4116 break;
4117 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004118 }
Richard Trieubeffb832014-04-15 23:47:53 +00004119 }
4120 } else {
4121 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4122 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4123
4124 if (HeaderName) {
4125 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4126 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4127 R.suppressDiagnostics();
4128 S.LookupName(R, S.getCurScope());
4129
4130 if (R.isSingleResult()) {
4131 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4132 if (FD && FD->getBuiltinID() == AbsKind) {
4133 EmitHeaderHint = false;
4134 } else {
4135 return;
4136 }
4137 } else if (!R.empty()) {
4138 return;
4139 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004140 }
4141 }
4142
4143 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00004144 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004145
Richard Trieubeffb832014-04-15 23:47:53 +00004146 if (!HeaderName)
4147 return;
4148
4149 if (!EmitHeaderHint)
4150 return;
4151
Alp Toker5d96e0a2014-07-11 20:53:51 +00004152 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4153 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00004154}
4155
4156static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4157 if (!FDecl)
4158 return false;
4159
4160 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4161 return false;
4162
4163 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4164
4165 while (ND && ND->isInlineNamespace()) {
4166 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004167 }
Richard Trieubeffb832014-04-15 23:47:53 +00004168
4169 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4170 return false;
4171
4172 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4173 return false;
4174
4175 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004176}
4177
4178// Warn when using the wrong abs() function.
4179void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4180 const FunctionDecl *FDecl,
4181 IdentifierInfo *FnInfo) {
4182 if (Call->getNumArgs() != 1)
4183 return;
4184
4185 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00004186 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4187 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004188 return;
4189
4190 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4191 QualType ParamType = Call->getArg(0)->getType();
4192
Alp Toker5d96e0a2014-07-11 20:53:51 +00004193 // Unsigned types cannot be negative. Suggest removing the absolute value
4194 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004195 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00004196 const char *FunctionName =
4197 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004198 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4199 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00004200 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004201 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4202 return;
4203 }
4204
Richard Trieubeffb832014-04-15 23:47:53 +00004205 // std::abs has overloads which prevent most of the absolute value problems
4206 // from occurring.
4207 if (IsStdAbs)
4208 return;
4209
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004210 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4211 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4212
4213 // The argument and parameter are the same kind. Check if they are the right
4214 // size.
4215 if (ArgValueKind == ParamValueKind) {
4216 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4217 return;
4218
4219 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4220 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4221 << FDecl << ArgType << ParamType;
4222
4223 if (NewAbsKind == 0)
4224 return;
4225
4226 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004227 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004228 return;
4229 }
4230
4231 // ArgValueKind != ParamValueKind
4232 // The wrong type of absolute value function was used. Attempt to find the
4233 // proper one.
4234 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4235 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4236 if (NewAbsKind == 0)
4237 return;
4238
4239 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4240 << FDecl << ParamValueKind << ArgValueKind;
4241
4242 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004243 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004244 return;
4245}
4246
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004247//===--- CHECK: Standard memory functions ---------------------------------===//
4248
Nico Weber0e6daef2013-12-26 23:38:39 +00004249/// \brief Takes the expression passed to the size_t parameter of functions
4250/// such as memcmp, strncat, etc and warns if it's a comparison.
4251///
4252/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4253static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4254 IdentifierInfo *FnName,
4255 SourceLocation FnLoc,
4256 SourceLocation RParenLoc) {
4257 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4258 if (!Size)
4259 return false;
4260
4261 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4262 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4263 return false;
4264
Nico Weber0e6daef2013-12-26 23:38:39 +00004265 SourceRange SizeRange = Size->getSourceRange();
4266 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4267 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00004268 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004269 << FnName << FixItHint::CreateInsertion(
4270 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00004271 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00004272 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00004273 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00004274 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4275 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00004276
4277 return true;
4278}
4279
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004280/// \brief Determine whether the given type is or contains a dynamic class type
4281/// (e.g., whether it has a vtable).
4282static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4283 bool &IsContained) {
4284 // Look through array types while ignoring qualifiers.
4285 const Type *Ty = T->getBaseElementTypeUnsafe();
4286 IsContained = false;
4287
4288 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4289 RD = RD ? RD->getDefinition() : nullptr;
4290 if (!RD)
4291 return nullptr;
4292
4293 if (RD->isDynamicClass())
4294 return RD;
4295
4296 // Check all the fields. If any bases were dynamic, the class is dynamic.
4297 // It's impossible for a class to transitively contain itself by value, so
4298 // infinite recursion is impossible.
4299 for (auto *FD : RD->fields()) {
4300 bool SubContained;
4301 if (const CXXRecordDecl *ContainedRD =
4302 getContainedDynamicClass(FD->getType(), SubContained)) {
4303 IsContained = true;
4304 return ContainedRD;
4305 }
4306 }
4307
4308 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004309}
4310
Chandler Carruth889ed862011-06-21 23:04:20 +00004311/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004312/// otherwise returns NULL.
4313static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004314 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004315 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4316 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4317 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004318
Craig Topperc3ec1492014-05-26 06:22:03 +00004319 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004320}
4321
Chandler Carruth889ed862011-06-21 23:04:20 +00004322/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004323static QualType getSizeOfArgType(const Expr* E) {
4324 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4325 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4326 if (SizeOf->getKind() == clang::UETT_SizeOf)
4327 return SizeOf->getTypeOfArgument();
4328
4329 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004330}
4331
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004332/// \brief Check for dangerous or invalid arguments to memset().
4333///
Chandler Carruthac687262011-06-03 06:23:57 +00004334/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004335/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4336/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004337///
4338/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004339void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004340 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004341 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004342 assert(BId != 0);
4343
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004344 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004345 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004346 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004347 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004348 return;
4349
Anna Zaks22122702012-01-17 00:37:07 +00004350 unsigned LastArg = (BId == Builtin::BImemset ||
4351 BId == Builtin::BIstrndup ? 1 : 2);
4352 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004353 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004354
Nico Weber0e6daef2013-12-26 23:38:39 +00004355 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4356 Call->getLocStart(), Call->getRParenLoc()))
4357 return;
4358
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004359 // We have special checking when the length is a sizeof expression.
4360 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4361 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4362 llvm::FoldingSetNodeID SizeOfArgID;
4363
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004364 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4365 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004366 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004367
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004368 QualType DestTy = Dest->getType();
4369 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4370 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004371
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004372 // Never warn about void type pointers. This can be used to suppress
4373 // false positives.
4374 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004375 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004376
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004377 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4378 // actually comparing the expressions for equality. Because computing the
4379 // expression IDs can be expensive, we only do this if the diagnostic is
4380 // enabled.
4381 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004382 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4383 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004384 // We only compute IDs for expressions if the warning is enabled, and
4385 // cache the sizeof arg's ID.
4386 if (SizeOfArgID == llvm::FoldingSetNodeID())
4387 SizeOfArg->Profile(SizeOfArgID, Context, true);
4388 llvm::FoldingSetNodeID DestID;
4389 Dest->Profile(DestID, Context, true);
4390 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004391 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4392 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004393 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004394 StringRef ReadableName = FnName->getName();
4395
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004396 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004397 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004398 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004399 if (!PointeeTy->isIncompleteType() &&
4400 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004401 ActionIdx = 2; // If the pointee's size is sizeof(char),
4402 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004403
4404 // If the function is defined as a builtin macro, do not show macro
4405 // expansion.
4406 SourceLocation SL = SizeOfArg->getExprLoc();
4407 SourceRange DSR = Dest->getSourceRange();
4408 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004409 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004410
4411 if (SM.isMacroArgExpansion(SL)) {
4412 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4413 SL = SM.getSpellingLoc(SL);
4414 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4415 SM.getSpellingLoc(DSR.getEnd()));
4416 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4417 SM.getSpellingLoc(SSR.getEnd()));
4418 }
4419
Anna Zaksd08d9152012-05-30 23:14:52 +00004420 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004421 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004422 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004423 << PointeeTy
4424 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004425 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004426 << SSR);
4427 DiagRuntimeBehavior(SL, SizeOfArg,
4428 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4429 << ActionIdx
4430 << SSR);
4431
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004432 break;
4433 }
4434 }
4435
4436 // Also check for cases where the sizeof argument is the exact same
4437 // type as the memory argument, and where it points to a user-defined
4438 // record type.
4439 if (SizeOfArgTy != QualType()) {
4440 if (PointeeTy->isRecordType() &&
4441 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4442 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4443 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4444 << FnName << SizeOfArgTy << ArgIdx
4445 << PointeeTy << Dest->getSourceRange()
4446 << LenExpr->getSourceRange());
4447 break;
4448 }
Nico Weberc5e73862011-06-14 16:14:58 +00004449 }
4450
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004451 // Always complain about dynamic classes.
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004452 bool IsContained;
4453 if (const CXXRecordDecl *ContainedRD =
4454 getContainedDynamicClass(PointeeTy, IsContained)) {
Anna Zaks22122702012-01-17 00:37:07 +00004455
4456 unsigned OperationType = 0;
4457 // "overwritten" if we're warning about the destination for any call
4458 // but memcmp; otherwise a verb appropriate to the call.
4459 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4460 if (BId == Builtin::BImemcpy)
4461 OperationType = 1;
4462 else if(BId == Builtin::BImemmove)
4463 OperationType = 2;
4464 else if (BId == Builtin::BImemcmp)
4465 OperationType = 3;
4466 }
4467
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004468 DiagRuntimeBehavior(
4469 Dest->getExprLoc(), Dest,
4470 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004471 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004472 << FnName << IsContained << ContainedRD << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004473 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004474 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4475 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004476 DiagRuntimeBehavior(
4477 Dest->getExprLoc(), Dest,
4478 PDiag(diag::warn_arc_object_memaccess)
4479 << ArgIdx << FnName << PointeeTy
4480 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004481 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004482 continue;
John McCall31168b02011-06-15 23:02:42 +00004483
4484 DiagRuntimeBehavior(
4485 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004486 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004487 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4488 break;
4489 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004490 }
4491}
4492
Ted Kremenek6865f772011-08-18 20:55:45 +00004493// A little helper routine: ignore addition and subtraction of integer literals.
4494// This intentionally does not ignore all integer constant expressions because
4495// we don't want to remove sizeof().
4496static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4497 Ex = Ex->IgnoreParenCasts();
4498
4499 for (;;) {
4500 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4501 if (!BO || !BO->isAdditiveOp())
4502 break;
4503
4504 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4505 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4506
4507 if (isa<IntegerLiteral>(RHS))
4508 Ex = LHS;
4509 else if (isa<IntegerLiteral>(LHS))
4510 Ex = RHS;
4511 else
4512 break;
4513 }
4514
4515 return Ex;
4516}
4517
Anna Zaks13b08572012-08-08 21:42:23 +00004518static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4519 ASTContext &Context) {
4520 // Only handle constant-sized or VLAs, but not flexible members.
4521 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4522 // Only issue the FIXIT for arrays of size > 1.
4523 if (CAT->getSize().getSExtValue() <= 1)
4524 return false;
4525 } else if (!Ty->isVariableArrayType()) {
4526 return false;
4527 }
4528 return true;
4529}
4530
Ted Kremenek6865f772011-08-18 20:55:45 +00004531// Warn if the user has made the 'size' argument to strlcpy or strlcat
4532// be the size of the source, instead of the destination.
4533void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4534 IdentifierInfo *FnName) {
4535
4536 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00004537 unsigned NumArgs = Call->getNumArgs();
4538 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00004539 return;
4540
4541 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4542 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004543 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00004544
4545 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4546 Call->getLocStart(), Call->getRParenLoc()))
4547 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004548
4549 // Look for 'strlcpy(dst, x, sizeof(x))'
4550 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4551 CompareWithSrc = Ex;
4552 else {
4553 // Look for 'strlcpy(dst, x, strlen(x))'
4554 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004555 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4556 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004557 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4558 }
4559 }
4560
4561 if (!CompareWithSrc)
4562 return;
4563
4564 // Determine if the argument to sizeof/strlen is equal to the source
4565 // argument. In principle there's all kinds of things you could do
4566 // here, for instance creating an == expression and evaluating it with
4567 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4568 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4569 if (!SrcArgDRE)
4570 return;
4571
4572 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4573 if (!CompareWithSrcDRE ||
4574 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4575 return;
4576
4577 const Expr *OriginalSizeArg = Call->getArg(2);
4578 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4579 << OriginalSizeArg->getSourceRange() << FnName;
4580
4581 // Output a FIXIT hint if the destination is an array (rather than a
4582 // pointer to an array). This could be enhanced to handle some
4583 // pointers if we know the actual size, like if DstArg is 'array+2'
4584 // we could say 'sizeof(array)-2'.
4585 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004586 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004587 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004588
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004589 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004590 llvm::raw_svector_ostream OS(sizeString);
4591 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004592 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004593 OS << ")";
4594
4595 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4596 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4597 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004598}
4599
Anna Zaks314cd092012-02-01 19:08:57 +00004600/// Check if two expressions refer to the same declaration.
4601static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4602 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4603 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4604 return D1->getDecl() == D2->getDecl();
4605 return false;
4606}
4607
4608static const Expr *getStrlenExprArg(const Expr *E) {
4609 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4610 const FunctionDecl *FD = CE->getDirectCallee();
4611 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00004612 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004613 return CE->getArg(0)->IgnoreParenCasts();
4614 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004615 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004616}
4617
4618// Warn on anti-patterns as the 'size' argument to strncat.
4619// The correct size argument should look like following:
4620// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4621void Sema::CheckStrncatArguments(const CallExpr *CE,
4622 IdentifierInfo *FnName) {
4623 // Don't crash if the user has the wrong number of arguments.
4624 if (CE->getNumArgs() < 3)
4625 return;
4626 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4627 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4628 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4629
Nico Weber0e6daef2013-12-26 23:38:39 +00004630 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4631 CE->getRParenLoc()))
4632 return;
4633
Anna Zaks314cd092012-02-01 19:08:57 +00004634 // Identify common expressions, which are wrongly used as the size argument
4635 // to strncat and may lead to buffer overflows.
4636 unsigned PatternType = 0;
4637 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4638 // - sizeof(dst)
4639 if (referToTheSameDecl(SizeOfArg, DstArg))
4640 PatternType = 1;
4641 // - sizeof(src)
4642 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4643 PatternType = 2;
4644 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4645 if (BE->getOpcode() == BO_Sub) {
4646 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4647 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4648 // - sizeof(dst) - strlen(dst)
4649 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4650 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4651 PatternType = 1;
4652 // - sizeof(src) - (anything)
4653 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4654 PatternType = 2;
4655 }
4656 }
4657
4658 if (PatternType == 0)
4659 return;
4660
Anna Zaks5069aa32012-02-03 01:27:37 +00004661 // Generate the diagnostic.
4662 SourceLocation SL = LenArg->getLocStart();
4663 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004664 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00004665
4666 // If the function is defined as a builtin macro, do not show macro expansion.
4667 if (SM.isMacroArgExpansion(SL)) {
4668 SL = SM.getSpellingLoc(SL);
4669 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4670 SM.getSpellingLoc(SR.getEnd()));
4671 }
4672
Anna Zaks13b08572012-08-08 21:42:23 +00004673 // Check if the destination is an array (rather than a pointer to an array).
4674 QualType DstTy = DstArg->getType();
4675 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4676 Context);
4677 if (!isKnownSizeArray) {
4678 if (PatternType == 1)
4679 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4680 else
4681 Diag(SL, diag::warn_strncat_src_size) << SR;
4682 return;
4683 }
4684
Anna Zaks314cd092012-02-01 19:08:57 +00004685 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004686 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004687 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004688 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004689
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004690 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004691 llvm::raw_svector_ostream OS(sizeString);
4692 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004693 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004694 OS << ") - ";
4695 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004696 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004697 OS << ") - 1";
4698
Anna Zaks5069aa32012-02-03 01:27:37 +00004699 Diag(SL, diag::note_strncat_wrong_size)
4700 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004701}
4702
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004703//===--- CHECK: Return Address of Stack Variable --------------------------===//
4704
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004705static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4706 Decl *ParentDecl);
4707static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4708 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004709
4710/// CheckReturnStackAddr - Check if a return statement returns the address
4711/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004712static void
4713CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4714 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004715
Craig Topperc3ec1492014-05-26 06:22:03 +00004716 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004717 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004718
4719 // Perform checking for returned stack addresses, local blocks,
4720 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004721 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004722 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004723 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00004724 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004725 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004726 }
4727
Craig Topperc3ec1492014-05-26 06:22:03 +00004728 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004729 return; // Nothing suspicious was found.
4730
4731 SourceLocation diagLoc;
4732 SourceRange diagRange;
4733 if (refVars.empty()) {
4734 diagLoc = stackE->getLocStart();
4735 diagRange = stackE->getSourceRange();
4736 } else {
4737 // We followed through a reference variable. 'stackE' contains the
4738 // problematic expression but we will warn at the return statement pointing
4739 // at the reference variable. We will later display the "trail" of
4740 // reference variables using notes.
4741 diagLoc = refVars[0]->getLocStart();
4742 diagRange = refVars[0]->getSourceRange();
4743 }
4744
4745 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004746 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004747 : diag::warn_ret_stack_addr)
4748 << DR->getDecl()->getDeclName() << diagRange;
4749 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004750 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004751 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004752 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004753 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004754 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4755 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004756 << diagRange;
4757 }
4758
4759 // Display the "trail" of reference variables that we followed until we
4760 // found the problematic expression using notes.
4761 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4762 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4763 // If this var binds to another reference var, show the range of the next
4764 // var, otherwise the var binds to the problematic expression, in which case
4765 // show the range of the expression.
4766 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4767 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004768 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4769 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004770 }
4771}
4772
4773/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4774/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004775/// to a location on the stack, a local block, an address of a label, or a
4776/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004777/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004778/// encounter a subexpression that (1) clearly does not lead to one of the
4779/// above problematic expressions (2) is something we cannot determine leads to
4780/// a problematic expression based on such local checking.
4781///
4782/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4783/// the expression that they point to. Such variables are added to the
4784/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004785///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004786/// EvalAddr processes expressions that are pointers that are used as
4787/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004788/// At the base case of the recursion is a check for the above problematic
4789/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004790///
4791/// This implementation handles:
4792///
4793/// * pointer-to-pointer casts
4794/// * implicit conversions from array references to pointers
4795/// * taking the address of fields
4796/// * arbitrary interplay between "&" and "*" operators
4797/// * pointer arithmetic from an address of a stack variable
4798/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004799static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4800 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004801 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00004802 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004803
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004804 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00004805 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004806 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004807 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00004808 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00004809
Peter Collingbourne91147592011-04-15 00:35:48 +00004810 E = E->IgnoreParens();
4811
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004812 // Our "symbolic interpreter" is just a dispatch off the currently
4813 // viewed AST node. We then recursively traverse the AST by calling
4814 // EvalAddr and EvalVal appropriately.
4815 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004816 case Stmt::DeclRefExprClass: {
4817 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4818
Richard Smith40f08eb2014-01-30 22:05:38 +00004819 // If we leave the immediate function, the lifetime isn't about to end.
4820 if (DR->refersToEnclosingLocal())
Craig Topperc3ec1492014-05-26 06:22:03 +00004821 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00004822
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004823 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4824 // If this is a reference variable, follow through to the expression that
4825 // it points to.
4826 if (V->hasLocalStorage() &&
4827 V->getType()->isReferenceType() && V->hasInit()) {
4828 // Add the reference variable to the "trail".
4829 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004830 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004831 }
4832
Craig Topperc3ec1492014-05-26 06:22:03 +00004833 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004834 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004835
Chris Lattner934edb22007-12-28 05:31:15 +00004836 case Stmt::UnaryOperatorClass: {
4837 // The only unary operator that make sense to handle here
4838 // is AddrOf. All others don't make sense as pointers.
4839 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004840
John McCalle3027922010-08-25 11:45:40 +00004841 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004842 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004843 else
Craig Topperc3ec1492014-05-26 06:22:03 +00004844 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004845 }
Mike Stump11289f42009-09-09 15:08:12 +00004846
Chris Lattner934edb22007-12-28 05:31:15 +00004847 case Stmt::BinaryOperatorClass: {
4848 // Handle pointer arithmetic. All other binary operators are not valid
4849 // in this context.
4850 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00004851 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00004852
John McCalle3027922010-08-25 11:45:40 +00004853 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00004854 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004855
Chris Lattner934edb22007-12-28 05:31:15 +00004856 Expr *Base = B->getLHS();
4857
4858 // Determine which argument is the real pointer base. It could be
4859 // the RHS argument instead of the LHS.
4860 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00004861
Chris Lattner934edb22007-12-28 05:31:15 +00004862 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004863 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004864 }
Steve Naroff2752a172008-09-10 19:17:48 +00004865
Chris Lattner934edb22007-12-28 05:31:15 +00004866 // For conditional operators we need to see if either the LHS or RHS are
4867 // valid DeclRefExpr*s. If one of them is valid, we return it.
4868 case Stmt::ConditionalOperatorClass: {
4869 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004870
Chris Lattner934edb22007-12-28 05:31:15 +00004871 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004872 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4873 if (Expr *LHSExpr = C->getLHS()) {
4874 // In C++, we can have a throw-expression, which has 'void' type.
4875 if (!LHSExpr->getType()->isVoidType())
4876 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004877 return LHS;
4878 }
Chris Lattner934edb22007-12-28 05:31:15 +00004879
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004880 // In C++, we can have a throw-expression, which has 'void' type.
4881 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004882 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004883
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004884 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004885 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004886
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004887 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00004888 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004889 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00004890 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004891
4892 case Stmt::AddrLabelExprClass:
4893 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00004894
John McCall28fc7092011-11-10 05:35:25 +00004895 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004896 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4897 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004898
Ted Kremenekc3b4c522008-08-07 00:49:01 +00004899 // For casts, we need to handle conversions from arrays to
4900 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00004901 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00004902 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00004903 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00004904 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00004905 case Stmt::CXXStaticCastExprClass:
4906 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00004907 case Stmt::CXXConstCastExprClass:
4908 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00004909 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4910 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00004911 case CK_LValueToRValue:
4912 case CK_NoOp:
4913 case CK_BaseToDerived:
4914 case CK_DerivedToBase:
4915 case CK_UncheckedDerivedToBase:
4916 case CK_Dynamic:
4917 case CK_CPointerToObjCPointerCast:
4918 case CK_BlockPointerToObjCPointerCast:
4919 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004920 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004921
4922 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004923 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004924
Richard Trieudadefde2014-07-02 04:39:38 +00004925 case CK_BitCast:
4926 if (SubExpr->getType()->isAnyPointerType() ||
4927 SubExpr->getType()->isBlockPointerType() ||
4928 SubExpr->getType()->isObjCQualifiedIdType())
4929 return EvalAddr(SubExpr, refVars, ParentDecl);
4930 else
4931 return nullptr;
4932
Eli Friedman8195ad72012-02-23 23:04:32 +00004933 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00004934 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00004935 }
Chris Lattner934edb22007-12-28 05:31:15 +00004936 }
Mike Stump11289f42009-09-09 15:08:12 +00004937
Douglas Gregorfe314812011-06-21 17:03:29 +00004938 case Stmt::MaterializeTemporaryExprClass:
4939 if (Expr *Result = EvalAddr(
4940 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004941 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004942 return Result;
4943
4944 return E;
4945
Chris Lattner934edb22007-12-28 05:31:15 +00004946 // Everything else: we simply don't reason about them.
4947 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00004948 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00004949 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004950}
Mike Stump11289f42009-09-09 15:08:12 +00004951
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004952
4953/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4954/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004955static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4956 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004957do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004958 // We should only be called for evaluating non-pointer expressions, or
4959 // expressions with a pointer type that are not used as references but instead
4960 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00004961
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004962 // Our "symbolic interpreter" is just a dispatch off the currently
4963 // viewed AST node. We then recursively traverse the AST by calling
4964 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00004965
4966 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004967 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004968 case Stmt::ImplicitCastExprClass: {
4969 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00004970 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004971 E = IE->getSubExpr();
4972 continue;
4973 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004974 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00004975 }
4976
John McCall28fc7092011-11-10 05:35:25 +00004977 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004978 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004979
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004980 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004981 // When we hit a DeclRefExpr we are looking at code that refers to a
4982 // variable's name. If it's not a reference variable we check if it has
4983 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004984 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004985
Richard Smith40f08eb2014-01-30 22:05:38 +00004986 // If we leave the immediate function, the lifetime isn't about to end.
4987 if (DR->refersToEnclosingLocal())
Craig Topperc3ec1492014-05-26 06:22:03 +00004988 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00004989
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004990 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4991 // Check if it refers to itself, e.g. "int& i = i;".
4992 if (V == ParentDecl)
4993 return DR;
4994
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004995 if (V->hasLocalStorage()) {
4996 if (!V->getType()->isReferenceType())
4997 return DR;
4998
4999 // Reference variable, follow through to the expression that
5000 // it points to.
5001 if (V->hasInit()) {
5002 // Add the reference variable to the "trail".
5003 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005004 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005005 }
5006 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005007 }
Mike Stump11289f42009-09-09 15:08:12 +00005008
Craig Topperc3ec1492014-05-26 06:22:03 +00005009 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005010 }
Mike Stump11289f42009-09-09 15:08:12 +00005011
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005012 case Stmt::UnaryOperatorClass: {
5013 // The only unary operator that make sense to handle here
5014 // is Deref. All others don't resolve to a "name." This includes
5015 // handling all sorts of rvalues passed to a unary operator.
5016 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005017
John McCalle3027922010-08-25 11:45:40 +00005018 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005019 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005020
Craig Topperc3ec1492014-05-26 06:22:03 +00005021 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005022 }
Mike Stump11289f42009-09-09 15:08:12 +00005023
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005024 case Stmt::ArraySubscriptExprClass: {
5025 // Array subscripts are potential references to data on the stack. We
5026 // retrieve the DeclRefExpr* for the array variable if it indeed
5027 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005028 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005029 }
Mike Stump11289f42009-09-09 15:08:12 +00005030
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005031 case Stmt::ConditionalOperatorClass: {
5032 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005033 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005034 ConditionalOperator *C = cast<ConditionalOperator>(E);
5035
Anders Carlsson801c5c72007-11-30 19:04:31 +00005036 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005037 if (Expr *LHSExpr = C->getLHS()) {
5038 // In C++, we can have a throw-expression, which has 'void' type.
5039 if (!LHSExpr->getType()->isVoidType())
5040 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5041 return LHS;
5042 }
5043
5044 // In C++, we can have a throw-expression, which has 'void' type.
5045 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005046 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005047
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005048 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005049 }
Mike Stump11289f42009-09-09 15:08:12 +00005050
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005051 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005052 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005053 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005054
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005055 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005056 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005057 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005058
5059 // Check whether the member type is itself a reference, in which case
5060 // we're not going to refer to the member, but to what the member refers to.
5061 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005062 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005063
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005064 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005065 }
Mike Stump11289f42009-09-09 15:08:12 +00005066
Douglas Gregorfe314812011-06-21 17:03:29 +00005067 case Stmt::MaterializeTemporaryExprClass:
5068 if (Expr *Result = EvalVal(
5069 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005070 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005071 return Result;
5072
5073 return E;
5074
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005075 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005076 // Check that we don't return or take the address of a reference to a
5077 // temporary. This is only useful in C++.
5078 if (!E->isTypeDependent() && E->isRValue())
5079 return E;
5080
5081 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005082 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005083 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005084} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005085}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005086
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005087void
5088Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5089 SourceLocation ReturnLoc,
5090 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005091 const AttrVec *Attrs,
5092 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005093 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5094
5095 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00005096 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5097 CheckNonNullExpr(*this, RetValExp))
5098 Diag(ReturnLoc, diag::warn_null_ret)
5099 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00005100
5101 // C++11 [basic.stc.dynamic.allocation]p4:
5102 // If an allocation function declared with a non-throwing
5103 // exception-specification fails to allocate storage, it shall return
5104 // a null pointer. Any other allocation function that fails to allocate
5105 // storage shall indicate failure only by throwing an exception [...]
5106 if (FD) {
5107 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5108 if (Op == OO_New || Op == OO_Array_New) {
5109 const FunctionProtoType *Proto
5110 = FD->getType()->castAs<FunctionProtoType>();
5111 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5112 CheckNonNullExpr(*this, RetValExp))
5113 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5114 << FD << getLangOpts().CPlusPlus11;
5115 }
5116 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005117}
5118
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005119//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5120
5121/// Check for comparisons of floating point operands using != and ==.
5122/// Issue a warning if these are no self-comparisons, as they are not likely
5123/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00005124void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00005125 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5126 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005127
5128 // Special case: check for x == x (which is OK).
5129 // Do not emit warnings for such cases.
5130 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5131 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5132 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00005133 return;
Mike Stump11289f42009-09-09 15:08:12 +00005134
5135
Ted Kremenekeda40e22007-11-29 00:59:04 +00005136 // Special case: check for comparisons against literals that can be exactly
5137 // represented by APFloat. In such cases, do not emit a warning. This
5138 // is a heuristic: often comparison against such literals are used to
5139 // detect if a value in a variable has not changed. This clearly can
5140 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00005141 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5142 if (FLL->isExact())
5143 return;
5144 } else
5145 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5146 if (FLR->isExact())
5147 return;
Mike Stump11289f42009-09-09 15:08:12 +00005148
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005149 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00005150 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005151 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005152 return;
Mike Stump11289f42009-09-09 15:08:12 +00005153
David Blaikie1f4ff152012-07-16 20:47:22 +00005154 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005155 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005156 return;
Mike Stump11289f42009-09-09 15:08:12 +00005157
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005158 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00005159 Diag(Loc, diag::warn_floatingpoint_eq)
5160 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005161}
John McCallca01b222010-01-04 23:21:16 +00005162
John McCall70aa5392010-01-06 05:24:50 +00005163//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5164//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00005165
John McCall70aa5392010-01-06 05:24:50 +00005166namespace {
John McCallca01b222010-01-04 23:21:16 +00005167
John McCall70aa5392010-01-06 05:24:50 +00005168/// Structure recording the 'active' range of an integer-valued
5169/// expression.
5170struct IntRange {
5171 /// The number of bits active in the int.
5172 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00005173
John McCall70aa5392010-01-06 05:24:50 +00005174 /// True if the int is known not to have negative values.
5175 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00005176
John McCall70aa5392010-01-06 05:24:50 +00005177 IntRange(unsigned Width, bool NonNegative)
5178 : Width(Width), NonNegative(NonNegative)
5179 {}
John McCallca01b222010-01-04 23:21:16 +00005180
John McCall817d4af2010-11-10 23:38:19 +00005181 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00005182 static IntRange forBoolType() {
5183 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00005184 }
5185
John McCall817d4af2010-11-10 23:38:19 +00005186 /// Returns the range of an opaque value of the given integral type.
5187 static IntRange forValueOfType(ASTContext &C, QualType T) {
5188 return forValueOfCanonicalType(C,
5189 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00005190 }
5191
John McCall817d4af2010-11-10 23:38:19 +00005192 /// Returns the range of an opaque value of a canonical integral type.
5193 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00005194 assert(T->isCanonicalUnqualified());
5195
5196 if (const VectorType *VT = dyn_cast<VectorType>(T))
5197 T = VT->getElementType().getTypePtr();
5198 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5199 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005200 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5201 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00005202
David Majnemer6a426652013-06-07 22:07:20 +00005203 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00005204 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00005205 EnumDecl *Enum = ET->getDecl();
5206 if (!Enum->isCompleteDefinition())
5207 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00005208
David Majnemer6a426652013-06-07 22:07:20 +00005209 unsigned NumPositive = Enum->getNumPositiveBits();
5210 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00005211
David Majnemer6a426652013-06-07 22:07:20 +00005212 if (NumNegative == 0)
5213 return IntRange(NumPositive, true/*NonNegative*/);
5214 else
5215 return IntRange(std::max(NumPositive + 1, NumNegative),
5216 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00005217 }
John McCall70aa5392010-01-06 05:24:50 +00005218
5219 const BuiltinType *BT = cast<BuiltinType>(T);
5220 assert(BT->isInteger());
5221
5222 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5223 }
5224
John McCall817d4af2010-11-10 23:38:19 +00005225 /// Returns the "target" range of a canonical integral type, i.e.
5226 /// the range of values expressible in the type.
5227 ///
5228 /// This matches forValueOfCanonicalType except that enums have the
5229 /// full range of their type, not the range of their enumerators.
5230 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5231 assert(T->isCanonicalUnqualified());
5232
5233 if (const VectorType *VT = dyn_cast<VectorType>(T))
5234 T = VT->getElementType().getTypePtr();
5235 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5236 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005237 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5238 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005239 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00005240 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005241
5242 const BuiltinType *BT = cast<BuiltinType>(T);
5243 assert(BT->isInteger());
5244
5245 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5246 }
5247
5248 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00005249 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00005250 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00005251 L.NonNegative && R.NonNegative);
5252 }
5253
John McCall817d4af2010-11-10 23:38:19 +00005254 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00005255 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00005256 return IntRange(std::min(L.Width, R.Width),
5257 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00005258 }
5259};
5260
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005261static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5262 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005263 if (value.isSigned() && value.isNegative())
5264 return IntRange(value.getMinSignedBits(), false);
5265
5266 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005267 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005268
5269 // isNonNegative() just checks the sign bit without considering
5270 // signedness.
5271 return IntRange(value.getActiveBits(), true);
5272}
5273
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005274static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5275 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005276 if (result.isInt())
5277 return GetValueRange(C, result.getInt(), MaxWidth);
5278
5279 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00005280 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5281 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5282 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5283 R = IntRange::join(R, El);
5284 }
John McCall70aa5392010-01-06 05:24:50 +00005285 return R;
5286 }
5287
5288 if (result.isComplexInt()) {
5289 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5290 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5291 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00005292 }
5293
5294 // This can happen with lossless casts to intptr_t of "based" lvalues.
5295 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00005296 // FIXME: The only reason we need to pass the type in here is to get
5297 // the sign right on this one case. It would be nice if APValue
5298 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005299 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00005300 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005301}
John McCall70aa5392010-01-06 05:24:50 +00005302
Eli Friedmane6d33952013-07-08 20:20:06 +00005303static QualType GetExprType(Expr *E) {
5304 QualType Ty = E->getType();
5305 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5306 Ty = AtomicRHS->getValueType();
5307 return Ty;
5308}
5309
John McCall70aa5392010-01-06 05:24:50 +00005310/// Pseudo-evaluate the given integer expression, estimating the
5311/// range of values it might take.
5312///
5313/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005314static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005315 E = E->IgnoreParens();
5316
5317 // Try a full evaluation first.
5318 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005319 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005320 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005321
5322 // I think we only want to look through implicit casts here; if the
5323 // user has an explicit widening cast, we should treat the value as
5324 // being of the new, wider type.
5325 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005326 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005327 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5328
Eli Friedmane6d33952013-07-08 20:20:06 +00005329 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005330
John McCalle3027922010-08-25 11:45:40 +00005331 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005332
John McCall70aa5392010-01-06 05:24:50 +00005333 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005334 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005335 return OutputTypeRange;
5336
5337 IntRange SubRange
5338 = GetExprRange(C, CE->getSubExpr(),
5339 std::min(MaxWidth, OutputTypeRange.Width));
5340
5341 // Bail out if the subexpr's range is as wide as the cast type.
5342 if (SubRange.Width >= OutputTypeRange.Width)
5343 return OutputTypeRange;
5344
5345 // Otherwise, we take the smaller width, and we're non-negative if
5346 // either the output type or the subexpr is.
5347 return IntRange(SubRange.Width,
5348 SubRange.NonNegative || OutputTypeRange.NonNegative);
5349 }
5350
5351 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5352 // If we can fold the condition, just take that operand.
5353 bool CondResult;
5354 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5355 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5356 : CO->getFalseExpr(),
5357 MaxWidth);
5358
5359 // Otherwise, conservatively merge.
5360 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5361 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5362 return IntRange::join(L, R);
5363 }
5364
5365 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5366 switch (BO->getOpcode()) {
5367
5368 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005369 case BO_LAnd:
5370 case BO_LOr:
5371 case BO_LT:
5372 case BO_GT:
5373 case BO_LE:
5374 case BO_GE:
5375 case BO_EQ:
5376 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005377 return IntRange::forBoolType();
5378
John McCallc3688382011-07-13 06:35:24 +00005379 // The type of the assignments is the type of the LHS, so the RHS
5380 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005381 case BO_MulAssign:
5382 case BO_DivAssign:
5383 case BO_RemAssign:
5384 case BO_AddAssign:
5385 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005386 case BO_XorAssign:
5387 case BO_OrAssign:
5388 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005389 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005390
John McCallc3688382011-07-13 06:35:24 +00005391 // Simple assignments just pass through the RHS, which will have
5392 // been coerced to the LHS type.
5393 case BO_Assign:
5394 // TODO: bitfields?
5395 return GetExprRange(C, BO->getRHS(), MaxWidth);
5396
John McCall70aa5392010-01-06 05:24:50 +00005397 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005398 case BO_PtrMemD:
5399 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005400 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005401
John McCall2ce81ad2010-01-06 22:07:33 +00005402 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005403 case BO_And:
5404 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005405 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5406 GetExprRange(C, BO->getRHS(), MaxWidth));
5407
John McCall70aa5392010-01-06 05:24:50 +00005408 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005409 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005410 // ...except that we want to treat '1 << (blah)' as logically
5411 // positive. It's an important idiom.
5412 if (IntegerLiteral *I
5413 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5414 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005415 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005416 return IntRange(R.Width, /*NonNegative*/ true);
5417 }
5418 }
5419 // fallthrough
5420
John McCalle3027922010-08-25 11:45:40 +00005421 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005422 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005423
John McCall2ce81ad2010-01-06 22:07:33 +00005424 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005425 case BO_Shr:
5426 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005427 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5428
5429 // If the shift amount is a positive constant, drop the width by
5430 // that much.
5431 llvm::APSInt shift;
5432 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5433 shift.isNonNegative()) {
5434 unsigned zext = shift.getZExtValue();
5435 if (zext >= L.Width)
5436 L.Width = (L.NonNegative ? 0 : 1);
5437 else
5438 L.Width -= zext;
5439 }
5440
5441 return L;
5442 }
5443
5444 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005445 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005446 return GetExprRange(C, BO->getRHS(), MaxWidth);
5447
John McCall2ce81ad2010-01-06 22:07:33 +00005448 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005449 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005450 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005451 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005452 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005453
John McCall51431812011-07-14 22:39:48 +00005454 // The width of a division result is mostly determined by the size
5455 // of the LHS.
5456 case BO_Div: {
5457 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005458 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005459 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5460
5461 // If the divisor is constant, use that.
5462 llvm::APSInt divisor;
5463 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5464 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5465 if (log2 >= L.Width)
5466 L.Width = (L.NonNegative ? 0 : 1);
5467 else
5468 L.Width = std::min(L.Width - log2, MaxWidth);
5469 return L;
5470 }
5471
5472 // Otherwise, just use the LHS's width.
5473 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5474 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5475 }
5476
5477 // The result of a remainder can't be larger than the result of
5478 // either side.
5479 case BO_Rem: {
5480 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005481 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005482 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5483 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5484
5485 IntRange meet = IntRange::meet(L, R);
5486 meet.Width = std::min(meet.Width, MaxWidth);
5487 return meet;
5488 }
5489
5490 // The default behavior is okay for these.
5491 case BO_Mul:
5492 case BO_Add:
5493 case BO_Xor:
5494 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005495 break;
5496 }
5497
John McCall51431812011-07-14 22:39:48 +00005498 // The default case is to treat the operation as if it were closed
5499 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005500 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5501 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5502 return IntRange::join(L, R);
5503 }
5504
5505 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5506 switch (UO->getOpcode()) {
5507 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005508 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005509 return IntRange::forBoolType();
5510
5511 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005512 case UO_Deref:
5513 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005514 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005515
5516 default:
5517 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5518 }
5519 }
5520
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005521 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5522 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5523
John McCalld25db7e2013-05-06 21:39:12 +00005524 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005525 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005526 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005527
Eli Friedmane6d33952013-07-08 20:20:06 +00005528 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005529}
John McCall263a48b2010-01-04 23:31:57 +00005530
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005531static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005532 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005533}
5534
John McCall263a48b2010-01-04 23:31:57 +00005535/// Checks whether the given value, which currently has the given
5536/// source semantics, has the same value when coerced through the
5537/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005538static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5539 const llvm::fltSemantics &Src,
5540 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005541 llvm::APFloat truncated = value;
5542
5543 bool ignored;
5544 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5545 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5546
5547 return truncated.bitwiseIsEqual(value);
5548}
5549
5550/// Checks whether the given value, which currently has the given
5551/// source semantics, has the same value when coerced through the
5552/// target semantics.
5553///
5554/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005555static bool IsSameFloatAfterCast(const APValue &value,
5556 const llvm::fltSemantics &Src,
5557 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005558 if (value.isFloat())
5559 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5560
5561 if (value.isVector()) {
5562 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5563 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5564 return false;
5565 return true;
5566 }
5567
5568 assert(value.isComplexFloat());
5569 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5570 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5571}
5572
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005573static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005574
Ted Kremenek6274be42010-09-23 21:43:44 +00005575static bool IsZero(Sema &S, Expr *E) {
5576 // Suppress cases where we are comparing against an enum constant.
5577 if (const DeclRefExpr *DR =
5578 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5579 if (isa<EnumConstantDecl>(DR->getDecl()))
5580 return false;
5581
5582 // Suppress cases where the '0' value is expanded from a macro.
5583 if (E->getLocStart().isMacroID())
5584 return false;
5585
John McCallcc7e5bf2010-05-06 08:58:33 +00005586 llvm::APSInt Value;
5587 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5588}
5589
John McCall2551c1b2010-10-06 00:25:24 +00005590static bool HasEnumType(Expr *E) {
5591 // Strip off implicit integral promotions.
5592 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005593 if (ICE->getCastKind() != CK_IntegralCast &&
5594 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005595 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005596 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005597 }
5598
5599 return E->getType()->isEnumeralType();
5600}
5601
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005602static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005603 // Disable warning in template instantiations.
5604 if (!S.ActiveTemplateInstantiations.empty())
5605 return;
5606
John McCalle3027922010-08-25 11:45:40 +00005607 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005608 if (E->isValueDependent())
5609 return;
5610
John McCalle3027922010-08-25 11:45:40 +00005611 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005612 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005613 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005614 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005615 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005616 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005617 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005618 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005619 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005620 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005621 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005622 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005623 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005624 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005625 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005626 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5627 }
5628}
5629
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005630static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005631 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005632 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005633 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005634 // Disable warning in template instantiations.
5635 if (!S.ActiveTemplateInstantiations.empty())
5636 return;
5637
Richard Trieu0f097742014-04-04 04:13:47 +00005638 // TODO: Investigate using GetExprRange() to get tighter bounds
5639 // on the bit ranges.
5640 QualType OtherT = Other->getType();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005641 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5642 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00005643 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5644 unsigned OtherWidth = OtherRange.Width;
5645
5646 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5647
Richard Trieu560910c2012-11-14 22:50:24 +00005648 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00005649 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00005650 return;
5651
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005652 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00005653 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005654
Richard Trieu0f097742014-04-04 04:13:47 +00005655 // Used for diagnostic printout.
5656 enum {
5657 LiteralConstant = 0,
5658 CXXBoolLiteralTrue,
5659 CXXBoolLiteralFalse
5660 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005661
Richard Trieu0f097742014-04-04 04:13:47 +00005662 if (!OtherIsBooleanType) {
5663 QualType ConstantT = Constant->getType();
5664 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005665
Richard Trieu0f097742014-04-04 04:13:47 +00005666 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5667 return;
5668 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5669 "comparison with non-integer type");
5670
5671 bool ConstantSigned = ConstantT->isSignedIntegerType();
5672 bool CommonSigned = CommonT->isSignedIntegerType();
5673
5674 bool EqualityOnly = false;
5675
5676 if (CommonSigned) {
5677 // The common type is signed, therefore no signed to unsigned conversion.
5678 if (!OtherRange.NonNegative) {
5679 // Check that the constant is representable in type OtherT.
5680 if (ConstantSigned) {
5681 if (OtherWidth >= Value.getMinSignedBits())
5682 return;
5683 } else { // !ConstantSigned
5684 if (OtherWidth >= Value.getActiveBits() + 1)
5685 return;
5686 }
5687 } else { // !OtherSigned
5688 // Check that the constant is representable in type OtherT.
5689 // Negative values are out of range.
5690 if (ConstantSigned) {
5691 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5692 return;
5693 } else { // !ConstantSigned
5694 if (OtherWidth >= Value.getActiveBits())
5695 return;
5696 }
Richard Trieu560910c2012-11-14 22:50:24 +00005697 }
Richard Trieu0f097742014-04-04 04:13:47 +00005698 } else { // !CommonSigned
5699 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005700 if (OtherWidth >= Value.getActiveBits())
5701 return;
Craig Toppercf360162014-06-18 05:13:11 +00005702 } else { // OtherSigned
5703 assert(!ConstantSigned &&
5704 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00005705 // Check to see if the constant is representable in OtherT.
5706 if (OtherWidth > Value.getActiveBits())
5707 return;
5708 // Check to see if the constant is equivalent to a negative value
5709 // cast to CommonT.
5710 if (S.Context.getIntWidth(ConstantT) ==
5711 S.Context.getIntWidth(CommonT) &&
5712 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5713 return;
5714 // The constant value rests between values that OtherT can represent
5715 // after conversion. Relational comparison still works, but equality
5716 // comparisons will be tautological.
5717 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005718 }
5719 }
Richard Trieu0f097742014-04-04 04:13:47 +00005720
5721 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5722
5723 if (op == BO_EQ || op == BO_NE) {
5724 IsTrue = op == BO_NE;
5725 } else if (EqualityOnly) {
5726 return;
5727 } else if (RhsConstant) {
5728 if (op == BO_GT || op == BO_GE)
5729 IsTrue = !PositiveConstant;
5730 else // op == BO_LT || op == BO_LE
5731 IsTrue = PositiveConstant;
5732 } else {
5733 if (op == BO_LT || op == BO_LE)
5734 IsTrue = !PositiveConstant;
5735 else // op == BO_GT || op == BO_GE
5736 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005737 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005738 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00005739 // Other isKnownToHaveBooleanValue
5740 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
5741 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
5742 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
5743
5744 static const struct LinkedConditions {
5745 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
5746 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
5747 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
5748 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
5749 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
5750 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
5751
5752 } TruthTable = {
5753 // Constant on LHS. | Constant on RHS. |
5754 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
5755 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
5756 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
5757 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
5758 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
5759 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
5760 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
5761 };
5762
5763 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
5764
5765 enum ConstantValue ConstVal = Zero;
5766 if (Value.isUnsigned() || Value.isNonNegative()) {
5767 if (Value == 0) {
5768 LiteralOrBoolConstant =
5769 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
5770 ConstVal = Zero;
5771 } else if (Value == 1) {
5772 LiteralOrBoolConstant =
5773 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
5774 ConstVal = One;
5775 } else {
5776 LiteralOrBoolConstant = LiteralConstant;
5777 ConstVal = GT_One;
5778 }
5779 } else {
5780 ConstVal = LT_Zero;
5781 }
5782
5783 CompareBoolWithConstantResult CmpRes;
5784
5785 switch (op) {
5786 case BO_LT:
5787 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
5788 break;
5789 case BO_GT:
5790 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
5791 break;
5792 case BO_LE:
5793 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
5794 break;
5795 case BO_GE:
5796 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
5797 break;
5798 case BO_EQ:
5799 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
5800 break;
5801 case BO_NE:
5802 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
5803 break;
5804 default:
5805 CmpRes = Unkwn;
5806 break;
5807 }
5808
5809 if (CmpRes == AFals) {
5810 IsTrue = false;
5811 } else if (CmpRes == ATrue) {
5812 IsTrue = true;
5813 } else {
5814 return;
5815 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005816 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005817
5818 // If this is a comparison to an enum constant, include that
5819 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00005820 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005821 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5822 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5823
5824 SmallString<64> PrettySourceValue;
5825 llvm::raw_svector_ostream OS(PrettySourceValue);
5826 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00005827 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005828 else
5829 OS << Value;
5830
Richard Trieu0f097742014-04-04 04:13:47 +00005831 S.DiagRuntimeBehavior(
5832 E->getOperatorLoc(), E,
5833 S.PDiag(diag::warn_out_of_range_compare)
5834 << OS.str() << LiteralOrBoolConstant
5835 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
5836 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005837}
5838
John McCallcc7e5bf2010-05-06 08:58:33 +00005839/// Analyze the operands of the given comparison. Implements the
5840/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005841static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00005842 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5843 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00005844}
John McCall263a48b2010-01-04 23:31:57 +00005845
John McCallca01b222010-01-04 23:21:16 +00005846/// \brief Implements -Wsign-compare.
5847///
Richard Trieu82402a02011-09-15 21:56:47 +00005848/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005849static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005850 // The type the comparison is being performed in.
5851 QualType T = E->getLHS()->getType();
5852 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5853 && "comparison with mismatched types");
Fariborz Jahanian282071e2012-09-18 17:46:26 +00005854 if (E->isValueDependent())
5855 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005856
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005857 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5858 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005859
5860 bool IsComparisonConstant = false;
5861
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005862 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005863 // of 'true' or 'false'.
5864 if (T->isIntegralType(S.Context)) {
5865 llvm::APSInt RHSValue;
5866 bool IsRHSIntegralLiteral =
5867 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5868 llvm::APSInt LHSValue;
5869 bool IsLHSIntegralLiteral =
5870 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5871 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5872 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5873 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5874 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5875 else
5876 IsComparisonConstant =
5877 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005878 } else if (!T->hasUnsignedIntegerRepresentation())
5879 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005880
John McCallcc7e5bf2010-05-06 08:58:33 +00005881 // We don't do anything special if this isn't an unsigned integral
5882 // comparison: we're only interested in integral comparisons, and
5883 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00005884 //
5885 // We also don't care about value-dependent expressions or expressions
5886 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005887 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00005888 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005889
John McCallcc7e5bf2010-05-06 08:58:33 +00005890 // Check to see if one of the (unmodified) operands is of different
5891 // signedness.
5892 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00005893 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5894 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00005895 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00005896 signedOperand = LHS;
5897 unsignedOperand = RHS;
5898 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5899 signedOperand = RHS;
5900 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00005901 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00005902 CheckTrivialUnsignedComparison(S, E);
5903 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005904 }
5905
John McCallcc7e5bf2010-05-06 08:58:33 +00005906 // Otherwise, calculate the effective range of the signed operand.
5907 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00005908
John McCallcc7e5bf2010-05-06 08:58:33 +00005909 // Go ahead and analyze implicit conversions in the operands. Note
5910 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00005911 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5912 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00005913
John McCallcc7e5bf2010-05-06 08:58:33 +00005914 // If the signed range is non-negative, -Wsign-compare won't fire,
5915 // but we should still check for comparisons which are always true
5916 // or false.
5917 if (signedRange.NonNegative)
5918 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005919
5920 // For (in)equality comparisons, if the unsigned operand is a
5921 // constant which cannot collide with a overflowed signed operand,
5922 // then reinterpreting the signed operand as unsigned will not
5923 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00005924 if (E->isEqualityOp()) {
5925 unsigned comparisonWidth = S.Context.getIntWidth(T);
5926 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00005927
John McCallcc7e5bf2010-05-06 08:58:33 +00005928 // We should never be unable to prove that the unsigned operand is
5929 // non-negative.
5930 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5931
5932 if (unsignedRange.Width < comparisonWidth)
5933 return;
5934 }
5935
Douglas Gregorbfb4a212012-05-01 01:53:49 +00005936 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5937 S.PDiag(diag::warn_mixed_sign_comparison)
5938 << LHS->getType() << RHS->getType()
5939 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00005940}
5941
John McCall1f425642010-11-11 03:21:53 +00005942/// Analyzes an attempt to assign the given value to a bitfield.
5943///
5944/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005945static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5946 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00005947 assert(Bitfield->isBitField());
5948 if (Bitfield->isInvalidDecl())
5949 return false;
5950
John McCalldeebbcf2010-11-11 05:33:51 +00005951 // White-list bool bitfields.
5952 if (Bitfield->getType()->isBooleanType())
5953 return false;
5954
Douglas Gregor789adec2011-02-04 13:09:01 +00005955 // Ignore value- or type-dependent expressions.
5956 if (Bitfield->getBitWidth()->isValueDependent() ||
5957 Bitfield->getBitWidth()->isTypeDependent() ||
5958 Init->isValueDependent() ||
5959 Init->isTypeDependent())
5960 return false;
5961
John McCall1f425642010-11-11 03:21:53 +00005962 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5963
Richard Smith5fab0c92011-12-28 19:48:30 +00005964 llvm::APSInt Value;
5965 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00005966 return false;
5967
John McCall1f425642010-11-11 03:21:53 +00005968 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00005969 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00005970
5971 if (OriginalWidth <= FieldWidth)
5972 return false;
5973
Eli Friedmanc267a322012-01-26 23:11:39 +00005974 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005975 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00005976 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00005977
Eli Friedmanc267a322012-01-26 23:11:39 +00005978 // Check whether the stored value is equal to the original value.
5979 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00005980 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00005981 return false;
5982
Eli Friedmanc267a322012-01-26 23:11:39 +00005983 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00005984 // therefore don't strictly fit into a signed bitfield of width 1.
5985 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00005986 return false;
5987
John McCall1f425642010-11-11 03:21:53 +00005988 std::string PrettyValue = Value.toString(10);
5989 std::string PrettyTrunc = TruncatedValue.toString(10);
5990
5991 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5992 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5993 << Init->getSourceRange();
5994
5995 return true;
5996}
5997
John McCalld2a53122010-11-09 23:24:47 +00005998/// Analyze the given simple or compound assignment for warning-worthy
5999/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006000static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006001 // Just recurse on the LHS.
6002 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6003
6004 // We want to recurse on the RHS as normal unless we're assigning to
6005 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006006 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006007 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006008 E->getOperatorLoc())) {
6009 // Recurse, ignoring any implicit conversions on the RHS.
6010 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6011 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006012 }
6013 }
6014
6015 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6016}
6017
John McCall263a48b2010-01-04 23:31:57 +00006018/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006019static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006020 SourceLocation CContext, unsigned diag,
6021 bool pruneControlFlow = false) {
6022 if (pruneControlFlow) {
6023 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6024 S.PDiag(diag)
6025 << SourceType << T << E->getSourceRange()
6026 << SourceRange(CContext));
6027 return;
6028 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006029 S.Diag(E->getExprLoc(), diag)
6030 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6031}
6032
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006033/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006034static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006035 SourceLocation CContext, unsigned diag,
6036 bool pruneControlFlow = false) {
6037 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006038}
6039
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006040/// Diagnose an implicit cast from a literal expression. Does not warn when the
6041/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006042void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6043 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006044 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006045 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006046 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006047 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6048 T->hasUnsignedIntegerRepresentation());
6049 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006050 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006051 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006052 return;
6053
Eli Friedman07185912013-08-29 23:44:43 +00006054 // FIXME: Force the precision of the source value down so we don't print
6055 // digits which are usually useless (we don't really care here if we
6056 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6057 // would automatically print the shortest representation, but it's a bit
6058 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006059 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006060 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6061 precision = (precision * 59 + 195) / 196;
6062 Value.toString(PrettySourceValue, precision);
6063
David Blaikie9b88cc02012-05-15 17:18:27 +00006064 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006065 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6066 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6067 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006068 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006069
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006070 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006071 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6072 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006073}
6074
John McCall18a2c2c2010-11-09 22:22:12 +00006075std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6076 if (!Range.Width) return "0";
6077
6078 llvm::APSInt ValueInRange = Value;
6079 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006080 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006081 return ValueInRange.toString(10);
6082}
6083
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006084static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6085 if (!isa<ImplicitCastExpr>(Ex))
6086 return false;
6087
6088 Expr *InnerE = Ex->IgnoreParenImpCasts();
6089 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6090 const Type *Source =
6091 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6092 if (Target->isDependentType())
6093 return false;
6094
6095 const BuiltinType *FloatCandidateBT =
6096 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6097 const Type *BoolCandidateType = ToBool ? Target : Source;
6098
6099 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6100 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6101}
6102
6103void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6104 SourceLocation CC) {
6105 unsigned NumArgs = TheCall->getNumArgs();
6106 for (unsigned i = 0; i < NumArgs; ++i) {
6107 Expr *CurrA = TheCall->getArg(i);
6108 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6109 continue;
6110
6111 bool IsSwapped = ((i > 0) &&
6112 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6113 IsSwapped |= ((i < (NumArgs - 1)) &&
6114 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6115 if (IsSwapped) {
6116 // Warn on this floating-point to bool conversion.
6117 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6118 CurrA->getType(), CC,
6119 diag::warn_impcast_floating_point_to_bool);
6120 }
6121 }
6122}
6123
John McCallcc7e5bf2010-05-06 08:58:33 +00006124void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00006125 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006126 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00006127
John McCallcc7e5bf2010-05-06 08:58:33 +00006128 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6129 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6130 if (Source == Target) return;
6131 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00006132
Chandler Carruthc22845a2011-07-26 05:40:03 +00006133 // If the conversion context location is invalid don't complain. We also
6134 // don't want to emit a warning if the issue occurs from the expansion of
6135 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6136 // delay this check as long as possible. Once we detect we are in that
6137 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006138 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00006139 return;
6140
Richard Trieu021baa32011-09-23 20:10:00 +00006141 // Diagnose implicit casts to bool.
6142 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6143 if (isa<StringLiteral>(E))
6144 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00006145 // and expressions, for instance, assert(0 && "error here"), are
6146 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00006147 return DiagnoseImpCast(S, E, T, CC,
6148 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00006149 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6150 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6151 // This covers the literal expressions that evaluate to Objective-C
6152 // objects.
6153 return DiagnoseImpCast(S, E, T, CC,
6154 diag::warn_impcast_objective_c_literal_to_bool);
6155 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006156 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6157 // Warn on pointer to bool conversion that is always true.
6158 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6159 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00006160 }
Richard Trieu021baa32011-09-23 20:10:00 +00006161 }
John McCall263a48b2010-01-04 23:31:57 +00006162
6163 // Strip vector types.
6164 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006165 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006166 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006167 return;
John McCallacf0ee52010-10-08 02:01:28 +00006168 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006169 }
Chris Lattneree7286f2011-06-14 04:51:15 +00006170
6171 // If the vector cast is cast between two vectors of the same size, it is
6172 // a bitcast, not a conversion.
6173 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6174 return;
John McCall263a48b2010-01-04 23:31:57 +00006175
6176 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6177 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6178 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00006179 if (auto VecTy = dyn_cast<VectorType>(Target))
6180 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00006181
6182 // Strip complex types.
6183 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006184 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006185 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006186 return;
6187
John McCallacf0ee52010-10-08 02:01:28 +00006188 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006189 }
John McCall263a48b2010-01-04 23:31:57 +00006190
6191 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6192 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6193 }
6194
6195 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6196 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6197
6198 // If the source is floating point...
6199 if (SourceBT && SourceBT->isFloatingPoint()) {
6200 // ...and the target is floating point...
6201 if (TargetBT && TargetBT->isFloatingPoint()) {
6202 // ...then warn if we're dropping FP rank.
6203
6204 // Builtin FP kinds are ordered by increasing FP rank.
6205 if (SourceBT->getKind() > TargetBT->getKind()) {
6206 // Don't warn about float constants that are precisely
6207 // representable in the target type.
6208 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006209 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00006210 // Value might be a float, a float vector, or a float complex.
6211 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00006212 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6213 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00006214 return;
6215 }
6216
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006217 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006218 return;
6219
John McCallacf0ee52010-10-08 02:01:28 +00006220 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00006221 }
6222 return;
6223 }
6224
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006225 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00006226 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006227 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006228 return;
6229
Chandler Carruth22c7a792011-02-17 11:05:49 +00006230 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00006231 // We also want to warn on, e.g., "int i = -1.234"
6232 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6233 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6234 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6235
Chandler Carruth016ef402011-04-10 08:36:24 +00006236 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6237 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00006238 } else {
6239 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6240 }
6241 }
John McCall263a48b2010-01-04 23:31:57 +00006242
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006243 // If the target is bool, warn if expr is a function or method call.
6244 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6245 isa<CallExpr>(E)) {
6246 // Check last argument of function call to see if it is an
6247 // implicit cast from a type matching the type the result
6248 // is being cast to.
6249 CallExpr *CEx = cast<CallExpr>(E);
6250 unsigned NumArgs = CEx->getNumArgs();
6251 if (NumArgs > 0) {
6252 Expr *LastA = CEx->getArg(NumArgs - 1);
6253 Expr *InnerE = LastA->IgnoreParenImpCasts();
6254 const Type *InnerType =
6255 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6256 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6257 // Warn on this floating-point to bool conversion
6258 DiagnoseImpCast(S, E, T, CC,
6259 diag::warn_impcast_floating_point_to_bool);
6260 }
6261 }
6262 }
John McCall263a48b2010-01-04 23:31:57 +00006263 return;
6264 }
6265
Richard Trieubeaf3452011-05-29 19:59:02 +00006266 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikie9366d2b2012-06-19 21:19:06 +00006267 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiea1edff02012-11-08 00:41:20 +00006268 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikiebcd4b552013-02-16 00:56:22 +00006269 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieae12b182012-03-16 20:30:12 +00006270 SourceLocation Loc = E->getSourceRange().getBegin();
6271 if (Loc.isMacroID())
6272 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie18e9ac72012-05-15 21:57:38 +00006273 if (!Loc.isMacroID() || CC.isMacroID())
6274 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6275 << T << clang::SourceRange(CC)
Richard Smithf7ec86a2013-09-20 00:27:40 +00006276 << FixItHint::CreateReplacement(Loc,
6277 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieubeaf3452011-05-29 19:59:02 +00006278 }
6279
David Blaikie9366d2b2012-06-19 21:19:06 +00006280 if (!Source->isIntegerType() || !Target->isIntegerType())
6281 return;
6282
David Blaikie7555b6a2012-05-15 16:56:36 +00006283 // TODO: remove this early return once the false positives for constant->bool
6284 // in templates, macros, etc, are reduced or removed.
6285 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6286 return;
6287
John McCallcc7e5bf2010-05-06 08:58:33 +00006288 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00006289 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00006290
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006291 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00006292 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006293 // TODO: this should happen for bitfield stores, too.
6294 llvm::APSInt Value(32);
6295 if (E->isIntegerConstantExpr(Value, S.Context)) {
6296 if (S.SourceMgr.isInSystemMacro(CC))
6297 return;
6298
John McCall18a2c2c2010-11-09 22:22:12 +00006299 std::string PrettySourceValue = Value.toString(10);
6300 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006301
Ted Kremenek33ba9952011-10-22 02:37:33 +00006302 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6303 S.PDiag(diag::warn_impcast_integer_precision_constant)
6304 << PrettySourceValue << PrettyTargetValue
6305 << E->getType() << T << E->getSourceRange()
6306 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006307 return;
6308 }
6309
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006310 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6311 if (S.SourceMgr.isInSystemMacro(CC))
6312 return;
6313
David Blaikie9455da02012-04-12 22:40:54 +00006314 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006315 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6316 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006317 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006318 }
6319
6320 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6321 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6322 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006323
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006324 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006325 return;
6326
John McCallcc7e5bf2010-05-06 08:58:33 +00006327 unsigned DiagID = diag::warn_impcast_integer_sign;
6328
6329 // Traditionally, gcc has warned about this under -Wsign-compare.
6330 // We also want to warn about it in -Wconversion.
6331 // So if -Wconversion is off, use a completely identical diagnostic
6332 // in the sign-compare group.
6333 // The conditional-checking code will
6334 if (ICContext) {
6335 DiagID = diag::warn_impcast_integer_sign_conditional;
6336 *ICContext = true;
6337 }
6338
John McCallacf0ee52010-10-08 02:01:28 +00006339 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006340 }
6341
Douglas Gregora78f1932011-02-22 02:45:07 +00006342 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006343 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6344 // type, to give us better diagnostics.
6345 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006346 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006347 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6348 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6349 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6350 SourceType = S.Context.getTypeDeclType(Enum);
6351 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6352 }
6353 }
6354
Douglas Gregora78f1932011-02-22 02:45:07 +00006355 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6356 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006357 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6358 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006359 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006360 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006361 return;
6362
Douglas Gregor364f7db2011-03-12 00:14:31 +00006363 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006364 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006365 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006366
John McCall263a48b2010-01-04 23:31:57 +00006367 return;
6368}
6369
David Blaikie18e9ac72012-05-15 21:57:38 +00006370void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6371 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006372
6373void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006374 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006375 E = E->IgnoreParenImpCasts();
6376
6377 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006378 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006379
John McCallacf0ee52010-10-08 02:01:28 +00006380 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006381 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006382 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006383 return;
6384}
6385
David Blaikie18e9ac72012-05-15 21:57:38 +00006386void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6387 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00006388 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006389
6390 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006391 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6392 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006393
6394 // If -Wconversion would have warned about either of the candidates
6395 // for a signedness conversion to the context type...
6396 if (!Suspicious) return;
6397
6398 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006399 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006400 return;
6401
John McCallcc7e5bf2010-05-06 08:58:33 +00006402 // ...then check whether it would have warned about either of the
6403 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006404 if (E->getType() == T) return;
6405
6406 Suspicious = false;
6407 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6408 E->getType(), CC, &Suspicious);
6409 if (!Suspicious)
6410 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006411 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006412}
6413
6414/// AnalyzeImplicitConversions - Find and report any interesting
6415/// implicit conversions in the given expression. There are a couple
6416/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006417void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006418 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006419 Expr *E = OrigE->IgnoreParenImpCasts();
6420
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006421 if (E->isTypeDependent() || E->isValueDependent())
6422 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006423
John McCallcc7e5bf2010-05-06 08:58:33 +00006424 // For conditional operators, we analyze the arguments as if they
6425 // were being fed directly into the output.
6426 if (isa<ConditionalOperator>(E)) {
6427 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006428 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006429 return;
6430 }
6431
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006432 // Check implicit argument conversions for function calls.
6433 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6434 CheckImplicitArgumentConversions(S, Call, CC);
6435
John McCallcc7e5bf2010-05-06 08:58:33 +00006436 // Go ahead and check any implicit conversions we might have skipped.
6437 // The non-canonical typecheck is just an optimization;
6438 // CheckImplicitConversion will filter out dead implicit conversions.
6439 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006440 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006441
6442 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006443
6444 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006445 if (POE->getResultExpr())
6446 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006447 }
6448
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006449 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6450 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6451
John McCallcc7e5bf2010-05-06 08:58:33 +00006452 // Skip past explicit casts.
6453 if (isa<ExplicitCastExpr>(E)) {
6454 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006455 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006456 }
6457
John McCalld2a53122010-11-09 23:24:47 +00006458 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6459 // Do a somewhat different check with comparison operators.
6460 if (BO->isComparisonOp())
6461 return AnalyzeComparison(S, BO);
6462
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006463 // And with simple assignments.
6464 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006465 return AnalyzeAssignment(S, BO);
6466 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006467
6468 // These break the otherwise-useful invariant below. Fortunately,
6469 // we don't really need to recurse into them, because any internal
6470 // expressions should have been analyzed already when they were
6471 // built into statements.
6472 if (isa<StmtExpr>(E)) return;
6473
6474 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006475 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006476
6477 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006478 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006479 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006480 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006481 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006482 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006483 if (!ChildExpr)
6484 continue;
6485
Richard Trieu955231d2014-01-25 01:10:35 +00006486 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006487 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006488 // Ignore checking string literals that are in logical and operators.
6489 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006490 continue;
6491 AnalyzeImplicitConversions(S, ChildExpr, CC);
6492 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006493}
6494
6495} // end anonymous namespace
6496
Richard Trieu3bb8b562014-02-26 02:36:06 +00006497enum {
6498 AddressOf,
6499 FunctionPointer,
6500 ArrayPointer
6501};
6502
Richard Trieuc1888e02014-06-28 23:25:37 +00006503// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6504// Returns true when emitting a warning about taking the address of a reference.
6505static bool CheckForReference(Sema &SemaRef, const Expr *E,
6506 PartialDiagnostic PD) {
6507 E = E->IgnoreParenImpCasts();
6508
6509 const FunctionDecl *FD = nullptr;
6510
6511 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6512 if (!DRE->getDecl()->getType()->isReferenceType())
6513 return false;
6514 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6515 if (!M->getMemberDecl()->getType()->isReferenceType())
6516 return false;
6517 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
6518 if (!Call->getCallReturnType()->isReferenceType())
6519 return false;
6520 FD = Call->getDirectCallee();
6521 } else {
6522 return false;
6523 }
6524
6525 SemaRef.Diag(E->getExprLoc(), PD);
6526
6527 // If possible, point to location of function.
6528 if (FD) {
6529 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6530 }
6531
6532 return true;
6533}
6534
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006535// Returns true if the SourceLocation is expanded from any macro body.
6536// Returns false if the SourceLocation is invalid, is from not in a macro
6537// expansion, or is from expanded from a top-level macro argument.
6538static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
6539 if (Loc.isInvalid())
6540 return false;
6541
6542 while (Loc.isMacroID()) {
6543 if (SM.isMacroBodyExpansion(Loc))
6544 return true;
6545 Loc = SM.getImmediateMacroCallerLoc(Loc);
6546 }
6547
6548 return false;
6549}
6550
Richard Trieu3bb8b562014-02-26 02:36:06 +00006551/// \brief Diagnose pointers that are always non-null.
6552/// \param E the expression containing the pointer
6553/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6554/// compared to a null pointer
6555/// \param IsEqual True when the comparison is equal to a null pointer
6556/// \param Range Extra SourceRange to highlight in the diagnostic
6557void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6558 Expr::NullPointerConstantKind NullKind,
6559 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00006560 if (!E)
6561 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006562
6563 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006564 if (E->getExprLoc().isMacroID()) {
6565 const SourceManager &SM = getSourceManager();
6566 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
6567 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00006568 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006569 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006570 E = E->IgnoreImpCasts();
6571
6572 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6573
Richard Trieuf7432752014-06-06 21:39:26 +00006574 if (isa<CXXThisExpr>(E)) {
6575 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6576 : diag::warn_this_bool_conversion;
6577 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6578 return;
6579 }
6580
Richard Trieu3bb8b562014-02-26 02:36:06 +00006581 bool IsAddressOf = false;
6582
6583 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6584 if (UO->getOpcode() != UO_AddrOf)
6585 return;
6586 IsAddressOf = true;
6587 E = UO->getSubExpr();
6588 }
6589
Richard Trieuc1888e02014-06-28 23:25:37 +00006590 if (IsAddressOf) {
6591 unsigned DiagID = IsCompare
6592 ? diag::warn_address_of_reference_null_compare
6593 : diag::warn_address_of_reference_bool_conversion;
6594 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6595 << IsEqual;
6596 if (CheckForReference(*this, E, PD)) {
6597 return;
6598 }
6599 }
6600
Richard Trieu3bb8b562014-02-26 02:36:06 +00006601 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00006602 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006603 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6604 D = R->getDecl();
6605 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6606 D = M->getMemberDecl();
6607 }
6608
6609 // Weak Decls can be null.
6610 if (!D || D->isWeak())
6611 return;
6612
6613 QualType T = D->getType();
6614 const bool IsArray = T->isArrayType();
6615 const bool IsFunction = T->isFunctionType();
6616
Richard Trieuc1888e02014-06-28 23:25:37 +00006617 // Address of function is used to silence the function warning.
6618 if (IsAddressOf && IsFunction) {
6619 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006620 }
6621
6622 // Found nothing.
6623 if (!IsAddressOf && !IsFunction && !IsArray)
6624 return;
6625
6626 // Pretty print the expression for the diagnostic.
6627 std::string Str;
6628 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00006629 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00006630
6631 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6632 : diag::warn_impcast_pointer_to_bool;
6633 unsigned DiagType;
6634 if (IsAddressOf)
6635 DiagType = AddressOf;
6636 else if (IsFunction)
6637 DiagType = FunctionPointer;
6638 else if (IsArray)
6639 DiagType = ArrayPointer;
6640 else
6641 llvm_unreachable("Could not determine diagnostic.");
6642 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6643 << Range << IsEqual;
6644
6645 if (!IsFunction)
6646 return;
6647
6648 // Suggest '&' to silence the function warning.
6649 Diag(E->getExprLoc(), diag::note_function_warning_silence)
6650 << FixItHint::CreateInsertion(E->getLocStart(), "&");
6651
6652 // Check to see if '()' fixit should be emitted.
6653 QualType ReturnType;
6654 UnresolvedSet<4> NonTemplateOverloads;
6655 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6656 if (ReturnType.isNull())
6657 return;
6658
6659 if (IsCompare) {
6660 // There are two cases here. If there is null constant, the only suggest
6661 // for a pointer return type. If the null is 0, then suggest if the return
6662 // type is a pointer or an integer type.
6663 if (!ReturnType->isPointerType()) {
6664 if (NullKind == Expr::NPCK_ZeroExpression ||
6665 NullKind == Expr::NPCK_ZeroLiteral) {
6666 if (!ReturnType->isIntegerType())
6667 return;
6668 } else {
6669 return;
6670 }
6671 }
6672 } else { // !IsCompare
6673 // For function to bool, only suggest if the function pointer has bool
6674 // return type.
6675 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6676 return;
6677 }
6678 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006679 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00006680}
6681
6682
John McCallcc7e5bf2010-05-06 08:58:33 +00006683/// Diagnoses "dangerous" implicit conversions within the given
6684/// expression (which is a full expression). Implements -Wconversion
6685/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006686///
6687/// \param CC the "context" location of the implicit conversion, i.e.
6688/// the most location of the syntactic entity requiring the implicit
6689/// conversion
6690void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006691 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00006692 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00006693 return;
6694
6695 // Don't diagnose for value- or type-dependent expressions.
6696 if (E->isTypeDependent() || E->isValueDependent())
6697 return;
6698
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006699 // Check for array bounds violations in cases where the check isn't triggered
6700 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6701 // ArraySubscriptExpr is on the RHS of a variable initialization.
6702 CheckArrayAccess(E);
6703
John McCallacf0ee52010-10-08 02:01:28 +00006704 // This is not the right CC for (e.g.) a variable initialization.
6705 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006706}
6707
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006708/// Diagnose when expression is an integer constant expression and its evaluation
6709/// results in integer overflow
6710void Sema::CheckForIntOverflow (Expr *E) {
Richard Smithe9ff7702013-11-05 22:23:30 +00006711 if (isa<BinaryOperator>(E->IgnoreParens()))
6712 E->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006713}
6714
Richard Smithc406cb72013-01-17 01:17:56 +00006715namespace {
6716/// \brief Visitor for expressions which looks for unsequenced operations on the
6717/// same object.
6718class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006719 typedef EvaluatedExprVisitor<SequenceChecker> Base;
6720
Richard Smithc406cb72013-01-17 01:17:56 +00006721 /// \brief A tree of sequenced regions within an expression. Two regions are
6722 /// unsequenced if one is an ancestor or a descendent of the other. When we
6723 /// finish processing an expression with sequencing, such as a comma
6724 /// expression, we fold its tree nodes into its parent, since they are
6725 /// unsequenced with respect to nodes we will visit later.
6726 class SequenceTree {
6727 struct Value {
6728 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6729 unsigned Parent : 31;
6730 bool Merged : 1;
6731 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006732 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00006733
6734 public:
6735 /// \brief A region within an expression which may be sequenced with respect
6736 /// to some other region.
6737 class Seq {
6738 explicit Seq(unsigned N) : Index(N) {}
6739 unsigned Index;
6740 friend class SequenceTree;
6741 public:
6742 Seq() : Index(0) {}
6743 };
6744
6745 SequenceTree() { Values.push_back(Value(0)); }
6746 Seq root() const { return Seq(0); }
6747
6748 /// \brief Create a new sequence of operations, which is an unsequenced
6749 /// subset of \p Parent. This sequence of operations is sequenced with
6750 /// respect to other children of \p Parent.
6751 Seq allocate(Seq Parent) {
6752 Values.push_back(Value(Parent.Index));
6753 return Seq(Values.size() - 1);
6754 }
6755
6756 /// \brief Merge a sequence of operations into its parent.
6757 void merge(Seq S) {
6758 Values[S.Index].Merged = true;
6759 }
6760
6761 /// \brief Determine whether two operations are unsequenced. This operation
6762 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
6763 /// should have been merged into its parent as appropriate.
6764 bool isUnsequenced(Seq Cur, Seq Old) {
6765 unsigned C = representative(Cur.Index);
6766 unsigned Target = representative(Old.Index);
6767 while (C >= Target) {
6768 if (C == Target)
6769 return true;
6770 C = Values[C].Parent;
6771 }
6772 return false;
6773 }
6774
6775 private:
6776 /// \brief Pick a representative for a sequence.
6777 unsigned representative(unsigned K) {
6778 if (Values[K].Merged)
6779 // Perform path compression as we go.
6780 return Values[K].Parent = representative(Values[K].Parent);
6781 return K;
6782 }
6783 };
6784
6785 /// An object for which we can track unsequenced uses.
6786 typedef NamedDecl *Object;
6787
6788 /// Different flavors of object usage which we track. We only track the
6789 /// least-sequenced usage of each kind.
6790 enum UsageKind {
6791 /// A read of an object. Multiple unsequenced reads are OK.
6792 UK_Use,
6793 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00006794 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00006795 UK_ModAsValue,
6796 /// A modification of an object which is not sequenced before the value
6797 /// computation of the expression, such as n++.
6798 UK_ModAsSideEffect,
6799
6800 UK_Count = UK_ModAsSideEffect + 1
6801 };
6802
6803 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00006804 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00006805 Expr *Use;
6806 SequenceTree::Seq Seq;
6807 };
6808
6809 struct UsageInfo {
6810 UsageInfo() : Diagnosed(false) {}
6811 Usage Uses[UK_Count];
6812 /// Have we issued a diagnostic for this variable already?
6813 bool Diagnosed;
6814 };
6815 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
6816
6817 Sema &SemaRef;
6818 /// Sequenced regions within the expression.
6819 SequenceTree Tree;
6820 /// Declaration modifications and references which we have seen.
6821 UsageInfoMap UsageMap;
6822 /// The region we are currently within.
6823 SequenceTree::Seq Region;
6824 /// Filled in with declarations which were modified as a side-effect
6825 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006826 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00006827 /// Expressions to check later. We defer checking these to reduce
6828 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006829 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00006830
6831 /// RAII object wrapping the visitation of a sequenced subexpression of an
6832 /// expression. At the end of this process, the side-effects of the evaluation
6833 /// become sequenced with respect to the value computation of the result, so
6834 /// we downgrade any UK_ModAsSideEffect within the evaluation to
6835 /// UK_ModAsValue.
6836 struct SequencedSubexpression {
6837 SequencedSubexpression(SequenceChecker &Self)
6838 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
6839 Self.ModAsSideEffect = &ModAsSideEffect;
6840 }
6841 ~SequencedSubexpression() {
6842 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
6843 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
6844 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
6845 Self.addUsage(U, ModAsSideEffect[I].first,
6846 ModAsSideEffect[I].second.Use, UK_ModAsValue);
6847 }
6848 Self.ModAsSideEffect = OldModAsSideEffect;
6849 }
6850
6851 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006852 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
6853 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00006854 };
6855
Richard Smith40238f02013-06-20 22:21:56 +00006856 /// RAII object wrapping the visitation of a subexpression which we might
6857 /// choose to evaluate as a constant. If any subexpression is evaluated and
6858 /// found to be non-constant, this allows us to suppress the evaluation of
6859 /// the outer expression.
6860 class EvaluationTracker {
6861 public:
6862 EvaluationTracker(SequenceChecker &Self)
6863 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
6864 Self.EvalTracker = this;
6865 }
6866 ~EvaluationTracker() {
6867 Self.EvalTracker = Prev;
6868 if (Prev)
6869 Prev->EvalOK &= EvalOK;
6870 }
6871
6872 bool evaluate(const Expr *E, bool &Result) {
6873 if (!EvalOK || E->isValueDependent())
6874 return false;
6875 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
6876 return EvalOK;
6877 }
6878
6879 private:
6880 SequenceChecker &Self;
6881 EvaluationTracker *Prev;
6882 bool EvalOK;
6883 } *EvalTracker;
6884
Richard Smithc406cb72013-01-17 01:17:56 +00006885 /// \brief Find the object which is produced by the specified expression,
6886 /// if any.
6887 Object getObject(Expr *E, bool Mod) const {
6888 E = E->IgnoreParenCasts();
6889 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6890 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
6891 return getObject(UO->getSubExpr(), Mod);
6892 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6893 if (BO->getOpcode() == BO_Comma)
6894 return getObject(BO->getRHS(), Mod);
6895 if (Mod && BO->isAssignmentOp())
6896 return getObject(BO->getLHS(), Mod);
6897 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6898 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
6899 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
6900 return ME->getMemberDecl();
6901 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6902 // FIXME: If this is a reference, map through to its value.
6903 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00006904 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00006905 }
6906
6907 /// \brief Note that an object was modified or used by an expression.
6908 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
6909 Usage &U = UI.Uses[UK];
6910 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
6911 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
6912 ModAsSideEffect->push_back(std::make_pair(O, U));
6913 U.Use = Ref;
6914 U.Seq = Region;
6915 }
6916 }
6917 /// \brief Check whether a modification or use conflicts with a prior usage.
6918 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
6919 bool IsModMod) {
6920 if (UI.Diagnosed)
6921 return;
6922
6923 const Usage &U = UI.Uses[OtherKind];
6924 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
6925 return;
6926
6927 Expr *Mod = U.Use;
6928 Expr *ModOrUse = Ref;
6929 if (OtherKind == UK_Use)
6930 std::swap(Mod, ModOrUse);
6931
6932 SemaRef.Diag(Mod->getExprLoc(),
6933 IsModMod ? diag::warn_unsequenced_mod_mod
6934 : diag::warn_unsequenced_mod_use)
6935 << O << SourceRange(ModOrUse->getExprLoc());
6936 UI.Diagnosed = true;
6937 }
6938
6939 void notePreUse(Object O, Expr *Use) {
6940 UsageInfo &U = UsageMap[O];
6941 // Uses conflict with other modifications.
6942 checkUsage(O, U, Use, UK_ModAsValue, false);
6943 }
6944 void notePostUse(Object O, Expr *Use) {
6945 UsageInfo &U = UsageMap[O];
6946 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
6947 addUsage(U, O, Use, UK_Use);
6948 }
6949
6950 void notePreMod(Object O, Expr *Mod) {
6951 UsageInfo &U = UsageMap[O];
6952 // Modifications conflict with other modifications and with uses.
6953 checkUsage(O, U, Mod, UK_ModAsValue, true);
6954 checkUsage(O, U, Mod, UK_Use, false);
6955 }
6956 void notePostMod(Object O, Expr *Use, UsageKind UK) {
6957 UsageInfo &U = UsageMap[O];
6958 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
6959 addUsage(U, O, Use, UK);
6960 }
6961
6962public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006963 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00006964 : Base(S.Context), SemaRef(S), Region(Tree.root()),
6965 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006966 Visit(E);
6967 }
6968
6969 void VisitStmt(Stmt *S) {
6970 // Skip all statements which aren't expressions for now.
6971 }
6972
6973 void VisitExpr(Expr *E) {
6974 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00006975 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006976 }
6977
6978 void VisitCastExpr(CastExpr *E) {
6979 Object O = Object();
6980 if (E->getCastKind() == CK_LValueToRValue)
6981 O = getObject(E->getSubExpr(), false);
6982
6983 if (O)
6984 notePreUse(O, E);
6985 VisitExpr(E);
6986 if (O)
6987 notePostUse(O, E);
6988 }
6989
6990 void VisitBinComma(BinaryOperator *BO) {
6991 // C++11 [expr.comma]p1:
6992 // Every value computation and side effect associated with the left
6993 // expression is sequenced before every value computation and side
6994 // effect associated with the right expression.
6995 SequenceTree::Seq LHS = Tree.allocate(Region);
6996 SequenceTree::Seq RHS = Tree.allocate(Region);
6997 SequenceTree::Seq OldRegion = Region;
6998
6999 {
7000 SequencedSubexpression SeqLHS(*this);
7001 Region = LHS;
7002 Visit(BO->getLHS());
7003 }
7004
7005 Region = RHS;
7006 Visit(BO->getRHS());
7007
7008 Region = OldRegion;
7009
7010 // Forget that LHS and RHS are sequenced. They are both unsequenced
7011 // with respect to other stuff.
7012 Tree.merge(LHS);
7013 Tree.merge(RHS);
7014 }
7015
7016 void VisitBinAssign(BinaryOperator *BO) {
7017 // The modification is sequenced after the value computation of the LHS
7018 // and RHS, so check it before inspecting the operands and update the
7019 // map afterwards.
7020 Object O = getObject(BO->getLHS(), true);
7021 if (!O)
7022 return VisitExpr(BO);
7023
7024 notePreMod(O, BO);
7025
7026 // C++11 [expr.ass]p7:
7027 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7028 // only once.
7029 //
7030 // Therefore, for a compound assignment operator, O is considered used
7031 // everywhere except within the evaluation of E1 itself.
7032 if (isa<CompoundAssignOperator>(BO))
7033 notePreUse(O, BO);
7034
7035 Visit(BO->getLHS());
7036
7037 if (isa<CompoundAssignOperator>(BO))
7038 notePostUse(O, BO);
7039
7040 Visit(BO->getRHS());
7041
Richard Smith83e37bee2013-06-26 23:16:51 +00007042 // C++11 [expr.ass]p1:
7043 // the assignment is sequenced [...] before the value computation of the
7044 // assignment expression.
7045 // C11 6.5.16/3 has no such rule.
7046 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7047 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007048 }
7049 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7050 VisitBinAssign(CAO);
7051 }
7052
7053 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7054 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7055 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7056 Object O = getObject(UO->getSubExpr(), true);
7057 if (!O)
7058 return VisitExpr(UO);
7059
7060 notePreMod(O, UO);
7061 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00007062 // C++11 [expr.pre.incr]p1:
7063 // the expression ++x is equivalent to x+=1
7064 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7065 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007066 }
7067
7068 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7069 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7070 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7071 Object O = getObject(UO->getSubExpr(), true);
7072 if (!O)
7073 return VisitExpr(UO);
7074
7075 notePreMod(O, UO);
7076 Visit(UO->getSubExpr());
7077 notePostMod(O, UO, UK_ModAsSideEffect);
7078 }
7079
7080 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7081 void VisitBinLOr(BinaryOperator *BO) {
7082 // The side-effects of the LHS of an '&&' are sequenced before the
7083 // value computation of the RHS, and hence before the value computation
7084 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7085 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00007086 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007087 {
7088 SequencedSubexpression Sequenced(*this);
7089 Visit(BO->getLHS());
7090 }
7091
7092 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007093 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007094 if (!Result)
7095 Visit(BO->getRHS());
7096 } else {
7097 // Check for unsequenced operations in the RHS, treating it as an
7098 // entirely separate evaluation.
7099 //
7100 // FIXME: If there are operations in the RHS which are unsequenced
7101 // with respect to operations outside the RHS, and those operations
7102 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00007103 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007104 }
Richard Smithc406cb72013-01-17 01:17:56 +00007105 }
7106 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00007107 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007108 {
7109 SequencedSubexpression Sequenced(*this);
7110 Visit(BO->getLHS());
7111 }
7112
7113 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007114 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007115 if (Result)
7116 Visit(BO->getRHS());
7117 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00007118 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007119 }
Richard Smithc406cb72013-01-17 01:17:56 +00007120 }
7121
7122 // Only visit the condition, unless we can be sure which subexpression will
7123 // be chosen.
7124 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00007125 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00007126 {
7127 SequencedSubexpression Sequenced(*this);
7128 Visit(CO->getCond());
7129 }
Richard Smithc406cb72013-01-17 01:17:56 +00007130
7131 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007132 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00007133 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007134 else {
Richard Smithd33f5202013-01-17 23:18:09 +00007135 WorkList.push_back(CO->getTrueExpr());
7136 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007137 }
Richard Smithc406cb72013-01-17 01:17:56 +00007138 }
7139
Richard Smithe3dbfe02013-06-30 10:40:20 +00007140 void VisitCallExpr(CallExpr *CE) {
7141 // C++11 [intro.execution]p15:
7142 // When calling a function [...], every value computation and side effect
7143 // associated with any argument expression, or with the postfix expression
7144 // designating the called function, is sequenced before execution of every
7145 // expression or statement in the body of the function [and thus before
7146 // the value computation of its result].
7147 SequencedSubexpression Sequenced(*this);
7148 Base::VisitCallExpr(CE);
7149
7150 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7151 }
7152
Richard Smithc406cb72013-01-17 01:17:56 +00007153 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007154 // This is a call, so all subexpressions are sequenced before the result.
7155 SequencedSubexpression Sequenced(*this);
7156
Richard Smithc406cb72013-01-17 01:17:56 +00007157 if (!CCE->isListInitialization())
7158 return VisitExpr(CCE);
7159
7160 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007161 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007162 SequenceTree::Seq Parent = Region;
7163 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7164 E = CCE->arg_end();
7165 I != E; ++I) {
7166 Region = Tree.allocate(Parent);
7167 Elts.push_back(Region);
7168 Visit(*I);
7169 }
7170
7171 // Forget that the initializers are sequenced.
7172 Region = Parent;
7173 for (unsigned I = 0; I < Elts.size(); ++I)
7174 Tree.merge(Elts[I]);
7175 }
7176
7177 void VisitInitListExpr(InitListExpr *ILE) {
7178 if (!SemaRef.getLangOpts().CPlusPlus11)
7179 return VisitExpr(ILE);
7180
7181 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007182 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007183 SequenceTree::Seq Parent = Region;
7184 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7185 Expr *E = ILE->getInit(I);
7186 if (!E) continue;
7187 Region = Tree.allocate(Parent);
7188 Elts.push_back(Region);
7189 Visit(E);
7190 }
7191
7192 // Forget that the initializers are sequenced.
7193 Region = Parent;
7194 for (unsigned I = 0; I < Elts.size(); ++I)
7195 Tree.merge(Elts[I]);
7196 }
7197};
7198}
7199
7200void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007201 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00007202 WorkList.push_back(E);
7203 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00007204 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00007205 SequenceChecker(*this, Item, WorkList);
7206 }
Richard Smithc406cb72013-01-17 01:17:56 +00007207}
7208
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007209void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7210 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007211 CheckImplicitConversions(E, CheckLoc);
7212 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007213 if (!IsConstexpr && !E->isValueDependent())
7214 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007215}
7216
John McCall1f425642010-11-11 03:21:53 +00007217void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7218 FieldDecl *BitField,
7219 Expr *Init) {
7220 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7221}
7222
Mike Stump0c2ec772010-01-21 03:59:47 +00007223/// CheckParmsForFunctionDef - Check that the parameters of the given
7224/// function are appropriate for the definition of a function. This
7225/// takes care of any checks that cannot be performed on the
7226/// declaration itself, e.g., that the types of each of the function
7227/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00007228bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7229 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00007230 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007231 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00007232 for (; P != PEnd; ++P) {
7233 ParmVarDecl *Param = *P;
7234
Mike Stump0c2ec772010-01-21 03:59:47 +00007235 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7236 // function declarator that is part of a function definition of
7237 // that function shall not have incomplete type.
7238 //
7239 // This is also C++ [dcl.fct]p6.
7240 if (!Param->isInvalidDecl() &&
7241 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007242 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007243 Param->setInvalidDecl();
7244 HasInvalidParm = true;
7245 }
7246
7247 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7248 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00007249 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00007250 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00007251 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007252 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00007253 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00007254
7255 // C99 6.7.5.3p12:
7256 // If the function declarator is not part of a definition of that
7257 // function, parameters may have incomplete type and may use the [*]
7258 // notation in their sequences of declarator specifiers to specify
7259 // variable length array types.
7260 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007261 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00007262 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00007263 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00007264 // information is added for it.
7265 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007266 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00007267 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007268 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00007269 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007270
7271 // MSVC destroys objects passed by value in the callee. Therefore a
7272 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007273 // object's destructor. However, we don't perform any direct access check
7274 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00007275 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7276 .getCXXABI()
7277 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00007278 if (!Param->isInvalidDecl()) {
7279 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7280 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7281 if (!ClassDecl->isInvalidDecl() &&
7282 !ClassDecl->hasIrrelevantDestructor() &&
7283 !ClassDecl->isDependentContext()) {
7284 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7285 MarkFunctionReferenced(Param->getLocation(), Destructor);
7286 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7287 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007288 }
7289 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007290 }
Mike Stump0c2ec772010-01-21 03:59:47 +00007291 }
7292
7293 return HasInvalidParm;
7294}
John McCall2b5c1b22010-08-12 21:44:57 +00007295
7296/// CheckCastAlign - Implements -Wcast-align, which warns when a
7297/// pointer cast increases the alignment requirements.
7298void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7299 // This is actually a lot of work to potentially be doing on every
7300 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007301 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00007302 return;
7303
7304 // Ignore dependent types.
7305 if (T->isDependentType() || Op->getType()->isDependentType())
7306 return;
7307
7308 // Require that the destination be a pointer type.
7309 const PointerType *DestPtr = T->getAs<PointerType>();
7310 if (!DestPtr) return;
7311
7312 // If the destination has alignment 1, we're done.
7313 QualType DestPointee = DestPtr->getPointeeType();
7314 if (DestPointee->isIncompleteType()) return;
7315 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7316 if (DestAlign.isOne()) return;
7317
7318 // Require that the source be a pointer type.
7319 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7320 if (!SrcPtr) return;
7321 QualType SrcPointee = SrcPtr->getPointeeType();
7322
7323 // Whitelist casts from cv void*. We already implicitly
7324 // whitelisted casts to cv void*, since they have alignment 1.
7325 // Also whitelist casts involving incomplete types, which implicitly
7326 // includes 'void'.
7327 if (SrcPointee->isIncompleteType()) return;
7328
7329 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7330 if (SrcAlign >= DestAlign) return;
7331
7332 Diag(TRange.getBegin(), diag::warn_cast_align)
7333 << Op->getType() << T
7334 << static_cast<unsigned>(SrcAlign.getQuantity())
7335 << static_cast<unsigned>(DestAlign.getQuantity())
7336 << TRange << Op->getSourceRange();
7337}
7338
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007339static const Type* getElementType(const Expr *BaseExpr) {
7340 const Type* EltType = BaseExpr->getType().getTypePtr();
7341 if (EltType->isAnyPointerType())
7342 return EltType->getPointeeType().getTypePtr();
7343 else if (EltType->isArrayType())
7344 return EltType->getBaseElementTypeUnsafe();
7345 return EltType;
7346}
7347
Chandler Carruth28389f02011-08-05 09:10:50 +00007348/// \brief Check whether this array fits the idiom of a size-one tail padded
7349/// array member of a struct.
7350///
7351/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7352/// commonly used to emulate flexible arrays in C89 code.
7353static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7354 const NamedDecl *ND) {
7355 if (Size != 1 || !ND) return false;
7356
7357 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7358 if (!FD) return false;
7359
7360 // Don't consider sizes resulting from macro expansions or template argument
7361 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00007362
7363 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007364 while (TInfo) {
7365 TypeLoc TL = TInfo->getTypeLoc();
7366 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007367 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7368 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007369 TInfo = TDL->getTypeSourceInfo();
7370 continue;
7371 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007372 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7373 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007374 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7375 return false;
7376 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007377 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007378 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007379
7380 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007381 if (!RD) return false;
7382 if (RD->isUnion()) return false;
7383 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7384 if (!CRD->isStandardLayout()) return false;
7385 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007386
Benjamin Kramer8c543672011-08-06 03:04:42 +00007387 // See if this is the last field decl in the record.
7388 const Decl *D = FD;
7389 while ((D = D->getNextDeclInContext()))
7390 if (isa<FieldDecl>(D))
7391 return false;
7392 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007393}
7394
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007395void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007396 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007397 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007398 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007399 if (IndexExpr->isValueDependent())
7400 return;
7401
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007402 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007403 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007404 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007405 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007406 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007407 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007408
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007409 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007410 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007411 return;
Richard Smith13f67182011-12-16 19:31:14 +00007412 if (IndexNegated)
7413 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007414
Craig Topperc3ec1492014-05-26 06:22:03 +00007415 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007416 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7417 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007418 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007419 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007420
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007421 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007422 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007423 if (!size.isStrictlyPositive())
7424 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007425
7426 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007427 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007428 // Make sure we're comparing apples to apples when comparing index to size
7429 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7430 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007431 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007432 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007433 if (ptrarith_typesize != array_typesize) {
7434 // There's a cast to a different size type involved
7435 uint64_t ratio = array_typesize / ptrarith_typesize;
7436 // TODO: Be smarter about handling cases where array_typesize is not a
7437 // multiple of ptrarith_typesize
7438 if (ptrarith_typesize * ratio == array_typesize)
7439 size *= llvm::APInt(size.getBitWidth(), ratio);
7440 }
7441 }
7442
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007443 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007444 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007445 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007446 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007447
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007448 // For array subscripting the index must be less than size, but for pointer
7449 // arithmetic also allow the index (offset) to be equal to size since
7450 // computing the next address after the end of the array is legal and
7451 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007452 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007453 return;
7454
7455 // Also don't warn for arrays of size 1 which are members of some
7456 // structure. These are often used to approximate flexible arrays in C89
7457 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007458 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007459 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007460
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007461 // Suppress the warning if the subscript expression (as identified by the
7462 // ']' location) and the index expression are both from macro expansions
7463 // within a system header.
7464 if (ASE) {
7465 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7466 ASE->getRBracketLoc());
7467 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7468 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7469 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007470 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007471 return;
7472 }
7473 }
7474
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007475 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007476 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007477 DiagID = diag::warn_array_index_exceeds_bounds;
7478
7479 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7480 PDiag(DiagID) << index.toString(10, true)
7481 << size.toString(10, true)
7482 << (unsigned)size.getLimitedValue(~0U)
7483 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007484 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007485 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007486 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007487 DiagID = diag::warn_ptr_arith_precedes_bounds;
7488 if (index.isNegative()) index = -index;
7489 }
7490
7491 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7492 PDiag(DiagID) << index.toString(10, true)
7493 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007494 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007495
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007496 if (!ND) {
7497 // Try harder to find a NamedDecl to point at in the note.
7498 while (const ArraySubscriptExpr *ASE =
7499 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7500 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7501 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7502 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7503 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7504 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7505 }
7506
Chandler Carruth1af88f12011-02-17 21:10:52 +00007507 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007508 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7509 PDiag(diag::note_array_index_out_of_bounds)
7510 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007511}
7512
Ted Kremenekdf26df72011-03-01 18:41:00 +00007513void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007514 int AllowOnePastEnd = 0;
7515 while (expr) {
7516 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007517 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007518 case Stmt::ArraySubscriptExprClass: {
7519 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007520 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007521 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007522 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007523 }
7524 case Stmt::UnaryOperatorClass: {
7525 // Only unwrap the * and & unary operators
7526 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7527 expr = UO->getSubExpr();
7528 switch (UO->getOpcode()) {
7529 case UO_AddrOf:
7530 AllowOnePastEnd++;
7531 break;
7532 case UO_Deref:
7533 AllowOnePastEnd--;
7534 break;
7535 default:
7536 return;
7537 }
7538 break;
7539 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007540 case Stmt::ConditionalOperatorClass: {
7541 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7542 if (const Expr *lhs = cond->getLHS())
7543 CheckArrayAccess(lhs);
7544 if (const Expr *rhs = cond->getRHS())
7545 CheckArrayAccess(rhs);
7546 return;
7547 }
7548 default:
7549 return;
7550 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007551 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007552}
John McCall31168b02011-06-15 23:02:42 +00007553
7554//===--- CHECK: Objective-C retain cycles ----------------------------------//
7555
7556namespace {
7557 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00007558 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00007559 VarDecl *Variable;
7560 SourceRange Range;
7561 SourceLocation Loc;
7562 bool Indirect;
7563
7564 void setLocsFrom(Expr *e) {
7565 Loc = e->getExprLoc();
7566 Range = e->getSourceRange();
7567 }
7568 };
7569}
7570
7571/// Consider whether capturing the given variable can possibly lead to
7572/// a retain cycle.
7573static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007574 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007575 // lifetime. In MRR, it's captured strongly if the variable is
7576 // __block and has an appropriate type.
7577 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7578 return false;
7579
7580 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007581 if (ref)
7582 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007583 return true;
7584}
7585
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007586static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007587 while (true) {
7588 e = e->IgnoreParens();
7589 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7590 switch (cast->getCastKind()) {
7591 case CK_BitCast:
7592 case CK_LValueBitCast:
7593 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007594 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007595 e = cast->getSubExpr();
7596 continue;
7597
John McCall31168b02011-06-15 23:02:42 +00007598 default:
7599 return false;
7600 }
7601 }
7602
7603 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7604 ObjCIvarDecl *ivar = ref->getDecl();
7605 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7606 return false;
7607
7608 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007609 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00007610 return false;
7611
7612 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7613 owner.Indirect = true;
7614 return true;
7615 }
7616
7617 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7618 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7619 if (!var) return false;
7620 return considerVariable(var, ref, owner);
7621 }
7622
John McCall31168b02011-06-15 23:02:42 +00007623 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7624 if (member->isArrow()) return false;
7625
7626 // Don't count this as an indirect ownership.
7627 e = member->getBase();
7628 continue;
7629 }
7630
John McCallfe96e0b2011-11-06 09:01:30 +00007631 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7632 // Only pay attention to pseudo-objects on property references.
7633 ObjCPropertyRefExpr *pre
7634 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7635 ->IgnoreParens());
7636 if (!pre) return false;
7637 if (pre->isImplicitProperty()) return false;
7638 ObjCPropertyDecl *property = pre->getExplicitProperty();
7639 if (!property->isRetaining() &&
7640 !(property->getPropertyIvarDecl() &&
7641 property->getPropertyIvarDecl()->getType()
7642 .getObjCLifetime() == Qualifiers::OCL_Strong))
7643 return false;
7644
7645 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007646 if (pre->isSuperReceiver()) {
7647 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7648 if (!owner.Variable)
7649 return false;
7650 owner.Loc = pre->getLocation();
7651 owner.Range = pre->getSourceRange();
7652 return true;
7653 }
John McCallfe96e0b2011-11-06 09:01:30 +00007654 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7655 ->getSourceExpr());
7656 continue;
7657 }
7658
John McCall31168b02011-06-15 23:02:42 +00007659 // Array ivars?
7660
7661 return false;
7662 }
7663}
7664
7665namespace {
7666 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7667 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7668 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007669 Context(Context), Variable(variable), Capturer(nullptr),
7670 VarWillBeReased(false) {}
7671 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00007672 VarDecl *Variable;
7673 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007674 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00007675
7676 void VisitDeclRefExpr(DeclRefExpr *ref) {
7677 if (ref->getDecl() == Variable && !Capturer)
7678 Capturer = ref;
7679 }
7680
John McCall31168b02011-06-15 23:02:42 +00007681 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7682 if (Capturer) return;
7683 Visit(ref->getBase());
7684 if (Capturer && ref->isFreeIvar())
7685 Capturer = ref;
7686 }
7687
7688 void VisitBlockExpr(BlockExpr *block) {
7689 // Look inside nested blocks
7690 if (block->getBlockDecl()->capturesVariable(Variable))
7691 Visit(block->getBlockDecl()->getBody());
7692 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00007693
7694 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7695 if (Capturer) return;
7696 if (OVE->getSourceExpr())
7697 Visit(OVE->getSourceExpr());
7698 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007699 void VisitBinaryOperator(BinaryOperator *BinOp) {
7700 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
7701 return;
7702 Expr *LHS = BinOp->getLHS();
7703 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
7704 if (DRE->getDecl() != Variable)
7705 return;
7706 if (Expr *RHS = BinOp->getRHS()) {
7707 RHS = RHS->IgnoreParenCasts();
7708 llvm::APSInt Value;
7709 VarWillBeReased =
7710 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
7711 }
7712 }
7713 }
John McCall31168b02011-06-15 23:02:42 +00007714 };
7715}
7716
7717/// Check whether the given argument is a block which captures a
7718/// variable.
7719static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7720 assert(owner.Variable && owner.Loc.isValid());
7721
7722 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00007723
7724 // Look through [^{...} copy] and Block_copy(^{...}).
7725 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7726 Selector Cmd = ME->getSelector();
7727 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7728 e = ME->getInstanceReceiver();
7729 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00007730 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00007731 e = e->IgnoreParenCasts();
7732 }
7733 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7734 if (CE->getNumArgs() == 1) {
7735 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00007736 if (Fn) {
7737 const IdentifierInfo *FnI = Fn->getIdentifier();
7738 if (FnI && FnI->isStr("_Block_copy")) {
7739 e = CE->getArg(0)->IgnoreParenCasts();
7740 }
7741 }
Jordan Rose67e887c2012-09-17 17:54:30 +00007742 }
7743 }
7744
John McCall31168b02011-06-15 23:02:42 +00007745 BlockExpr *block = dyn_cast<BlockExpr>(e);
7746 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00007747 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00007748
7749 FindCaptureVisitor visitor(S.Context, owner.Variable);
7750 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007751 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00007752}
7753
7754static void diagnoseRetainCycle(Sema &S, Expr *capturer,
7755 RetainCycleOwner &owner) {
7756 assert(capturer);
7757 assert(owner.Variable && owner.Loc.isValid());
7758
7759 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
7760 << owner.Variable << capturer->getSourceRange();
7761 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
7762 << owner.Indirect << owner.Range;
7763}
7764
7765/// Check for a keyword selector that starts with the word 'add' or
7766/// 'set'.
7767static bool isSetterLikeSelector(Selector sel) {
7768 if (sel.isUnarySelector()) return false;
7769
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007770 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00007771 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007772 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00007773 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007774 else if (str.startswith("add")) {
7775 // Specially whitelist 'addOperationWithBlock:'.
7776 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
7777 return false;
7778 str = str.substr(3);
7779 }
John McCall31168b02011-06-15 23:02:42 +00007780 else
7781 return false;
7782
7783 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00007784 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00007785}
7786
7787/// Check a message send to see if it's likely to cause a retain cycle.
7788void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
7789 // Only check instance methods whose selector looks like a setter.
7790 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
7791 return;
7792
7793 // Try to find a variable that the receiver is strongly owned by.
7794 RetainCycleOwner owner;
7795 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007796 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00007797 return;
7798 } else {
7799 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
7800 owner.Variable = getCurMethodDecl()->getSelfDecl();
7801 owner.Loc = msg->getSuperLoc();
7802 owner.Range = msg->getSuperLoc();
7803 }
7804
7805 // Check whether the receiver is captured by any of the arguments.
7806 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
7807 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
7808 return diagnoseRetainCycle(*this, capturer, owner);
7809}
7810
7811/// Check a property assign to see if it's likely to cause a retain cycle.
7812void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
7813 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007814 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00007815 return;
7816
7817 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
7818 diagnoseRetainCycle(*this, capturer, owner);
7819}
7820
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007821void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
7822 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00007823 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007824 return;
7825
7826 // Because we don't have an expression for the variable, we have to set the
7827 // location explicitly here.
7828 Owner.Loc = Var->getLocation();
7829 Owner.Range = Var->getSourceRange();
7830
7831 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
7832 diagnoseRetainCycle(*this, Capturer, Owner);
7833}
7834
Ted Kremenek9304da92012-12-21 08:04:28 +00007835static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
7836 Expr *RHS, bool isProperty) {
7837 // Check if RHS is an Objective-C object literal, which also can get
7838 // immediately zapped in a weak reference. Note that we explicitly
7839 // allow ObjCStringLiterals, since those are designed to never really die.
7840 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007841
Ted Kremenek64873352012-12-21 22:46:35 +00007842 // This enum needs to match with the 'select' in
7843 // warn_objc_arc_literal_assign (off-by-1).
7844 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
7845 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
7846 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007847
7848 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00007849 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00007850 << (isProperty ? 0 : 1)
7851 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007852
7853 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00007854}
7855
Ted Kremenekc1f014a2012-12-21 19:45:30 +00007856static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
7857 Qualifiers::ObjCLifetime LT,
7858 Expr *RHS, bool isProperty) {
7859 // Strip off any implicit cast added to get to the one ARC-specific.
7860 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7861 if (cast->getCastKind() == CK_ARCConsumeObject) {
7862 S.Diag(Loc, diag::warn_arc_retained_assign)
7863 << (LT == Qualifiers::OCL_ExplicitNone)
7864 << (isProperty ? 0 : 1)
7865 << RHS->getSourceRange();
7866 return true;
7867 }
7868 RHS = cast->getSubExpr();
7869 }
7870
7871 if (LT == Qualifiers::OCL_Weak &&
7872 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
7873 return true;
7874
7875 return false;
7876}
7877
Ted Kremenekb36234d2012-12-21 08:04:20 +00007878bool Sema::checkUnsafeAssigns(SourceLocation Loc,
7879 QualType LHS, Expr *RHS) {
7880 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
7881
7882 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
7883 return false;
7884
7885 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
7886 return true;
7887
7888 return false;
7889}
7890
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007891void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
7892 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007893 QualType LHSType;
7894 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00007895 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007896 ObjCPropertyRefExpr *PRE
7897 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
7898 if (PRE && !PRE->isImplicitProperty()) {
7899 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7900 if (PD)
7901 LHSType = PD->getType();
7902 }
7903
7904 if (LHSType.isNull())
7905 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00007906
7907 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
7908
7909 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007910 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00007911 getCurFunction()->markSafeWeakUse(LHS);
7912 }
7913
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007914 if (checkUnsafeAssigns(Loc, LHSType, RHS))
7915 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00007916
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007917 // FIXME. Check for other life times.
7918 if (LT != Qualifiers::OCL_None)
7919 return;
7920
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007921 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007922 if (PRE->isImplicitProperty())
7923 return;
7924 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7925 if (!PD)
7926 return;
7927
Bill Wendling44426052012-12-20 19:22:21 +00007928 unsigned Attributes = PD->getPropertyAttributes();
7929 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007930 // when 'assign' attribute was not explicitly specified
7931 // by user, ignore it and rely on property type itself
7932 // for lifetime info.
7933 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
7934 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
7935 LHSType->isObjCRetainableType())
7936 return;
7937
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007938 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00007939 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007940 Diag(Loc, diag::warn_arc_retained_property_assign)
7941 << RHS->getSourceRange();
7942 return;
7943 }
7944 RHS = cast->getSubExpr();
7945 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007946 }
Bill Wendling44426052012-12-20 19:22:21 +00007947 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00007948 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
7949 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00007950 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007951 }
7952}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00007953
7954//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
7955
7956namespace {
7957bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
7958 SourceLocation StmtLoc,
7959 const NullStmt *Body) {
7960 // Do not warn if the body is a macro that expands to nothing, e.g:
7961 //
7962 // #define CALL(x)
7963 // if (condition)
7964 // CALL(0);
7965 //
7966 if (Body->hasLeadingEmptyMacro())
7967 return false;
7968
7969 // Get line numbers of statement and body.
7970 bool StmtLineInvalid;
7971 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
7972 &StmtLineInvalid);
7973 if (StmtLineInvalid)
7974 return false;
7975
7976 bool BodyLineInvalid;
7977 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
7978 &BodyLineInvalid);
7979 if (BodyLineInvalid)
7980 return false;
7981
7982 // Warn if null statement and body are on the same line.
7983 if (StmtLine != BodyLine)
7984 return false;
7985
7986 return true;
7987}
7988} // Unnamed namespace
7989
7990void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
7991 const Stmt *Body,
7992 unsigned DiagID) {
7993 // Since this is a syntactic check, don't emit diagnostic for template
7994 // instantiations, this just adds noise.
7995 if (CurrentInstantiationScope)
7996 return;
7997
7998 // The body should be a null statement.
7999 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8000 if (!NBody)
8001 return;
8002
8003 // Do the usual checks.
8004 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8005 return;
8006
8007 Diag(NBody->getSemiLoc(), DiagID);
8008 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8009}
8010
8011void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8012 const Stmt *PossibleBody) {
8013 assert(!CurrentInstantiationScope); // Ensured by caller
8014
8015 SourceLocation StmtLoc;
8016 const Stmt *Body;
8017 unsigned DiagID;
8018 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8019 StmtLoc = FS->getRParenLoc();
8020 Body = FS->getBody();
8021 DiagID = diag::warn_empty_for_body;
8022 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8023 StmtLoc = WS->getCond()->getSourceRange().getEnd();
8024 Body = WS->getBody();
8025 DiagID = diag::warn_empty_while_body;
8026 } else
8027 return; // Neither `for' nor `while'.
8028
8029 // The body should be a null statement.
8030 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8031 if (!NBody)
8032 return;
8033
8034 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008035 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008036 return;
8037
8038 // Do the usual checks.
8039 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8040 return;
8041
8042 // `for(...);' and `while(...);' are popular idioms, so in order to keep
8043 // noise level low, emit diagnostics only if for/while is followed by a
8044 // CompoundStmt, e.g.:
8045 // for (int i = 0; i < n; i++);
8046 // {
8047 // a(i);
8048 // }
8049 // or if for/while is followed by a statement with more indentation
8050 // than for/while itself:
8051 // for (int i = 0; i < n; i++);
8052 // a(i);
8053 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8054 if (!ProbableTypo) {
8055 bool BodyColInvalid;
8056 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8057 PossibleBody->getLocStart(),
8058 &BodyColInvalid);
8059 if (BodyColInvalid)
8060 return;
8061
8062 bool StmtColInvalid;
8063 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8064 S->getLocStart(),
8065 &StmtColInvalid);
8066 if (StmtColInvalid)
8067 return;
8068
8069 if (BodyCol > StmtCol)
8070 ProbableTypo = true;
8071 }
8072
8073 if (ProbableTypo) {
8074 Diag(NBody->getSemiLoc(), DiagID);
8075 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8076 }
8077}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008078
8079//===--- Layout compatibility ----------------------------------------------//
8080
8081namespace {
8082
8083bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8084
8085/// \brief Check if two enumeration types are layout-compatible.
8086bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8087 // C++11 [dcl.enum] p8:
8088 // Two enumeration types are layout-compatible if they have the same
8089 // underlying type.
8090 return ED1->isComplete() && ED2->isComplete() &&
8091 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8092}
8093
8094/// \brief Check if two fields are layout-compatible.
8095bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8096 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8097 return false;
8098
8099 if (Field1->isBitField() != Field2->isBitField())
8100 return false;
8101
8102 if (Field1->isBitField()) {
8103 // Make sure that the bit-fields are the same length.
8104 unsigned Bits1 = Field1->getBitWidthValue(C);
8105 unsigned Bits2 = Field2->getBitWidthValue(C);
8106
8107 if (Bits1 != Bits2)
8108 return false;
8109 }
8110
8111 return true;
8112}
8113
8114/// \brief Check if two standard-layout structs are layout-compatible.
8115/// (C++11 [class.mem] p17)
8116bool isLayoutCompatibleStruct(ASTContext &C,
8117 RecordDecl *RD1,
8118 RecordDecl *RD2) {
8119 // If both records are C++ classes, check that base classes match.
8120 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
8121 // If one of records is a CXXRecordDecl we are in C++ mode,
8122 // thus the other one is a CXXRecordDecl, too.
8123 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
8124 // Check number of base classes.
8125 if (D1CXX->getNumBases() != D2CXX->getNumBases())
8126 return false;
8127
8128 // Check the base classes.
8129 for (CXXRecordDecl::base_class_const_iterator
8130 Base1 = D1CXX->bases_begin(),
8131 BaseEnd1 = D1CXX->bases_end(),
8132 Base2 = D2CXX->bases_begin();
8133 Base1 != BaseEnd1;
8134 ++Base1, ++Base2) {
8135 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
8136 return false;
8137 }
8138 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
8139 // If only RD2 is a C++ class, it should have zero base classes.
8140 if (D2CXX->getNumBases() > 0)
8141 return false;
8142 }
8143
8144 // Check the fields.
8145 RecordDecl::field_iterator Field2 = RD2->field_begin(),
8146 Field2End = RD2->field_end(),
8147 Field1 = RD1->field_begin(),
8148 Field1End = RD1->field_end();
8149 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
8150 if (!isLayoutCompatible(C, *Field1, *Field2))
8151 return false;
8152 }
8153 if (Field1 != Field1End || Field2 != Field2End)
8154 return false;
8155
8156 return true;
8157}
8158
8159/// \brief Check if two standard-layout unions are layout-compatible.
8160/// (C++11 [class.mem] p18)
8161bool isLayoutCompatibleUnion(ASTContext &C,
8162 RecordDecl *RD1,
8163 RecordDecl *RD2) {
8164 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008165 for (auto *Field2 : RD2->fields())
8166 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008167
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008168 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008169 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
8170 I = UnmatchedFields.begin(),
8171 E = UnmatchedFields.end();
8172
8173 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008174 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008175 bool Result = UnmatchedFields.erase(*I);
8176 (void) Result;
8177 assert(Result);
8178 break;
8179 }
8180 }
8181 if (I == E)
8182 return false;
8183 }
8184
8185 return UnmatchedFields.empty();
8186}
8187
8188bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
8189 if (RD1->isUnion() != RD2->isUnion())
8190 return false;
8191
8192 if (RD1->isUnion())
8193 return isLayoutCompatibleUnion(C, RD1, RD2);
8194 else
8195 return isLayoutCompatibleStruct(C, RD1, RD2);
8196}
8197
8198/// \brief Check if two types are layout-compatible in C++11 sense.
8199bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
8200 if (T1.isNull() || T2.isNull())
8201 return false;
8202
8203 // C++11 [basic.types] p11:
8204 // If two types T1 and T2 are the same type, then T1 and T2 are
8205 // layout-compatible types.
8206 if (C.hasSameType(T1, T2))
8207 return true;
8208
8209 T1 = T1.getCanonicalType().getUnqualifiedType();
8210 T2 = T2.getCanonicalType().getUnqualifiedType();
8211
8212 const Type::TypeClass TC1 = T1->getTypeClass();
8213 const Type::TypeClass TC2 = T2->getTypeClass();
8214
8215 if (TC1 != TC2)
8216 return false;
8217
8218 if (TC1 == Type::Enum) {
8219 return isLayoutCompatible(C,
8220 cast<EnumType>(T1)->getDecl(),
8221 cast<EnumType>(T2)->getDecl());
8222 } else if (TC1 == Type::Record) {
8223 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
8224 return false;
8225
8226 return isLayoutCompatible(C,
8227 cast<RecordType>(T1)->getDecl(),
8228 cast<RecordType>(T2)->getDecl());
8229 }
8230
8231 return false;
8232}
8233}
8234
8235//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
8236
8237namespace {
8238/// \brief Given a type tag expression find the type tag itself.
8239///
8240/// \param TypeExpr Type tag expression, as it appears in user's code.
8241///
8242/// \param VD Declaration of an identifier that appears in a type tag.
8243///
8244/// \param MagicValue Type tag magic value.
8245bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
8246 const ValueDecl **VD, uint64_t *MagicValue) {
8247 while(true) {
8248 if (!TypeExpr)
8249 return false;
8250
8251 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
8252
8253 switch (TypeExpr->getStmtClass()) {
8254 case Stmt::UnaryOperatorClass: {
8255 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
8256 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
8257 TypeExpr = UO->getSubExpr();
8258 continue;
8259 }
8260 return false;
8261 }
8262
8263 case Stmt::DeclRefExprClass: {
8264 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
8265 *VD = DRE->getDecl();
8266 return true;
8267 }
8268
8269 case Stmt::IntegerLiteralClass: {
8270 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
8271 llvm::APInt MagicValueAPInt = IL->getValue();
8272 if (MagicValueAPInt.getActiveBits() <= 64) {
8273 *MagicValue = MagicValueAPInt.getZExtValue();
8274 return true;
8275 } else
8276 return false;
8277 }
8278
8279 case Stmt::BinaryConditionalOperatorClass:
8280 case Stmt::ConditionalOperatorClass: {
8281 const AbstractConditionalOperator *ACO =
8282 cast<AbstractConditionalOperator>(TypeExpr);
8283 bool Result;
8284 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
8285 if (Result)
8286 TypeExpr = ACO->getTrueExpr();
8287 else
8288 TypeExpr = ACO->getFalseExpr();
8289 continue;
8290 }
8291 return false;
8292 }
8293
8294 case Stmt::BinaryOperatorClass: {
8295 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
8296 if (BO->getOpcode() == BO_Comma) {
8297 TypeExpr = BO->getRHS();
8298 continue;
8299 }
8300 return false;
8301 }
8302
8303 default:
8304 return false;
8305 }
8306 }
8307}
8308
8309/// \brief Retrieve the C type corresponding to type tag TypeExpr.
8310///
8311/// \param TypeExpr Expression that specifies a type tag.
8312///
8313/// \param MagicValues Registered magic values.
8314///
8315/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
8316/// kind.
8317///
8318/// \param TypeInfo Information about the corresponding C type.
8319///
8320/// \returns true if the corresponding C type was found.
8321bool GetMatchingCType(
8322 const IdentifierInfo *ArgumentKind,
8323 const Expr *TypeExpr, const ASTContext &Ctx,
8324 const llvm::DenseMap<Sema::TypeTagMagicValue,
8325 Sema::TypeTagData> *MagicValues,
8326 bool &FoundWrongKind,
8327 Sema::TypeTagData &TypeInfo) {
8328 FoundWrongKind = false;
8329
8330 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00008331 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008332
8333 uint64_t MagicValue;
8334
8335 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
8336 return false;
8337
8338 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00008339 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008340 if (I->getArgumentKind() != ArgumentKind) {
8341 FoundWrongKind = true;
8342 return false;
8343 }
8344 TypeInfo.Type = I->getMatchingCType();
8345 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
8346 TypeInfo.MustBeNull = I->getMustBeNull();
8347 return true;
8348 }
8349 return false;
8350 }
8351
8352 if (!MagicValues)
8353 return false;
8354
8355 llvm::DenseMap<Sema::TypeTagMagicValue,
8356 Sema::TypeTagData>::const_iterator I =
8357 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
8358 if (I == MagicValues->end())
8359 return false;
8360
8361 TypeInfo = I->second;
8362 return true;
8363}
8364} // unnamed namespace
8365
8366void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8367 uint64_t MagicValue, QualType Type,
8368 bool LayoutCompatible,
8369 bool MustBeNull) {
8370 if (!TypeTagForDatatypeMagicValues)
8371 TypeTagForDatatypeMagicValues.reset(
8372 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
8373
8374 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
8375 (*TypeTagForDatatypeMagicValues)[Magic] =
8376 TypeTagData(Type, LayoutCompatible, MustBeNull);
8377}
8378
8379namespace {
8380bool IsSameCharType(QualType T1, QualType T2) {
8381 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
8382 if (!BT1)
8383 return false;
8384
8385 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8386 if (!BT2)
8387 return false;
8388
8389 BuiltinType::Kind T1Kind = BT1->getKind();
8390 BuiltinType::Kind T2Kind = BT2->getKind();
8391
8392 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
8393 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
8394 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8395 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8396}
8397} // unnamed namespace
8398
8399void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8400 const Expr * const *ExprArgs) {
8401 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8402 bool IsPointerAttr = Attr->getIsPointer();
8403
8404 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8405 bool FoundWrongKind;
8406 TypeTagData TypeInfo;
8407 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8408 TypeTagForDatatypeMagicValues.get(),
8409 FoundWrongKind, TypeInfo)) {
8410 if (FoundWrongKind)
8411 Diag(TypeTagExpr->getExprLoc(),
8412 diag::warn_type_tag_for_datatype_wrong_kind)
8413 << TypeTagExpr->getSourceRange();
8414 return;
8415 }
8416
8417 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8418 if (IsPointerAttr) {
8419 // Skip implicit cast of pointer to `void *' (as a function argument).
8420 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00008421 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00008422 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008423 ArgumentExpr = ICE->getSubExpr();
8424 }
8425 QualType ArgumentType = ArgumentExpr->getType();
8426
8427 // Passing a `void*' pointer shouldn't trigger a warning.
8428 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8429 return;
8430
8431 if (TypeInfo.MustBeNull) {
8432 // Type tag with matching void type requires a null pointer.
8433 if (!ArgumentExpr->isNullPointerConstant(Context,
8434 Expr::NPC_ValueDependentIsNotNull)) {
8435 Diag(ArgumentExpr->getExprLoc(),
8436 diag::warn_type_safety_null_pointer_required)
8437 << ArgumentKind->getName()
8438 << ArgumentExpr->getSourceRange()
8439 << TypeTagExpr->getSourceRange();
8440 }
8441 return;
8442 }
8443
8444 QualType RequiredType = TypeInfo.Type;
8445 if (IsPointerAttr)
8446 RequiredType = Context.getPointerType(RequiredType);
8447
8448 bool mismatch = false;
8449 if (!TypeInfo.LayoutCompatible) {
8450 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8451
8452 // C++11 [basic.fundamental] p1:
8453 // Plain char, signed char, and unsigned char are three distinct types.
8454 //
8455 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8456 // char' depending on the current char signedness mode.
8457 if (mismatch)
8458 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8459 RequiredType->getPointeeType())) ||
8460 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8461 mismatch = false;
8462 } else
8463 if (IsPointerAttr)
8464 mismatch = !isLayoutCompatible(Context,
8465 ArgumentType->getPointeeType(),
8466 RequiredType->getPointeeType());
8467 else
8468 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8469
8470 if (mismatch)
8471 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00008472 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008473 << TypeInfo.LayoutCompatible << RequiredType
8474 << ArgumentExpr->getSourceRange()
8475 << TypeTagExpr->getSourceRange();
8476}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008477