blob: 3e3d60e053119747a1e5f6824d4ba99b3e977a54 [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
Peter Collingbournef7706832014-12-12 23:41:25 +0000142static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
143 if (checkArgCount(S, BuiltinCall, 2))
144 return true;
145
146 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
147 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
148 Expr *Call = BuiltinCall->getArg(0);
149 Expr *Chain = BuiltinCall->getArg(1);
150
151 if (Call->getStmtClass() != Stmt::CallExprClass) {
152 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
153 << Call->getSourceRange();
154 return true;
155 }
156
157 auto CE = cast<CallExpr>(Call);
158 if (CE->getCallee()->getType()->isBlockPointerType()) {
159 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
160 << Call->getSourceRange();
161 return true;
162 }
163
164 const Decl *TargetDecl = CE->getCalleeDecl();
165 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
166 if (FD->getBuiltinID()) {
167 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
168 << Call->getSourceRange();
169 return true;
170 }
171
172 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
173 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
174 << Call->getSourceRange();
175 return true;
176 }
177
178 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
179 if (ChainResult.isInvalid())
180 return true;
181 if (!ChainResult.get()->getType()->isPointerType()) {
182 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
183 << Chain->getSourceRange();
184 return true;
185 }
186
David Majnemerced8bdf2015-02-25 17:36:15 +0000187 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000188 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
189 QualType BuiltinTy = S.Context.getFunctionType(
190 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
191 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
192
193 Builtin =
194 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
195
196 BuiltinCall->setType(CE->getType());
197 BuiltinCall->setValueKind(CE->getValueKind());
198 BuiltinCall->setObjectKind(CE->getObjectKind());
199 BuiltinCall->setCallee(Builtin);
200 BuiltinCall->setArg(1, ChainResult.get());
201
202 return false;
203}
204
Reid Kleckner1d59f992015-01-22 01:36:17 +0000205static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
206 Scope::ScopeFlags NeededScopeFlags,
207 unsigned DiagID) {
208 // Scopes aren't available during instantiation. Fortunately, builtin
209 // functions cannot be template args so they cannot be formed through template
210 // instantiation. Therefore checking once during the parse is sufficient.
211 if (!SemaRef.ActiveTemplateInstantiations.empty())
212 return false;
213
214 Scope *S = SemaRef.getCurScope();
215 while (S && !S->isSEHExceptScope())
216 S = S->getParent();
217 if (!S || !(S->getFlags() & NeededScopeFlags)) {
218 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
219 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
220 << DRE->getDecl()->getIdentifier();
221 return true;
222 }
223
224 return false;
225}
226
John McCalldadc5752010-08-24 06:29:42 +0000227ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000228Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
229 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000230 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000231
Chris Lattner3be167f2010-10-01 23:23:24 +0000232 // Find out if any arguments are required to be integer constant expressions.
233 unsigned ICEArguments = 0;
234 ASTContext::GetBuiltinTypeError Error;
235 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
236 if (Error != ASTContext::GE_None)
237 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
238
239 // If any arguments are required to be ICE's, check and diagnose.
240 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
241 // Skip arguments not required to be ICE's.
242 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
243
244 llvm::APSInt Result;
245 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
246 return true;
247 ICEArguments &= ~(1 << ArgNo);
248 }
249
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000250 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000251 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000252 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000253 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000254 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000255 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000256 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000257 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000258 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000259 if (SemaBuiltinVAStart(TheCall))
260 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000261 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000262 case Builtin::BI__va_start: {
263 switch (Context.getTargetInfo().getTriple().getArch()) {
264 case llvm::Triple::arm:
265 case llvm::Triple::thumb:
266 if (SemaBuiltinVAStartARM(TheCall))
267 return ExprError();
268 break;
269 default:
270 if (SemaBuiltinVAStart(TheCall))
271 return ExprError();
272 break;
273 }
274 break;
275 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000276 case Builtin::BI__builtin_isgreater:
277 case Builtin::BI__builtin_isgreaterequal:
278 case Builtin::BI__builtin_isless:
279 case Builtin::BI__builtin_islessequal:
280 case Builtin::BI__builtin_islessgreater:
281 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000282 if (SemaBuiltinUnorderedCompare(TheCall))
283 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000284 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000285 case Builtin::BI__builtin_fpclassify:
286 if (SemaBuiltinFPClassification(TheCall, 6))
287 return ExprError();
288 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000289 case Builtin::BI__builtin_isfinite:
290 case Builtin::BI__builtin_isinf:
291 case Builtin::BI__builtin_isinf_sign:
292 case Builtin::BI__builtin_isnan:
293 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000294 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000295 return ExprError();
296 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000297 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000298 return SemaBuiltinShuffleVector(TheCall);
299 // TheCall will be freed by the smart pointer here, but that's fine, since
300 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000301 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000302 if (SemaBuiltinPrefetch(TheCall))
303 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000304 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000305 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000306 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000307 if (SemaBuiltinAssume(TheCall))
308 return ExprError();
309 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000310 case Builtin::BI__builtin_assume_aligned:
311 if (SemaBuiltinAssumeAligned(TheCall))
312 return ExprError();
313 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000314 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000315 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000316 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000317 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000318 case Builtin::BI__builtin_longjmp:
319 if (SemaBuiltinLongjmp(TheCall))
320 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000321 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000322 case Builtin::BI__builtin_setjmp:
323 if (SemaBuiltinSetjmp(TheCall))
324 return ExprError();
325 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000326 case Builtin::BI_setjmp:
327 case Builtin::BI_setjmpex:
328 if (checkArgCount(*this, TheCall, 1))
329 return true;
330 break;
John McCallbebede42011-02-26 05:39:39 +0000331
332 case Builtin::BI__builtin_classify_type:
333 if (checkArgCount(*this, TheCall, 1)) return true;
334 TheCall->setType(Context.IntTy);
335 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000336 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000337 if (checkArgCount(*this, TheCall, 1)) return true;
338 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000339 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000340 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000341 case Builtin::BI__sync_fetch_and_add_1:
342 case Builtin::BI__sync_fetch_and_add_2:
343 case Builtin::BI__sync_fetch_and_add_4:
344 case Builtin::BI__sync_fetch_and_add_8:
345 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000346 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000347 case Builtin::BI__sync_fetch_and_sub_1:
348 case Builtin::BI__sync_fetch_and_sub_2:
349 case Builtin::BI__sync_fetch_and_sub_4:
350 case Builtin::BI__sync_fetch_and_sub_8:
351 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000352 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000353 case Builtin::BI__sync_fetch_and_or_1:
354 case Builtin::BI__sync_fetch_and_or_2:
355 case Builtin::BI__sync_fetch_and_or_4:
356 case Builtin::BI__sync_fetch_and_or_8:
357 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000358 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000359 case Builtin::BI__sync_fetch_and_and_1:
360 case Builtin::BI__sync_fetch_and_and_2:
361 case Builtin::BI__sync_fetch_and_and_4:
362 case Builtin::BI__sync_fetch_and_and_8:
363 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000364 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000365 case Builtin::BI__sync_fetch_and_xor_1:
366 case Builtin::BI__sync_fetch_and_xor_2:
367 case Builtin::BI__sync_fetch_and_xor_4:
368 case Builtin::BI__sync_fetch_and_xor_8:
369 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000370 case Builtin::BI__sync_fetch_and_nand:
371 case Builtin::BI__sync_fetch_and_nand_1:
372 case Builtin::BI__sync_fetch_and_nand_2:
373 case Builtin::BI__sync_fetch_and_nand_4:
374 case Builtin::BI__sync_fetch_and_nand_8:
375 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000376 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000377 case Builtin::BI__sync_add_and_fetch_1:
378 case Builtin::BI__sync_add_and_fetch_2:
379 case Builtin::BI__sync_add_and_fetch_4:
380 case Builtin::BI__sync_add_and_fetch_8:
381 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000382 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000383 case Builtin::BI__sync_sub_and_fetch_1:
384 case Builtin::BI__sync_sub_and_fetch_2:
385 case Builtin::BI__sync_sub_and_fetch_4:
386 case Builtin::BI__sync_sub_and_fetch_8:
387 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000388 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000389 case Builtin::BI__sync_and_and_fetch_1:
390 case Builtin::BI__sync_and_and_fetch_2:
391 case Builtin::BI__sync_and_and_fetch_4:
392 case Builtin::BI__sync_and_and_fetch_8:
393 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000394 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000395 case Builtin::BI__sync_or_and_fetch_1:
396 case Builtin::BI__sync_or_and_fetch_2:
397 case Builtin::BI__sync_or_and_fetch_4:
398 case Builtin::BI__sync_or_and_fetch_8:
399 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000400 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000401 case Builtin::BI__sync_xor_and_fetch_1:
402 case Builtin::BI__sync_xor_and_fetch_2:
403 case Builtin::BI__sync_xor_and_fetch_4:
404 case Builtin::BI__sync_xor_and_fetch_8:
405 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000406 case Builtin::BI__sync_nand_and_fetch:
407 case Builtin::BI__sync_nand_and_fetch_1:
408 case Builtin::BI__sync_nand_and_fetch_2:
409 case Builtin::BI__sync_nand_and_fetch_4:
410 case Builtin::BI__sync_nand_and_fetch_8:
411 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000412 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000413 case Builtin::BI__sync_val_compare_and_swap_1:
414 case Builtin::BI__sync_val_compare_and_swap_2:
415 case Builtin::BI__sync_val_compare_and_swap_4:
416 case Builtin::BI__sync_val_compare_and_swap_8:
417 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000418 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000419 case Builtin::BI__sync_bool_compare_and_swap_1:
420 case Builtin::BI__sync_bool_compare_and_swap_2:
421 case Builtin::BI__sync_bool_compare_and_swap_4:
422 case Builtin::BI__sync_bool_compare_and_swap_8:
423 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000424 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000425 case Builtin::BI__sync_lock_test_and_set_1:
426 case Builtin::BI__sync_lock_test_and_set_2:
427 case Builtin::BI__sync_lock_test_and_set_4:
428 case Builtin::BI__sync_lock_test_and_set_8:
429 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000430 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000431 case Builtin::BI__sync_lock_release_1:
432 case Builtin::BI__sync_lock_release_2:
433 case Builtin::BI__sync_lock_release_4:
434 case Builtin::BI__sync_lock_release_8:
435 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000436 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000437 case Builtin::BI__sync_swap_1:
438 case Builtin::BI__sync_swap_2:
439 case Builtin::BI__sync_swap_4:
440 case Builtin::BI__sync_swap_8:
441 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000442 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000443#define BUILTIN(ID, TYPE, ATTRS)
444#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
445 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000446 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000447#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000448 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000449 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000450 return ExprError();
451 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000452 case Builtin::BI__builtin_addressof:
453 if (SemaBuiltinAddressof(*this, TheCall))
454 return ExprError();
455 break;
Richard Smith760520b2014-06-03 23:27:44 +0000456 case Builtin::BI__builtin_operator_new:
457 case Builtin::BI__builtin_operator_delete:
458 if (!getLangOpts().CPlusPlus) {
459 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
460 << (BuiltinID == Builtin::BI__builtin_operator_new
461 ? "__builtin_operator_new"
462 : "__builtin_operator_delete")
463 << "C++";
464 return ExprError();
465 }
466 // CodeGen assumes it can find the global new and delete to call,
467 // so ensure that they are declared.
468 DeclareGlobalNewDelete();
469 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000470
471 // check secure string manipulation functions where overflows
472 // are detectable at compile time
473 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000474 case Builtin::BI__builtin___memmove_chk:
475 case Builtin::BI__builtin___memset_chk:
476 case Builtin::BI__builtin___strlcat_chk:
477 case Builtin::BI__builtin___strlcpy_chk:
478 case Builtin::BI__builtin___strncat_chk:
479 case Builtin::BI__builtin___strncpy_chk:
480 case Builtin::BI__builtin___stpncpy_chk:
481 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
482 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000483 case Builtin::BI__builtin___memccpy_chk:
484 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
485 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000486 case Builtin::BI__builtin___snprintf_chk:
487 case Builtin::BI__builtin___vsnprintf_chk:
488 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
489 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000490
491 case Builtin::BI__builtin_call_with_static_chain:
492 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
493 return ExprError();
494 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000495
496 case Builtin::BI__exception_code:
497 case Builtin::BI_exception_code: {
498 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
499 diag::err_seh___except_block))
500 return ExprError();
501 break;
502 }
503 case Builtin::BI__exception_info:
504 case Builtin::BI_exception_info: {
505 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
506 diag::err_seh___except_filter))
507 return ExprError();
508 break;
509 }
510
David Majnemerba3e5ec2015-03-13 18:26:17 +0000511 case Builtin::BI__GetExceptionInfo:
512 if (checkArgCount(*this, TheCall, 1))
513 return ExprError();
514
515 if (CheckCXXThrowOperand(
516 TheCall->getLocStart(),
517 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
518 TheCall))
519 return ExprError();
520
521 TheCall->setType(Context.VoidPtrTy);
522 break;
523
Nate Begeman4904e322010-06-08 02:47:44 +0000524 }
Richard Smith760520b2014-06-03 23:27:44 +0000525
Nate Begeman4904e322010-06-08 02:47:44 +0000526 // Since the target specific builtins for each arch overlap, only check those
527 // of the arch we are compiling for.
528 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000529 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000530 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000531 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000532 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000533 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000534 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
535 return ExprError();
536 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000537 case llvm::Triple::aarch64:
538 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000539 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000540 return ExprError();
541 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000542 case llvm::Triple::mips:
543 case llvm::Triple::mipsel:
544 case llvm::Triple::mips64:
545 case llvm::Triple::mips64el:
546 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
547 return ExprError();
548 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000549 case llvm::Triple::x86:
550 case llvm::Triple::x86_64:
551 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
552 return ExprError();
553 break;
Kit Bartone50adcb2015-03-30 19:40:59 +0000554 case llvm::Triple::ppc:
555 case llvm::Triple::ppc64:
556 case llvm::Triple::ppc64le:
557 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
558 return ExprError();
559 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000560 default:
561 break;
562 }
563 }
564
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000565 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000566}
567
Nate Begeman91e1fea2010-06-14 05:21:25 +0000568// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000569static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000570 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000571 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000572 switch (Type.getEltType()) {
573 case NeonTypeFlags::Int8:
574 case NeonTypeFlags::Poly8:
575 return shift ? 7 : (8 << IsQuad) - 1;
576 case NeonTypeFlags::Int16:
577 case NeonTypeFlags::Poly16:
578 return shift ? 15 : (4 << IsQuad) - 1;
579 case NeonTypeFlags::Int32:
580 return shift ? 31 : (2 << IsQuad) - 1;
581 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000582 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000583 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000584 case NeonTypeFlags::Poly128:
585 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000586 case NeonTypeFlags::Float16:
587 assert(!shift && "cannot shift float types!");
588 return (4 << IsQuad) - 1;
589 case NeonTypeFlags::Float32:
590 assert(!shift && "cannot shift float types!");
591 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000592 case NeonTypeFlags::Float64:
593 assert(!shift && "cannot shift float types!");
594 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000595 }
David Blaikie8a40f702012-01-17 06:56:22 +0000596 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000597}
598
Bob Wilsone4d77232011-11-08 05:04:11 +0000599/// getNeonEltType - Return the QualType corresponding to the elements of
600/// the vector type specified by the NeonTypeFlags. This is used to check
601/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000602static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000603 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000604 switch (Flags.getEltType()) {
605 case NeonTypeFlags::Int8:
606 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
607 case NeonTypeFlags::Int16:
608 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
609 case NeonTypeFlags::Int32:
610 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
611 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000612 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000613 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
614 else
615 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
616 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000617 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000618 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000619 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000620 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000621 case NeonTypeFlags::Poly64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000622 return Context.UnsignedLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000623 case NeonTypeFlags::Poly128:
624 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000625 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000626 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000627 case NeonTypeFlags::Float32:
628 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000629 case NeonTypeFlags::Float64:
630 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000631 }
David Blaikie8a40f702012-01-17 06:56:22 +0000632 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000633}
634
Tim Northover12670412014-02-19 10:37:05 +0000635bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000636 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000637 uint64_t mask = 0;
638 unsigned TV = 0;
639 int PtrArgNum = -1;
640 bool HasConstPtr = false;
641 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000642#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000643#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000644#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000645 }
646
647 // For NEON intrinsics which are overloaded on vector element type, validate
648 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000649 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000650 if (mask) {
651 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
652 return true;
653
654 TV = Result.getLimitedValue(64);
655 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
656 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000657 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000658 }
659
660 if (PtrArgNum >= 0) {
661 // Check that pointer arguments have the specified type.
662 Expr *Arg = TheCall->getArg(PtrArgNum);
663 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
664 Arg = ICE->getSubExpr();
665 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
666 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000667
Tim Northovera2ee4332014-03-29 15:09:45 +0000668 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000669 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000670 bool IsInt64Long =
671 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
672 QualType EltTy =
673 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000674 if (HasConstPtr)
675 EltTy = EltTy.withConst();
676 QualType LHSTy = Context.getPointerType(EltTy);
677 AssignConvertType ConvTy;
678 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
679 if (RHS.isInvalid())
680 return true;
681 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
682 RHS.get(), AA_Assigning))
683 return true;
684 }
685
686 // For NEON intrinsics which take an immediate value as part of the
687 // instruction, range check them here.
688 unsigned i = 0, l = 0, u = 0;
689 switch (BuiltinID) {
690 default:
691 return false;
Tim Northover12670412014-02-19 10:37:05 +0000692#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000693#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000694#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000695 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000696
Richard Sandiford28940af2014-04-16 08:47:51 +0000697 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000698}
699
Tim Northovera2ee4332014-03-29 15:09:45 +0000700bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
701 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000702 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000703 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000704 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000705 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000706 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000707 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
708 BuiltinID == AArch64::BI__builtin_arm_strex ||
709 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000710 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000711 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000712 BuiltinID == ARM::BI__builtin_arm_ldaex ||
713 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
714 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000715
716 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
717
718 // Ensure that we have the proper number of arguments.
719 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
720 return true;
721
722 // Inspect the pointer argument of the atomic builtin. This should always be
723 // a pointer type, whose element is an integral scalar or pointer type.
724 // Because it is a pointer type, we don't have to worry about any implicit
725 // casts here.
726 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
727 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
728 if (PointerArgRes.isInvalid())
729 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000730 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000731
732 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
733 if (!pointerType) {
734 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
735 << PointerArg->getType() << PointerArg->getSourceRange();
736 return true;
737 }
738
739 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
740 // task is to insert the appropriate casts into the AST. First work out just
741 // what the appropriate type is.
742 QualType ValType = pointerType->getPointeeType();
743 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
744 if (IsLdrex)
745 AddrType.addConst();
746
747 // Issue a warning if the cast is dodgy.
748 CastKind CastNeeded = CK_NoOp;
749 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
750 CastNeeded = CK_BitCast;
751 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
752 << PointerArg->getType()
753 << Context.getPointerType(AddrType)
754 << AA_Passing << PointerArg->getSourceRange();
755 }
756
757 // Finally, do the cast and replace the argument with the corrected version.
758 AddrType = Context.getPointerType(AddrType);
759 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
760 if (PointerArgRes.isInvalid())
761 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000762 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000763
764 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
765
766 // In general, we allow ints, floats and pointers to be loaded and stored.
767 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
768 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
769 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
770 << PointerArg->getType() << PointerArg->getSourceRange();
771 return true;
772 }
773
774 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000775 if (Context.getTypeSize(ValType) > MaxWidth) {
776 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000777 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
778 << PointerArg->getType() << PointerArg->getSourceRange();
779 return true;
780 }
781
782 switch (ValType.getObjCLifetime()) {
783 case Qualifiers::OCL_None:
784 case Qualifiers::OCL_ExplicitNone:
785 // okay
786 break;
787
788 case Qualifiers::OCL_Weak:
789 case Qualifiers::OCL_Strong:
790 case Qualifiers::OCL_Autoreleasing:
791 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
792 << ValType << PointerArg->getSourceRange();
793 return true;
794 }
795
796
797 if (IsLdrex) {
798 TheCall->setType(ValType);
799 return false;
800 }
801
802 // Initialize the argument to be stored.
803 ExprResult ValArg = TheCall->getArg(0);
804 InitializedEntity Entity = InitializedEntity::InitializeParameter(
805 Context, ValType, /*consume*/ false);
806 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
807 if (ValArg.isInvalid())
808 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000809 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000810
811 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
812 // but the custom checker bypasses all default analysis.
813 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000814 return false;
815}
816
Nate Begeman4904e322010-06-08 02:47:44 +0000817bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000818 llvm::APSInt Result;
819
Tim Northover6aacd492013-07-16 09:47:53 +0000820 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000821 BuiltinID == ARM::BI__builtin_arm_ldaex ||
822 BuiltinID == ARM::BI__builtin_arm_strex ||
823 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000824 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000825 }
826
Yi Kong26d104a2014-08-13 19:18:14 +0000827 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
828 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
829 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
830 }
831
Tim Northover12670412014-02-19 10:37:05 +0000832 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
833 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000834
Yi Kong4efadfb2014-07-03 16:01:25 +0000835 // For intrinsics which take an immediate value as part of the instruction,
836 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000837 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000838 switch (BuiltinID) {
839 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000840 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
841 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000842 case ARM::BI__builtin_arm_vcvtr_f:
843 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000844 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +0000845 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +0000846 case ARM::BI__builtin_arm_isb:
847 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000848 }
Nate Begemand773fe62010-06-13 04:47:52 +0000849
Nate Begemanf568b072010-08-03 21:32:34 +0000850 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000851 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000852}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000853
Tim Northover573cbee2014-05-24 12:52:07 +0000854bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000855 CallExpr *TheCall) {
856 llvm::APSInt Result;
857
Tim Northover573cbee2014-05-24 12:52:07 +0000858 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000859 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
860 BuiltinID == AArch64::BI__builtin_arm_strex ||
861 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000862 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
863 }
864
Yi Konga5548432014-08-13 19:18:20 +0000865 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
866 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
867 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
868 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
869 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
870 }
871
Tim Northovera2ee4332014-03-29 15:09:45 +0000872 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
873 return true;
874
Yi Kong19a29ac2014-07-17 10:52:06 +0000875 // For intrinsics which take an immediate value as part of the instruction,
876 // range check them here.
877 unsigned i = 0, l = 0, u = 0;
878 switch (BuiltinID) {
879 default: return false;
880 case AArch64::BI__builtin_arm_dmb:
881 case AArch64::BI__builtin_arm_dsb:
882 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
883 }
884
Yi Kong19a29ac2014-07-17 10:52:06 +0000885 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +0000886}
887
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000888bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
889 unsigned i = 0, l = 0, u = 0;
890 switch (BuiltinID) {
891 default: return false;
892 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
893 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000894 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
895 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
896 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
897 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
898 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000899 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000900
Richard Sandiford28940af2014-04-16 08:47:51 +0000901 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000902}
903
Kit Bartone50adcb2015-03-30 19:40:59 +0000904bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
905 unsigned i = 0, l = 0, u = 0;
906 switch (BuiltinID) {
907 default: return false;
908 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
909 case PPC::BI__builtin_altivec_crypto_vshasigmad:
910 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
911 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
912 case PPC::BI__builtin_tbegin:
913 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
914 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
915 case PPC::BI__builtin_tabortwc:
916 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
917 case PPC::BI__builtin_tabortwci:
918 case PPC::BI__builtin_tabortdci:
919 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
920 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
921 }
922 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
923}
924
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000925bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topperdd84ec52014-12-27 07:00:08 +0000926 unsigned i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000927 switch (BuiltinID) {
Craig Topperdd84ec52014-12-27 07:00:08 +0000928 default: return false;
929 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
Craig Topper16015252015-01-31 06:31:23 +0000930 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
Craig Topper1a8b0472015-01-31 08:57:52 +0000931 case X86::BI__builtin_ia32_vpermil2pd:
932 case X86::BI__builtin_ia32_vpermil2pd256:
933 case X86::BI__builtin_ia32_vpermil2ps:
934 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
Craig Topper95b0d732015-01-25 23:30:05 +0000935 case X86::BI__builtin_ia32_cmpb128_mask:
936 case X86::BI__builtin_ia32_cmpw128_mask:
937 case X86::BI__builtin_ia32_cmpd128_mask:
938 case X86::BI__builtin_ia32_cmpq128_mask:
939 case X86::BI__builtin_ia32_cmpb256_mask:
940 case X86::BI__builtin_ia32_cmpw256_mask:
941 case X86::BI__builtin_ia32_cmpd256_mask:
942 case X86::BI__builtin_ia32_cmpq256_mask:
943 case X86::BI__builtin_ia32_cmpb512_mask:
944 case X86::BI__builtin_ia32_cmpw512_mask:
945 case X86::BI__builtin_ia32_cmpd512_mask:
946 case X86::BI__builtin_ia32_cmpq512_mask:
947 case X86::BI__builtin_ia32_ucmpb128_mask:
948 case X86::BI__builtin_ia32_ucmpw128_mask:
949 case X86::BI__builtin_ia32_ucmpd128_mask:
950 case X86::BI__builtin_ia32_ucmpq128_mask:
951 case X86::BI__builtin_ia32_ucmpb256_mask:
952 case X86::BI__builtin_ia32_ucmpw256_mask:
953 case X86::BI__builtin_ia32_ucmpd256_mask:
954 case X86::BI__builtin_ia32_ucmpq256_mask:
955 case X86::BI__builtin_ia32_ucmpb512_mask:
956 case X86::BI__builtin_ia32_ucmpw512_mask:
957 case X86::BI__builtin_ia32_ucmpd512_mask:
958 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
Craig Topper16015252015-01-31 06:31:23 +0000959 case X86::BI__builtin_ia32_roundps:
960 case X86::BI__builtin_ia32_roundpd:
961 case X86::BI__builtin_ia32_roundps256:
962 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
963 case X86::BI__builtin_ia32_roundss:
964 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
965 case X86::BI__builtin_ia32_cmpps:
966 case X86::BI__builtin_ia32_cmpss:
967 case X86::BI__builtin_ia32_cmppd:
968 case X86::BI__builtin_ia32_cmpsd:
969 case X86::BI__builtin_ia32_cmpps256:
970 case X86::BI__builtin_ia32_cmppd256:
971 case X86::BI__builtin_ia32_cmpps512_mask:
972 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +0000973 case X86::BI__builtin_ia32_vpcomub:
974 case X86::BI__builtin_ia32_vpcomuw:
975 case X86::BI__builtin_ia32_vpcomud:
976 case X86::BI__builtin_ia32_vpcomuq:
977 case X86::BI__builtin_ia32_vpcomb:
978 case X86::BI__builtin_ia32_vpcomw:
979 case X86::BI__builtin_ia32_vpcomd:
980 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000981 }
Craig Topperdd84ec52014-12-27 07:00:08 +0000982 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000983}
984
Richard Smith55ce3522012-06-25 20:30:08 +0000985/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
986/// parameter with the FormatAttr's correct format_idx and firstDataArg.
987/// Returns true when the format fits the function and the FormatStringInfo has
988/// been populated.
989bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
990 FormatStringInfo *FSI) {
991 FSI->HasVAListArg = Format->getFirstArg() == 0;
992 FSI->FormatIdx = Format->getFormatIdx() - 1;
993 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000994
Richard Smith55ce3522012-06-25 20:30:08 +0000995 // The way the format attribute works in GCC, the implicit this argument
996 // of member functions is counted. However, it doesn't appear in our own
997 // lists, so decrement format_idx in that case.
998 if (IsCXXMember) {
999 if(FSI->FormatIdx == 0)
1000 return false;
1001 --FSI->FormatIdx;
1002 if (FSI->FirstDataArg != 0)
1003 --FSI->FirstDataArg;
1004 }
1005 return true;
1006}
Mike Stump11289f42009-09-09 15:08:12 +00001007
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001008/// Checks if a the given expression evaluates to null.
1009///
1010/// \brief Returns true if the value evaluates to null.
1011static bool CheckNonNullExpr(Sema &S,
1012 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001013 // As a special case, transparent unions initialized with zero are
1014 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001015 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001016 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1017 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001018 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001019 if (const InitListExpr *ILE =
1020 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001021 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001022 }
1023
1024 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001025 return (!Expr->isValueDependent() &&
1026 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1027 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001028}
1029
1030static void CheckNonNullArgument(Sema &S,
1031 const Expr *ArgExpr,
1032 SourceLocation CallSiteLoc) {
1033 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001034 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
1035}
1036
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001037bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1038 FormatStringInfo FSI;
1039 if ((GetFormatStringType(Format) == FST_NSString) &&
1040 getFormatStringInfo(Format, false, &FSI)) {
1041 Idx = FSI.FormatIdx;
1042 return true;
1043 }
1044 return false;
1045}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001046/// \brief Diagnose use of %s directive in an NSString which is being passed
1047/// as formatting string to formatting method.
1048static void
1049DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1050 const NamedDecl *FDecl,
1051 Expr **Args,
1052 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001053 unsigned Idx = 0;
1054 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001055 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1056 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001057 Idx = 2;
1058 Format = true;
1059 }
1060 else
1061 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1062 if (S.GetFormatNSStringIdx(I, Idx)) {
1063 Format = true;
1064 break;
1065 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001066 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001067 if (!Format || NumArgs <= Idx)
1068 return;
1069 const Expr *FormatExpr = Args[Idx];
1070 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1071 FormatExpr = CSCE->getSubExpr();
1072 const StringLiteral *FormatString;
1073 if (const ObjCStringLiteral *OSL =
1074 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1075 FormatString = OSL->getString();
1076 else
1077 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1078 if (!FormatString)
1079 return;
1080 if (S.FormatStringHasSArg(FormatString)) {
1081 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1082 << "%s" << 1 << 1;
1083 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1084 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001085 }
1086}
1087
Ted Kremenek2bc73332014-01-17 06:24:43 +00001088static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001089 const NamedDecl *FDecl,
Richard Smith588bd9b2014-08-27 04:59:42 +00001090 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001091 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +00001092 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001093 llvm::SmallBitVector NonNullArgs;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001094 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001095 if (!NonNull->args_size()) {
1096 // Easy case: all pointer arguments are nonnull.
1097 for (const auto *Arg : Args)
Hal Finkelee90a222014-09-26 05:04:30 +00001098 if (S.isValidPointerAttrType(Arg->getType()))
Richard Smith588bd9b2014-08-27 04:59:42 +00001099 CheckNonNullArgument(S, Arg, CallSiteLoc);
1100 return;
1101 }
1102
1103 for (unsigned Val : NonNull->args()) {
1104 if (Val >= Args.size())
1105 continue;
1106 if (NonNullArgs.empty())
1107 NonNullArgs.resize(Args.size());
1108 NonNullArgs.set(Val);
1109 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001110 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001111
1112 // Check the attributes on the parameters.
1113 ArrayRef<ParmVarDecl*> parms;
1114 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1115 parms = FD->parameters();
1116 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
1117 parms = MD->parameters();
1118
Richard Smith588bd9b2014-08-27 04:59:42 +00001119 unsigned ArgIndex = 0;
Ted Kremenek9aedc152014-01-17 06:24:56 +00001120 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
Richard Smith588bd9b2014-08-27 04:59:42 +00001121 I != E; ++I, ++ArgIndex) {
Ted Kremenek9aedc152014-01-17 06:24:56 +00001122 const ParmVarDecl *PVD = *I;
Richard Smith588bd9b2014-08-27 04:59:42 +00001123 if (PVD->hasAttr<NonNullAttr>() ||
1124 (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
1125 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek9aedc152014-01-17 06:24:56 +00001126 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001127
1128 // In case this is a variadic call, check any remaining arguments.
1129 for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
1130 if (NonNullArgs[ArgIndex])
1131 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +00001132}
1133
Richard Smith55ce3522012-06-25 20:30:08 +00001134/// Handles the checks for format strings, non-POD arguments to vararg
1135/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00001136void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
1137 unsigned NumParams, bool IsMemberFunction,
1138 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001139 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001140 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001141 if (CurContext->isDependentContext())
1142 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001143
Ted Kremenekb8176da2010-09-09 04:33:05 +00001144 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001145 llvm::SmallBitVector CheckedVarArgs;
1146 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001147 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001148 // Only create vector if there are format attributes.
1149 CheckedVarArgs.resize(Args.size());
1150
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001151 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001152 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001153 }
Richard Smithd7293d72013-08-05 18:49:43 +00001154 }
Richard Smith55ce3522012-06-25 20:30:08 +00001155
1156 // Refuse POD arguments that weren't caught by the format string
1157 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001158 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001159 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001160 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001161 if (const Expr *Arg = Args[ArgIdx]) {
1162 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1163 checkVariadicArgument(Arg, CallType);
1164 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001165 }
Richard Smithd7293d72013-08-05 18:49:43 +00001166 }
Mike Stump11289f42009-09-09 15:08:12 +00001167
Richard Trieu41bc0992013-06-22 00:20:41 +00001168 if (FDecl) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001169 CheckNonNullArguments(*this, FDecl, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001170
Richard Trieu41bc0992013-06-22 00:20:41 +00001171 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001172 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1173 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001174 }
Richard Smith55ce3522012-06-25 20:30:08 +00001175}
1176
1177/// CheckConstructorCall - Check a constructor call for correctness and safety
1178/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001179void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1180 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001181 const FunctionProtoType *Proto,
1182 SourceLocation Loc) {
1183 VariadicCallType CallType =
1184 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +00001185 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +00001186 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
1187}
1188
1189/// CheckFunctionCall - Check a direct function call for various correctness
1190/// and safety properties not strictly enforced by the C type system.
1191bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1192 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001193 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1194 isa<CXXMethodDecl>(FDecl);
1195 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1196 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001197 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1198 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001199 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +00001200 Expr** Args = TheCall->getArgs();
1201 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001202 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001203 // If this is a call to a member operator, hide the first argument
1204 // from checkCall.
1205 // FIXME: Our choice of AST representation here is less than ideal.
1206 ++Args;
1207 --NumArgs;
1208 }
Craig Topper8c2a2a02014-08-30 16:55:39 +00001209 checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +00001210 IsMemberFunction, TheCall->getRParenLoc(),
1211 TheCall->getCallee()->getSourceRange(), CallType);
1212
1213 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1214 // None of the checks below are needed for functions that don't have
1215 // simple names (e.g., C++ conversion functions).
1216 if (!FnInfo)
1217 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001218
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001219 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001220 if (getLangOpts().ObjC1)
1221 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001222
Anna Zaks22122702012-01-17 00:37:07 +00001223 unsigned CMId = FDecl->getMemoryFunctionKind();
1224 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001225 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001226
Anna Zaks201d4892012-01-13 21:52:01 +00001227 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001228 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001229 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001230 else if (CMId == Builtin::BIstrncat)
1231 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001232 else
Anna Zaks22122702012-01-17 00:37:07 +00001233 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001234
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001235 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001236}
1237
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001238bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001239 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001240 VariadicCallType CallType =
1241 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001242
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001243 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +00001244 /*IsMemberFunction=*/false,
1245 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001246
1247 return false;
1248}
1249
Richard Trieu664c4c62013-06-20 21:03:13 +00001250bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1251 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001252 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
1253 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001254 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001255
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001256 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +00001257 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001258 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001259
Richard Trieu664c4c62013-06-20 21:03:13 +00001260 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001261 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001262 CallType = VariadicDoesNotApply;
1263 } else if (Ty->isBlockPointerType()) {
1264 CallType = VariadicBlock;
1265 } else { // Ty->isFunctionPointerType()
1266 CallType = VariadicFunction;
1267 }
Alp Toker9cacbab2014-01-20 20:26:09 +00001268 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001269
Craig Topper8c2a2a02014-08-30 16:55:39 +00001270 checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
1271 TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001272 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001273 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001274
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001275 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001276}
1277
Richard Trieu41bc0992013-06-22 00:20:41 +00001278/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1279/// such as function pointers returned from functions.
1280bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001281 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001282 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001283 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +00001284
Craig Topperc3ec1492014-05-26 06:22:03 +00001285 checkCall(/*FDecl=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001286 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001287 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001288 TheCall->getCallee()->getSourceRange(), CallType);
1289
1290 return false;
1291}
1292
Tim Northovere94a34c2014-03-11 10:49:14 +00001293static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1294 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1295 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1296 return false;
1297
1298 switch (Op) {
1299 case AtomicExpr::AO__c11_atomic_init:
1300 llvm_unreachable("There is no ordering argument for an init");
1301
1302 case AtomicExpr::AO__c11_atomic_load:
1303 case AtomicExpr::AO__atomic_load_n:
1304 case AtomicExpr::AO__atomic_load:
1305 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1306 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1307
1308 case AtomicExpr::AO__c11_atomic_store:
1309 case AtomicExpr::AO__atomic_store:
1310 case AtomicExpr::AO__atomic_store_n:
1311 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1312 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1313 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1314
1315 default:
1316 return true;
1317 }
1318}
1319
Richard Smithfeea8832012-04-12 05:08:17 +00001320ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1321 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001322 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1323 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001324
Richard Smithfeea8832012-04-12 05:08:17 +00001325 // All these operations take one of the following forms:
1326 enum {
1327 // C __c11_atomic_init(A *, C)
1328 Init,
1329 // C __c11_atomic_load(A *, int)
1330 Load,
1331 // void __atomic_load(A *, CP, int)
1332 Copy,
1333 // C __c11_atomic_add(A *, M, int)
1334 Arithmetic,
1335 // C __atomic_exchange_n(A *, CP, int)
1336 Xchg,
1337 // void __atomic_exchange(A *, C *, CP, int)
1338 GNUXchg,
1339 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1340 C11CmpXchg,
1341 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1342 GNUCmpXchg
1343 } Form = Init;
1344 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1345 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1346 // where:
1347 // C is an appropriate type,
1348 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1349 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1350 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1351 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001352
Gabor Horvath98bd0982015-03-16 09:59:54 +00001353 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1354 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1355 AtomicExpr::AO__atomic_load,
1356 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00001357 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1358 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1359 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1360 Op == AtomicExpr::AO__atomic_store_n ||
1361 Op == AtomicExpr::AO__atomic_exchange_n ||
1362 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1363 bool IsAddSub = false;
1364
1365 switch (Op) {
1366 case AtomicExpr::AO__c11_atomic_init:
1367 Form = Init;
1368 break;
1369
1370 case AtomicExpr::AO__c11_atomic_load:
1371 case AtomicExpr::AO__atomic_load_n:
1372 Form = Load;
1373 break;
1374
1375 case AtomicExpr::AO__c11_atomic_store:
1376 case AtomicExpr::AO__atomic_load:
1377 case AtomicExpr::AO__atomic_store:
1378 case AtomicExpr::AO__atomic_store_n:
1379 Form = Copy;
1380 break;
1381
1382 case AtomicExpr::AO__c11_atomic_fetch_add:
1383 case AtomicExpr::AO__c11_atomic_fetch_sub:
1384 case AtomicExpr::AO__atomic_fetch_add:
1385 case AtomicExpr::AO__atomic_fetch_sub:
1386 case AtomicExpr::AO__atomic_add_fetch:
1387 case AtomicExpr::AO__atomic_sub_fetch:
1388 IsAddSub = true;
1389 // Fall through.
1390 case AtomicExpr::AO__c11_atomic_fetch_and:
1391 case AtomicExpr::AO__c11_atomic_fetch_or:
1392 case AtomicExpr::AO__c11_atomic_fetch_xor:
1393 case AtomicExpr::AO__atomic_fetch_and:
1394 case AtomicExpr::AO__atomic_fetch_or:
1395 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001396 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001397 case AtomicExpr::AO__atomic_and_fetch:
1398 case AtomicExpr::AO__atomic_or_fetch:
1399 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001400 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001401 Form = Arithmetic;
1402 break;
1403
1404 case AtomicExpr::AO__c11_atomic_exchange:
1405 case AtomicExpr::AO__atomic_exchange_n:
1406 Form = Xchg;
1407 break;
1408
1409 case AtomicExpr::AO__atomic_exchange:
1410 Form = GNUXchg;
1411 break;
1412
1413 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1414 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1415 Form = C11CmpXchg;
1416 break;
1417
1418 case AtomicExpr::AO__atomic_compare_exchange:
1419 case AtomicExpr::AO__atomic_compare_exchange_n:
1420 Form = GNUCmpXchg;
1421 break;
1422 }
1423
1424 // Check we have the right number of arguments.
1425 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001426 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001427 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001428 << TheCall->getCallee()->getSourceRange();
1429 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001430 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1431 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001432 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001433 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001434 << TheCall->getCallee()->getSourceRange();
1435 return ExprError();
1436 }
1437
Richard Smithfeea8832012-04-12 05:08:17 +00001438 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001439 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001440 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1441 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1442 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001443 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001444 << Ptr->getType() << Ptr->getSourceRange();
1445 return ExprError();
1446 }
1447
Richard Smithfeea8832012-04-12 05:08:17 +00001448 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1449 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1450 QualType ValType = AtomTy; // 'C'
1451 if (IsC11) {
1452 if (!AtomTy->isAtomicType()) {
1453 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1454 << Ptr->getType() << Ptr->getSourceRange();
1455 return ExprError();
1456 }
Richard Smithe00921a2012-09-15 06:09:58 +00001457 if (AtomTy.isConstQualified()) {
1458 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1459 << Ptr->getType() << Ptr->getSourceRange();
1460 return ExprError();
1461 }
Richard Smithfeea8832012-04-12 05:08:17 +00001462 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001463 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001464
Richard Smithfeea8832012-04-12 05:08:17 +00001465 // For an arithmetic operation, the implied arithmetic must be well-formed.
1466 if (Form == Arithmetic) {
1467 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1468 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1469 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1470 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1471 return ExprError();
1472 }
1473 if (!IsAddSub && !ValType->isIntegerType()) {
1474 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1475 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1476 return ExprError();
1477 }
David Majnemere85cff82015-01-28 05:48:06 +00001478 if (IsC11 && ValType->isPointerType() &&
1479 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1480 diag::err_incomplete_type)) {
1481 return ExprError();
1482 }
Richard Smithfeea8832012-04-12 05:08:17 +00001483 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1484 // For __atomic_*_n operations, the value type must be a scalar integral or
1485 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001486 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001487 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1488 return ExprError();
1489 }
1490
Eli Friedmanaa769812013-09-11 03:49:34 +00001491 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1492 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001493 // For GNU atomics, require a trivially-copyable type. This is not part of
1494 // the GNU atomics specification, but we enforce it for sanity.
1495 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001496 << Ptr->getType() << Ptr->getSourceRange();
1497 return ExprError();
1498 }
1499
Richard Smithfeea8832012-04-12 05:08:17 +00001500 // FIXME: For any builtin other than a load, the ValType must not be
1501 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001502
1503 switch (ValType.getObjCLifetime()) {
1504 case Qualifiers::OCL_None:
1505 case Qualifiers::OCL_ExplicitNone:
1506 // okay
1507 break;
1508
1509 case Qualifiers::OCL_Weak:
1510 case Qualifiers::OCL_Strong:
1511 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001512 // FIXME: Can this happen? By this point, ValType should be known
1513 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001514 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1515 << ValType << Ptr->getSourceRange();
1516 return ExprError();
1517 }
1518
1519 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001520 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001521 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001522 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001523 ResultType = Context.BoolTy;
1524
Richard Smithfeea8832012-04-12 05:08:17 +00001525 // The type of a parameter passed 'by value'. In the GNU atomics, such
1526 // arguments are actually passed as pointers.
1527 QualType ByValType = ValType; // 'CP'
1528 if (!IsC11 && !IsN)
1529 ByValType = Ptr->getType();
1530
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001531 // The first argument --- the pointer --- has a fixed type; we
1532 // deduce the types of the rest of the arguments accordingly. Walk
1533 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001534 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001535 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001536 if (i < NumVals[Form] + 1) {
1537 switch (i) {
1538 case 1:
1539 // The second argument is the non-atomic operand. For arithmetic, this
1540 // is always passed by value, and for a compare_exchange it is always
1541 // passed by address. For the rest, GNU uses by-address and C11 uses
1542 // by-value.
1543 assert(Form != Load);
1544 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1545 Ty = ValType;
1546 else if (Form == Copy || Form == Xchg)
1547 Ty = ByValType;
1548 else if (Form == Arithmetic)
1549 Ty = Context.getPointerDiffType();
1550 else
1551 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1552 break;
1553 case 2:
1554 // The third argument to compare_exchange / GNU exchange is a
1555 // (pointer to a) desired value.
1556 Ty = ByValType;
1557 break;
1558 case 3:
1559 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1560 Ty = Context.BoolTy;
1561 break;
1562 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001563 } else {
1564 // The order(s) are always converted to int.
1565 Ty = Context.IntTy;
1566 }
Richard Smithfeea8832012-04-12 05:08:17 +00001567
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001568 InitializedEntity Entity =
1569 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001570 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001571 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1572 if (Arg.isInvalid())
1573 return true;
1574 TheCall->setArg(i, Arg.get());
1575 }
1576
Richard Smithfeea8832012-04-12 05:08:17 +00001577 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001578 SmallVector<Expr*, 5> SubExprs;
1579 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001580 switch (Form) {
1581 case Init:
1582 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001583 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001584 break;
1585 case Load:
1586 SubExprs.push_back(TheCall->getArg(1)); // Order
1587 break;
1588 case Copy:
1589 case Arithmetic:
1590 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001591 SubExprs.push_back(TheCall->getArg(2)); // Order
1592 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001593 break;
1594 case GNUXchg:
1595 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1596 SubExprs.push_back(TheCall->getArg(3)); // Order
1597 SubExprs.push_back(TheCall->getArg(1)); // Val1
1598 SubExprs.push_back(TheCall->getArg(2)); // Val2
1599 break;
1600 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001601 SubExprs.push_back(TheCall->getArg(3)); // Order
1602 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001603 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001604 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001605 break;
1606 case GNUCmpXchg:
1607 SubExprs.push_back(TheCall->getArg(4)); // Order
1608 SubExprs.push_back(TheCall->getArg(1)); // Val1
1609 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1610 SubExprs.push_back(TheCall->getArg(2)); // Val2
1611 SubExprs.push_back(TheCall->getArg(3)); // Weak
1612 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001613 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001614
1615 if (SubExprs.size() >= 2 && Form != Init) {
1616 llvm::APSInt Result(32);
1617 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1618 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001619 Diag(SubExprs[1]->getLocStart(),
1620 diag::warn_atomic_op_has_invalid_memory_order)
1621 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001622 }
1623
Fariborz Jahanian615de762013-05-28 17:37:39 +00001624 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1625 SubExprs, ResultType, Op,
1626 TheCall->getRParenLoc());
1627
1628 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1629 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1630 Context.AtomicUsesUnsupportedLibcall(AE))
1631 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1632 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001633
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001634 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001635}
1636
1637
John McCall29ad95b2011-08-27 01:09:30 +00001638/// checkBuiltinArgument - Given a call to a builtin function, perform
1639/// normal type-checking on the given argument, updating the call in
1640/// place. This is useful when a builtin function requires custom
1641/// type-checking for some of its arguments but not necessarily all of
1642/// them.
1643///
1644/// Returns true on error.
1645static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1646 FunctionDecl *Fn = E->getDirectCallee();
1647 assert(Fn && "builtin call without direct callee!");
1648
1649 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1650 InitializedEntity Entity =
1651 InitializedEntity::InitializeParameter(S.Context, Param);
1652
1653 ExprResult Arg = E->getArg(0);
1654 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1655 if (Arg.isInvalid())
1656 return true;
1657
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001658 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001659 return false;
1660}
1661
Chris Lattnerdc046542009-05-08 06:58:22 +00001662/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1663/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1664/// type of its first argument. The main ActOnCallExpr routines have already
1665/// promoted the types of arguments because all of these calls are prototyped as
1666/// void(...).
1667///
1668/// This function goes through and does final semantic checking for these
1669/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001670ExprResult
1671Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001672 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001673 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1674 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1675
1676 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001677 if (TheCall->getNumArgs() < 1) {
1678 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1679 << 0 << 1 << TheCall->getNumArgs()
1680 << TheCall->getCallee()->getSourceRange();
1681 return ExprError();
1682 }
Mike Stump11289f42009-09-09 15:08:12 +00001683
Chris Lattnerdc046542009-05-08 06:58:22 +00001684 // Inspect the first argument of the atomic builtin. This should always be
1685 // a pointer type, whose element is an integral scalar or pointer type.
1686 // Because it is a pointer type, we don't have to worry about any implicit
1687 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001688 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001689 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001690 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1691 if (FirstArgResult.isInvalid())
1692 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001693 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001694 TheCall->setArg(0, FirstArg);
1695
John McCall31168b02011-06-15 23:02:42 +00001696 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1697 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001698 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1699 << FirstArg->getType() << FirstArg->getSourceRange();
1700 return ExprError();
1701 }
Mike Stump11289f42009-09-09 15:08:12 +00001702
John McCall31168b02011-06-15 23:02:42 +00001703 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001704 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001705 !ValType->isBlockPointerType()) {
1706 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1707 << FirstArg->getType() << FirstArg->getSourceRange();
1708 return ExprError();
1709 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001710
John McCall31168b02011-06-15 23:02:42 +00001711 switch (ValType.getObjCLifetime()) {
1712 case Qualifiers::OCL_None:
1713 case Qualifiers::OCL_ExplicitNone:
1714 // okay
1715 break;
1716
1717 case Qualifiers::OCL_Weak:
1718 case Qualifiers::OCL_Strong:
1719 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001720 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001721 << ValType << FirstArg->getSourceRange();
1722 return ExprError();
1723 }
1724
John McCallb50451a2011-10-05 07:41:44 +00001725 // Strip any qualifiers off ValType.
1726 ValType = ValType.getUnqualifiedType();
1727
Chandler Carruth3973af72010-07-18 20:54:12 +00001728 // The majority of builtins return a value, but a few have special return
1729 // types, so allow them to override appropriately below.
1730 QualType ResultType = ValType;
1731
Chris Lattnerdc046542009-05-08 06:58:22 +00001732 // We need to figure out which concrete builtin this maps onto. For example,
1733 // __sync_fetch_and_add with a 2 byte object turns into
1734 // __sync_fetch_and_add_2.
1735#define BUILTIN_ROW(x) \
1736 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1737 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001738
Chris Lattnerdc046542009-05-08 06:58:22 +00001739 static const unsigned BuiltinIndices[][5] = {
1740 BUILTIN_ROW(__sync_fetch_and_add),
1741 BUILTIN_ROW(__sync_fetch_and_sub),
1742 BUILTIN_ROW(__sync_fetch_and_or),
1743 BUILTIN_ROW(__sync_fetch_and_and),
1744 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00001745 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00001746
Chris Lattnerdc046542009-05-08 06:58:22 +00001747 BUILTIN_ROW(__sync_add_and_fetch),
1748 BUILTIN_ROW(__sync_sub_and_fetch),
1749 BUILTIN_ROW(__sync_and_and_fetch),
1750 BUILTIN_ROW(__sync_or_and_fetch),
1751 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00001752 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001753
Chris Lattnerdc046542009-05-08 06:58:22 +00001754 BUILTIN_ROW(__sync_val_compare_and_swap),
1755 BUILTIN_ROW(__sync_bool_compare_and_swap),
1756 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001757 BUILTIN_ROW(__sync_lock_release),
1758 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001759 };
Mike Stump11289f42009-09-09 15:08:12 +00001760#undef BUILTIN_ROW
1761
Chris Lattnerdc046542009-05-08 06:58:22 +00001762 // Determine the index of the size.
1763 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001764 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001765 case 1: SizeIndex = 0; break;
1766 case 2: SizeIndex = 1; break;
1767 case 4: SizeIndex = 2; break;
1768 case 8: SizeIndex = 3; break;
1769 case 16: SizeIndex = 4; break;
1770 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001771 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1772 << FirstArg->getType() << FirstArg->getSourceRange();
1773 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001774 }
Mike Stump11289f42009-09-09 15:08:12 +00001775
Chris Lattnerdc046542009-05-08 06:58:22 +00001776 // Each of these builtins has one pointer argument, followed by some number of
1777 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1778 // that we ignore. Find out which row of BuiltinIndices to read from as well
1779 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001780 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001781 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00001782 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00001783 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001784 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001785 case Builtin::BI__sync_fetch_and_add:
1786 case Builtin::BI__sync_fetch_and_add_1:
1787 case Builtin::BI__sync_fetch_and_add_2:
1788 case Builtin::BI__sync_fetch_and_add_4:
1789 case Builtin::BI__sync_fetch_and_add_8:
1790 case Builtin::BI__sync_fetch_and_add_16:
1791 BuiltinIndex = 0;
1792 break;
1793
1794 case Builtin::BI__sync_fetch_and_sub:
1795 case Builtin::BI__sync_fetch_and_sub_1:
1796 case Builtin::BI__sync_fetch_and_sub_2:
1797 case Builtin::BI__sync_fetch_and_sub_4:
1798 case Builtin::BI__sync_fetch_and_sub_8:
1799 case Builtin::BI__sync_fetch_and_sub_16:
1800 BuiltinIndex = 1;
1801 break;
1802
1803 case Builtin::BI__sync_fetch_and_or:
1804 case Builtin::BI__sync_fetch_and_or_1:
1805 case Builtin::BI__sync_fetch_and_or_2:
1806 case Builtin::BI__sync_fetch_and_or_4:
1807 case Builtin::BI__sync_fetch_and_or_8:
1808 case Builtin::BI__sync_fetch_and_or_16:
1809 BuiltinIndex = 2;
1810 break;
1811
1812 case Builtin::BI__sync_fetch_and_and:
1813 case Builtin::BI__sync_fetch_and_and_1:
1814 case Builtin::BI__sync_fetch_and_and_2:
1815 case Builtin::BI__sync_fetch_and_and_4:
1816 case Builtin::BI__sync_fetch_and_and_8:
1817 case Builtin::BI__sync_fetch_and_and_16:
1818 BuiltinIndex = 3;
1819 break;
Mike Stump11289f42009-09-09 15:08:12 +00001820
Douglas Gregor73722482011-11-28 16:30:08 +00001821 case Builtin::BI__sync_fetch_and_xor:
1822 case Builtin::BI__sync_fetch_and_xor_1:
1823 case Builtin::BI__sync_fetch_and_xor_2:
1824 case Builtin::BI__sync_fetch_and_xor_4:
1825 case Builtin::BI__sync_fetch_and_xor_8:
1826 case Builtin::BI__sync_fetch_and_xor_16:
1827 BuiltinIndex = 4;
1828 break;
1829
Hal Finkeld2208b52014-10-02 20:53:50 +00001830 case Builtin::BI__sync_fetch_and_nand:
1831 case Builtin::BI__sync_fetch_and_nand_1:
1832 case Builtin::BI__sync_fetch_and_nand_2:
1833 case Builtin::BI__sync_fetch_and_nand_4:
1834 case Builtin::BI__sync_fetch_and_nand_8:
1835 case Builtin::BI__sync_fetch_and_nand_16:
1836 BuiltinIndex = 5;
1837 WarnAboutSemanticsChange = true;
1838 break;
1839
Douglas Gregor73722482011-11-28 16:30:08 +00001840 case Builtin::BI__sync_add_and_fetch:
1841 case Builtin::BI__sync_add_and_fetch_1:
1842 case Builtin::BI__sync_add_and_fetch_2:
1843 case Builtin::BI__sync_add_and_fetch_4:
1844 case Builtin::BI__sync_add_and_fetch_8:
1845 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001846 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00001847 break;
1848
1849 case Builtin::BI__sync_sub_and_fetch:
1850 case Builtin::BI__sync_sub_and_fetch_1:
1851 case Builtin::BI__sync_sub_and_fetch_2:
1852 case Builtin::BI__sync_sub_and_fetch_4:
1853 case Builtin::BI__sync_sub_and_fetch_8:
1854 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001855 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00001856 break;
1857
1858 case Builtin::BI__sync_and_and_fetch:
1859 case Builtin::BI__sync_and_and_fetch_1:
1860 case Builtin::BI__sync_and_and_fetch_2:
1861 case Builtin::BI__sync_and_and_fetch_4:
1862 case Builtin::BI__sync_and_and_fetch_8:
1863 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001864 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00001865 break;
1866
1867 case Builtin::BI__sync_or_and_fetch:
1868 case Builtin::BI__sync_or_and_fetch_1:
1869 case Builtin::BI__sync_or_and_fetch_2:
1870 case Builtin::BI__sync_or_and_fetch_4:
1871 case Builtin::BI__sync_or_and_fetch_8:
1872 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001873 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00001874 break;
1875
1876 case Builtin::BI__sync_xor_and_fetch:
1877 case Builtin::BI__sync_xor_and_fetch_1:
1878 case Builtin::BI__sync_xor_and_fetch_2:
1879 case Builtin::BI__sync_xor_and_fetch_4:
1880 case Builtin::BI__sync_xor_and_fetch_8:
1881 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001882 BuiltinIndex = 10;
1883 break;
1884
1885 case Builtin::BI__sync_nand_and_fetch:
1886 case Builtin::BI__sync_nand_and_fetch_1:
1887 case Builtin::BI__sync_nand_and_fetch_2:
1888 case Builtin::BI__sync_nand_and_fetch_4:
1889 case Builtin::BI__sync_nand_and_fetch_8:
1890 case Builtin::BI__sync_nand_and_fetch_16:
1891 BuiltinIndex = 11;
1892 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00001893 break;
Mike Stump11289f42009-09-09 15:08:12 +00001894
Chris Lattnerdc046542009-05-08 06:58:22 +00001895 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001896 case Builtin::BI__sync_val_compare_and_swap_1:
1897 case Builtin::BI__sync_val_compare_and_swap_2:
1898 case Builtin::BI__sync_val_compare_and_swap_4:
1899 case Builtin::BI__sync_val_compare_and_swap_8:
1900 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001901 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00001902 NumFixed = 2;
1903 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001904
Chris Lattnerdc046542009-05-08 06:58:22 +00001905 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001906 case Builtin::BI__sync_bool_compare_and_swap_1:
1907 case Builtin::BI__sync_bool_compare_and_swap_2:
1908 case Builtin::BI__sync_bool_compare_and_swap_4:
1909 case Builtin::BI__sync_bool_compare_and_swap_8:
1910 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001911 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001912 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001913 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001914 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001915
1916 case Builtin::BI__sync_lock_test_and_set:
1917 case Builtin::BI__sync_lock_test_and_set_1:
1918 case Builtin::BI__sync_lock_test_and_set_2:
1919 case Builtin::BI__sync_lock_test_and_set_4:
1920 case Builtin::BI__sync_lock_test_and_set_8:
1921 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001922 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00001923 break;
1924
Chris Lattnerdc046542009-05-08 06:58:22 +00001925 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001926 case Builtin::BI__sync_lock_release_1:
1927 case Builtin::BI__sync_lock_release_2:
1928 case Builtin::BI__sync_lock_release_4:
1929 case Builtin::BI__sync_lock_release_8:
1930 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001931 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00001932 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001933 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001934 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001935
1936 case Builtin::BI__sync_swap:
1937 case Builtin::BI__sync_swap_1:
1938 case Builtin::BI__sync_swap_2:
1939 case Builtin::BI__sync_swap_4:
1940 case Builtin::BI__sync_swap_8:
1941 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001942 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00001943 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001944 }
Mike Stump11289f42009-09-09 15:08:12 +00001945
Chris Lattnerdc046542009-05-08 06:58:22 +00001946 // Now that we know how many fixed arguments we expect, first check that we
1947 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001948 if (TheCall->getNumArgs() < 1+NumFixed) {
1949 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1950 << 0 << 1+NumFixed << TheCall->getNumArgs()
1951 << TheCall->getCallee()->getSourceRange();
1952 return ExprError();
1953 }
Mike Stump11289f42009-09-09 15:08:12 +00001954
Hal Finkeld2208b52014-10-02 20:53:50 +00001955 if (WarnAboutSemanticsChange) {
1956 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
1957 << TheCall->getCallee()->getSourceRange();
1958 }
1959
Chris Lattner5b9241b2009-05-08 15:36:58 +00001960 // Get the decl for the concrete builtin from this, we can tell what the
1961 // concrete integer type we should convert to is.
1962 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1963 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001964 FunctionDecl *NewBuiltinDecl;
1965 if (NewBuiltinID == BuiltinID)
1966 NewBuiltinDecl = FDecl;
1967 else {
1968 // Perform builtin lookup to avoid redeclaring it.
1969 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1970 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1971 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1972 assert(Res.getFoundDecl());
1973 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00001974 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001975 return ExprError();
1976 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001977
John McCallcf142162010-08-07 06:22:56 +00001978 // The first argument --- the pointer --- has a fixed type; we
1979 // deduce the types of the rest of the arguments accordingly. Walk
1980 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001981 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001982 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001983
Chris Lattnerdc046542009-05-08 06:58:22 +00001984 // GCC does an implicit conversion to the pointer or integer ValType. This
1985 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001986 // Initialize the argument.
1987 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1988 ValType, /*consume*/ false);
1989 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001990 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001991 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001992
Chris Lattnerdc046542009-05-08 06:58:22 +00001993 // Okay, we have something that *can* be converted to the right type. Check
1994 // to see if there is a potentially weird extension going on here. This can
1995 // happen when you do an atomic operation on something like an char* and
1996 // pass in 42. The 42 gets converted to char. This is even more strange
1997 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001998 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001999 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002000 }
Mike Stump11289f42009-09-09 15:08:12 +00002001
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002002 ASTContext& Context = this->getASTContext();
2003
2004 // Create a new DeclRefExpr to refer to the new decl.
2005 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2006 Context,
2007 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002008 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002009 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002010 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002011 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002012 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002013 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002014
Chris Lattnerdc046542009-05-08 06:58:22 +00002015 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002016 // FIXME: This loses syntactic information.
2017 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2018 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2019 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002020 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002021
Chandler Carruthbc8cab12010-07-18 07:23:17 +00002022 // Change the result type of the call to match the original value type. This
2023 // is arbitrary, but the codegen for these builtins ins design to handle it
2024 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00002025 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002026
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002027 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002028}
2029
Chris Lattner6436fb62009-02-18 06:01:06 +00002030/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002031/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002032/// Note: It might also make sense to do the UTF-16 conversion here (would
2033/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002034bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002035 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002036 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2037
Douglas Gregorfb65e592011-07-27 05:40:30 +00002038 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002039 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2040 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002041 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002042 }
Mike Stump11289f42009-09-09 15:08:12 +00002043
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002044 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002045 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002046 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002047 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002048 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002049 UTF16 *ToPtr = &ToBuf[0];
2050
2051 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2052 &ToPtr, ToPtr + NumBytes,
2053 strictConversion);
2054 // Check for conversion failure.
2055 if (Result != conversionOK)
2056 Diag(Arg->getLocStart(),
2057 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2058 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002059 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002060}
2061
Chris Lattnere202e6a2007-12-20 00:05:45 +00002062/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
2063/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00002064bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2065 Expr *Fn = TheCall->getCallee();
2066 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002067 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002068 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002069 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2070 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002071 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002072 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002073 return true;
2074 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002075
2076 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002077 return Diag(TheCall->getLocEnd(),
2078 diag::err_typecheck_call_too_few_args_at_least)
2079 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002080 }
2081
John McCall29ad95b2011-08-27 01:09:30 +00002082 // Type-check the first argument normally.
2083 if (checkBuiltinArgument(*this, TheCall, 0))
2084 return true;
2085
Chris Lattnere202e6a2007-12-20 00:05:45 +00002086 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002087 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002088 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002089 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002090 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002091 else if (FunctionDecl *FD = getCurFunctionDecl())
2092 isVariadic = FD->isVariadic();
2093 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002094 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002095
Chris Lattnere202e6a2007-12-20 00:05:45 +00002096 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002097 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2098 return true;
2099 }
Mike Stump11289f42009-09-09 15:08:12 +00002100
Chris Lattner43be2e62007-12-19 23:59:04 +00002101 // Verify that the second argument to the builtin is the last argument of the
2102 // current function or method.
2103 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002104 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002105
Nico Weber9eea7642013-05-24 23:31:57 +00002106 // These are valid if SecondArgIsLastNamedArgument is false after the next
2107 // block.
2108 QualType Type;
2109 SourceLocation ParamLoc;
2110
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002111 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2112 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002113 // FIXME: This isn't correct for methods (results in bogus warning).
2114 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002115 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002116 if (CurBlock)
2117 LastArg = *(CurBlock->TheDecl->param_end()-1);
2118 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002119 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002120 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002121 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002122 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002123
2124 Type = PV->getType();
2125 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002126 }
2127 }
Mike Stump11289f42009-09-09 15:08:12 +00002128
Chris Lattner43be2e62007-12-19 23:59:04 +00002129 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002130 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002131 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002132 else if (Type->isReferenceType()) {
2133 Diag(Arg->getLocStart(),
2134 diag::warn_va_start_of_reference_type_is_undefined);
2135 Diag(ParamLoc, diag::note_parameter_type) << Type;
2136 }
2137
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002138 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002139 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002140}
Chris Lattner43be2e62007-12-19 23:59:04 +00002141
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002142bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2143 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2144 // const char *named_addr);
2145
2146 Expr *Func = Call->getCallee();
2147
2148 if (Call->getNumArgs() < 3)
2149 return Diag(Call->getLocEnd(),
2150 diag::err_typecheck_call_too_few_args_at_least)
2151 << 0 /*function call*/ << 3 << Call->getNumArgs();
2152
2153 // Determine whether the current function is variadic or not.
2154 bool IsVariadic;
2155 if (BlockScopeInfo *CurBlock = getCurBlock())
2156 IsVariadic = CurBlock->TheDecl->isVariadic();
2157 else if (FunctionDecl *FD = getCurFunctionDecl())
2158 IsVariadic = FD->isVariadic();
2159 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2160 IsVariadic = MD->isVariadic();
2161 else
2162 llvm_unreachable("unexpected statement type");
2163
2164 if (!IsVariadic) {
2165 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2166 return true;
2167 }
2168
2169 // Type-check the first argument normally.
2170 if (checkBuiltinArgument(*this, Call, 0))
2171 return true;
2172
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002173 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002174 unsigned ArgNo;
2175 QualType Type;
2176 } ArgumentTypes[] = {
2177 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2178 { 2, Context.getSizeType() },
2179 };
2180
2181 for (const auto &AT : ArgumentTypes) {
2182 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2183 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2184 continue;
2185 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2186 << Arg->getType() << AT.Type << 1 /* different class */
2187 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2188 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2189 }
2190
2191 return false;
2192}
2193
Chris Lattner2da14fb2007-12-20 00:26:33 +00002194/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2195/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002196bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2197 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002198 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002199 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002200 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002201 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002202 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002203 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002204 << SourceRange(TheCall->getArg(2)->getLocStart(),
2205 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002206
John Wiegley01296292011-04-08 18:41:53 +00002207 ExprResult OrigArg0 = TheCall->getArg(0);
2208 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002209
Chris Lattner2da14fb2007-12-20 00:26:33 +00002210 // Do standard promotions between the two arguments, returning their common
2211 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002212 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002213 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2214 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002215
2216 // Make sure any conversions are pushed back into the call; this is
2217 // type safe since unordered compare builtins are declared as "_Bool
2218 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002219 TheCall->setArg(0, OrigArg0.get());
2220 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002221
John Wiegley01296292011-04-08 18:41:53 +00002222 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002223 return false;
2224
Chris Lattner2da14fb2007-12-20 00:26:33 +00002225 // If the common type isn't a real floating type, then the arguments were
2226 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002227 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002228 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002229 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002230 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2231 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002232
Chris Lattner2da14fb2007-12-20 00:26:33 +00002233 return false;
2234}
2235
Benjamin Kramer634fc102010-02-15 22:42:31 +00002236/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2237/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002238/// to check everything. We expect the last argument to be a floating point
2239/// value.
2240bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2241 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002242 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002243 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002244 if (TheCall->getNumArgs() > NumArgs)
2245 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002246 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002247 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002248 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002249 (*(TheCall->arg_end()-1))->getLocEnd());
2250
Benjamin Kramer64aae502010-02-16 10:07:31 +00002251 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002252
Eli Friedman7e4faac2009-08-31 20:06:00 +00002253 if (OrigArg->isTypeDependent())
2254 return false;
2255
Chris Lattner68784ef2010-05-06 05:50:07 +00002256 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002257 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002258 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002259 diag::err_typecheck_call_invalid_unary_fp)
2260 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002261
Chris Lattner68784ef2010-05-06 05:50:07 +00002262 // If this is an implicit conversion from float -> double, remove it.
2263 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2264 Expr *CastArg = Cast->getSubExpr();
2265 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2266 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2267 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002268 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002269 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002270 }
2271 }
2272
Eli Friedman7e4faac2009-08-31 20:06:00 +00002273 return false;
2274}
2275
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002276/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2277// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002278ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002279 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002280 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002281 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002282 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2283 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002284
Nate Begemana0110022010-06-08 00:16:34 +00002285 // Determine which of the following types of shufflevector we're checking:
2286 // 1) unary, vector mask: (lhs, mask)
2287 // 2) binary, vector mask: (lhs, rhs, mask)
2288 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2289 QualType resType = TheCall->getArg(0)->getType();
2290 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002291
Douglas Gregorc25f7662009-05-19 22:10:17 +00002292 if (!TheCall->getArg(0)->isTypeDependent() &&
2293 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002294 QualType LHSType = TheCall->getArg(0)->getType();
2295 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002296
Craig Topperbaca3892013-07-29 06:47:04 +00002297 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2298 return ExprError(Diag(TheCall->getLocStart(),
2299 diag::err_shufflevector_non_vector)
2300 << SourceRange(TheCall->getArg(0)->getLocStart(),
2301 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002302
Nate Begemana0110022010-06-08 00:16:34 +00002303 numElements = LHSType->getAs<VectorType>()->getNumElements();
2304 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002305
Nate Begemana0110022010-06-08 00:16:34 +00002306 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2307 // with mask. If so, verify that RHS is an integer vector type with the
2308 // same number of elts as lhs.
2309 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002310 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002311 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002312 return ExprError(Diag(TheCall->getLocStart(),
2313 diag::err_shufflevector_incompatible_vector)
2314 << SourceRange(TheCall->getArg(1)->getLocStart(),
2315 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002316 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002317 return ExprError(Diag(TheCall->getLocStart(),
2318 diag::err_shufflevector_incompatible_vector)
2319 << SourceRange(TheCall->getArg(0)->getLocStart(),
2320 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002321 } else if (numElements != numResElements) {
2322 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002323 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002324 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002325 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002326 }
2327
2328 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002329 if (TheCall->getArg(i)->isTypeDependent() ||
2330 TheCall->getArg(i)->isValueDependent())
2331 continue;
2332
Nate Begemana0110022010-06-08 00:16:34 +00002333 llvm::APSInt Result(32);
2334 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2335 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002336 diag::err_shufflevector_nonconstant_argument)
2337 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002338
Craig Topper50ad5b72013-08-03 17:40:38 +00002339 // Allow -1 which will be translated to undef in the IR.
2340 if (Result.isSigned() && Result.isAllOnesValue())
2341 continue;
2342
Chris Lattner7ab824e2008-08-10 02:05:13 +00002343 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002344 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002345 diag::err_shufflevector_argument_too_large)
2346 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002347 }
2348
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002349 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002350
Chris Lattner7ab824e2008-08-10 02:05:13 +00002351 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002352 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002353 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002354 }
2355
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002356 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2357 TheCall->getCallee()->getLocStart(),
2358 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002359}
Chris Lattner43be2e62007-12-19 23:59:04 +00002360
Hal Finkelc4d7c822013-09-18 03:29:45 +00002361/// SemaConvertVectorExpr - Handle __builtin_convertvector
2362ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2363 SourceLocation BuiltinLoc,
2364 SourceLocation RParenLoc) {
2365 ExprValueKind VK = VK_RValue;
2366 ExprObjectKind OK = OK_Ordinary;
2367 QualType DstTy = TInfo->getType();
2368 QualType SrcTy = E->getType();
2369
2370 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2371 return ExprError(Diag(BuiltinLoc,
2372 diag::err_convertvector_non_vector)
2373 << E->getSourceRange());
2374 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2375 return ExprError(Diag(BuiltinLoc,
2376 diag::err_convertvector_non_vector_type));
2377
2378 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2379 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2380 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2381 if (SrcElts != DstElts)
2382 return ExprError(Diag(BuiltinLoc,
2383 diag::err_convertvector_incompatible_vector)
2384 << E->getSourceRange());
2385 }
2386
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002387 return new (Context)
2388 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002389}
2390
Daniel Dunbarb7257262008-07-21 22:59:13 +00002391/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2392// This is declared to take (const void*, ...) and can take two
2393// optional constant int args.
2394bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002395 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002396
Chris Lattner3b054132008-11-19 05:08:23 +00002397 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002398 return Diag(TheCall->getLocEnd(),
2399 diag::err_typecheck_call_too_many_args_at_most)
2400 << 0 /*function call*/ << 3 << NumArgs
2401 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002402
2403 // Argument 0 is checked for us and the remaining arguments must be
2404 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002405 for (unsigned i = 1; i != NumArgs; ++i)
2406 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002407 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002408
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002409 return false;
2410}
2411
Hal Finkelf0417332014-07-17 14:25:55 +00002412/// SemaBuiltinAssume - Handle __assume (MS Extension).
2413// __assume does not evaluate its arguments, and should warn if its argument
2414// has side effects.
2415bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2416 Expr *Arg = TheCall->getArg(0);
2417 if (Arg->isInstantiationDependent()) return false;
2418
2419 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00002420 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002421 << Arg->getSourceRange()
2422 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2423
2424 return false;
2425}
2426
2427/// Handle __builtin_assume_aligned. This is declared
2428/// as (const void*, size_t, ...) and can take one optional constant int arg.
2429bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2430 unsigned NumArgs = TheCall->getNumArgs();
2431
2432 if (NumArgs > 3)
2433 return Diag(TheCall->getLocEnd(),
2434 diag::err_typecheck_call_too_many_args_at_most)
2435 << 0 /*function call*/ << 3 << NumArgs
2436 << TheCall->getSourceRange();
2437
2438 // The alignment must be a constant integer.
2439 Expr *Arg = TheCall->getArg(1);
2440
2441 // We can't check the value of a dependent argument.
2442 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2443 llvm::APSInt Result;
2444 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2445 return true;
2446
2447 if (!Result.isPowerOf2())
2448 return Diag(TheCall->getLocStart(),
2449 diag::err_alignment_not_power_of_two)
2450 << Arg->getSourceRange();
2451 }
2452
2453 if (NumArgs > 2) {
2454 ExprResult Arg(TheCall->getArg(2));
2455 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2456 Context.getSizeType(), false);
2457 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2458 if (Arg.isInvalid()) return true;
2459 TheCall->setArg(2, Arg.get());
2460 }
Hal Finkelf0417332014-07-17 14:25:55 +00002461
2462 return false;
2463}
2464
Eric Christopher8d0c6212010-04-17 02:26:23 +00002465/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2466/// TheCall is a constant expression.
2467bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2468 llvm::APSInt &Result) {
2469 Expr *Arg = TheCall->getArg(ArgNum);
2470 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2471 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2472
2473 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2474
2475 if (!Arg->isIntegerConstantExpr(Result, Context))
2476 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002477 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002478
Chris Lattnerd545ad12009-09-23 06:06:36 +00002479 return false;
2480}
2481
Richard Sandiford28940af2014-04-16 08:47:51 +00002482/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2483/// TheCall is a constant expression in the range [Low, High].
2484bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2485 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002486 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002487
2488 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002489 Expr *Arg = TheCall->getArg(ArgNum);
2490 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002491 return false;
2492
Eric Christopher8d0c6212010-04-17 02:26:23 +00002493 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002494 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002495 return true;
2496
Richard Sandiford28940af2014-04-16 08:47:51 +00002497 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002498 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002499 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002500
2501 return false;
2502}
2503
Eli Friedmanc97d0142009-05-03 06:04:26 +00002504/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002505/// This checks that the target supports __builtin_longjmp and
2506/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002507bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002508 if (!Context.getTargetInfo().hasSjLjLowering())
2509 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
2510 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2511
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002512 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002513 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002514
Eric Christopher8d0c6212010-04-17 02:26:23 +00002515 // TODO: This is less than ideal. Overload this to take a value.
2516 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2517 return true;
2518
2519 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002520 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2521 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2522
2523 return false;
2524}
2525
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002526
2527/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
2528/// This checks that the target supports __builtin_setjmp.
2529bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
2530 if (!Context.getTargetInfo().hasSjLjLowering())
2531 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
2532 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2533 return false;
2534}
2535
Richard Smithd7293d72013-08-05 18:49:43 +00002536namespace {
2537enum StringLiteralCheckType {
2538 SLCT_NotALiteral,
2539 SLCT_UncheckedLiteral,
2540 SLCT_CheckedLiteral
2541};
2542}
2543
Richard Smith55ce3522012-06-25 20:30:08 +00002544// Determine if an expression is a string literal or constant string.
2545// If this function returns false on the arguments to a function expecting a
2546// format string, we will usually need to emit a warning.
2547// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002548static StringLiteralCheckType
2549checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2550 bool HasVAListArg, unsigned format_idx,
2551 unsigned firstDataArg, Sema::FormatStringType Type,
2552 Sema::VariadicCallType CallType, bool InFunctionCall,
2553 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002554 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002555 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002556 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002557
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002558 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002559
Richard Smithd7293d72013-08-05 18:49:43 +00002560 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002561 // Technically -Wformat-nonliteral does not warn about this case.
2562 // The behavior of printf and friends in this case is implementation
2563 // dependent. Ideally if the format string cannot be null then
2564 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002565 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002566
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002567 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002568 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002569 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002570 // The expression is a literal if both sub-expressions were, and it was
2571 // completely checked only if both sub-expressions were checked.
2572 const AbstractConditionalOperator *C =
2573 cast<AbstractConditionalOperator>(E);
2574 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002575 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002576 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002577 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002578 if (Left == SLCT_NotALiteral)
2579 return SLCT_NotALiteral;
2580 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002581 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002582 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002583 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002584 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002585 }
2586
2587 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002588 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2589 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002590 }
2591
John McCallc07a0c72011-02-17 10:25:35 +00002592 case Stmt::OpaqueValueExprClass:
2593 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2594 E = src;
2595 goto tryAgain;
2596 }
Richard Smith55ce3522012-06-25 20:30:08 +00002597 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002598
Ted Kremeneka8890832011-02-24 23:03:04 +00002599 case Stmt::PredefinedExprClass:
2600 // While __func__, etc., are technically not string literals, they
2601 // cannot contain format specifiers and thus are not a security
2602 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002603 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002604
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002605 case Stmt::DeclRefExprClass: {
2606 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002607
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002608 // As an exception, do not flag errors for variables binding to
2609 // const string literals.
2610 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2611 bool isConstant = false;
2612 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002613
Richard Smithd7293d72013-08-05 18:49:43 +00002614 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2615 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002616 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002617 isConstant = T.isConstant(S.Context) &&
2618 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002619 } else if (T->isObjCObjectPointerType()) {
2620 // In ObjC, there is usually no "const ObjectPointer" type,
2621 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002622 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002623 }
Mike Stump11289f42009-09-09 15:08:12 +00002624
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002625 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002626 if (const Expr *Init = VD->getAnyInitializer()) {
2627 // Look through initializers like const char c[] = { "foo" }
2628 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2629 if (InitList->isStringLiteralInit())
2630 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2631 }
Richard Smithd7293d72013-08-05 18:49:43 +00002632 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002633 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002634 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002635 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002636 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002637 }
Mike Stump11289f42009-09-09 15:08:12 +00002638
Anders Carlssonb012ca92009-06-28 19:55:58 +00002639 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2640 // special check to see if the format string is a function parameter
2641 // of the function calling the printf function. If the function
2642 // has an attribute indicating it is a printf-like function, then we
2643 // should suppress warnings concerning non-literals being used in a call
2644 // to a vprintf function. For example:
2645 //
2646 // void
2647 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2648 // va_list ap;
2649 // va_start(ap, fmt);
2650 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2651 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002652 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002653 if (HasVAListArg) {
2654 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2655 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2656 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002657 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002658 // adjust for implicit parameter
2659 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2660 if (MD->isInstance())
2661 ++PVIndex;
2662 // We also check if the formats are compatible.
2663 // We can't pass a 'scanf' string to a 'printf' function.
2664 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002665 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002666 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002667 }
2668 }
2669 }
2670 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002671 }
Mike Stump11289f42009-09-09 15:08:12 +00002672
Richard Smith55ce3522012-06-25 20:30:08 +00002673 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002674 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002675
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002676 case Stmt::CallExprClass:
2677 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002678 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002679 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2680 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2681 unsigned ArgIndex = FA->getFormatIdx();
2682 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2683 if (MD->isInstance())
2684 --ArgIndex;
2685 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002686
Richard Smithd7293d72013-08-05 18:49:43 +00002687 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002688 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002689 Type, CallType, InFunctionCall,
2690 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002691 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2692 unsigned BuiltinID = FD->getBuiltinID();
2693 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2694 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2695 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002696 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002697 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002698 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002699 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002700 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002701 }
2702 }
Mike Stump11289f42009-09-09 15:08:12 +00002703
Richard Smith55ce3522012-06-25 20:30:08 +00002704 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002705 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002706 case Stmt::ObjCStringLiteralClass:
2707 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002708 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002709
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002710 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002711 StrE = ObjCFExpr->getString();
2712 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002713 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002714
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002715 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002716 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2717 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002718 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002719 }
Mike Stump11289f42009-09-09 15:08:12 +00002720
Richard Smith55ce3522012-06-25 20:30:08 +00002721 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002722 }
Mike Stump11289f42009-09-09 15:08:12 +00002723
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002724 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002725 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002726 }
2727}
2728
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002729Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002730 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002731 .Case("scanf", FST_Scanf)
2732 .Cases("printf", "printf0", FST_Printf)
2733 .Cases("NSString", "CFString", FST_NSString)
2734 .Case("strftime", FST_Strftime)
2735 .Case("strfmon", FST_Strfmon)
2736 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00002737 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00002738 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002739 .Default(FST_Unknown);
2740}
2741
Jordan Rose3e0ec582012-07-19 18:10:23 +00002742/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002743/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002744/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002745bool Sema::CheckFormatArguments(const FormatAttr *Format,
2746 ArrayRef<const Expr *> Args,
2747 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002748 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002749 SourceLocation Loc, SourceRange Range,
2750 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002751 FormatStringInfo FSI;
2752 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002753 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002754 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002755 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002756 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002757}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002758
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002759bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002760 bool HasVAListArg, unsigned format_idx,
2761 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002762 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002763 SourceLocation Loc, SourceRange Range,
2764 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002765 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002766 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002767 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002768 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002769 }
Mike Stump11289f42009-09-09 15:08:12 +00002770
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002771 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002772
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002773 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002774 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002775 // Dynamically generated format strings are difficult to
2776 // automatically vet at compile time. Requiring that format strings
2777 // are string literals: (1) permits the checking of format strings by
2778 // the compiler and thereby (2) can practically remove the source of
2779 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002780
Mike Stump11289f42009-09-09 15:08:12 +00002781 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002782 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002783 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002784 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002785 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002786 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2787 format_idx, firstDataArg, Type, CallType,
2788 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002789 if (CT != SLCT_NotALiteral)
2790 // Literal format string found, check done!
2791 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002792
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002793 // Strftime is particular as it always uses a single 'time' argument,
2794 // so it is safe to pass a non-literal string.
2795 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002796 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002797
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002798 // Do not emit diag when the string param is a macro expansion and the
2799 // format is either NSString or CFString. This is a hack to prevent
2800 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2801 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002802 if (Type == FST_NSString &&
2803 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002804 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002805
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002806 // If there are no arguments specified, warn with -Wformat-security, otherwise
2807 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002808 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002809 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002810 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002811 << OrigFormatExpr->getSourceRange();
2812 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002813 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002814 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002815 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002816 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002817}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002818
Ted Kremenekab278de2010-01-28 23:39:18 +00002819namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002820class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2821protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002822 Sema &S;
2823 const StringLiteral *FExpr;
2824 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002825 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002826 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002827 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002828 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002829 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002830 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002831 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002832 bool usesPositionalArgs;
2833 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002834 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002835 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002836 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002837public:
Ted Kremenek02087932010-07-16 02:11:22 +00002838 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002839 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002840 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002841 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002842 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002843 Sema::VariadicCallType callType,
2844 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002845 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002846 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2847 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002848 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002849 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002850 inFunctionCall(inFunctionCall), CallType(callType),
2851 CheckedVarArgs(CheckedVarArgs) {
2852 CoveredArgs.resize(numDataArgs);
2853 CoveredArgs.reset();
2854 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002855
Ted Kremenek019d2242010-01-29 01:50:07 +00002856 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002857
Ted Kremenek02087932010-07-16 02:11:22 +00002858 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002859 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002860
Jordan Rose92303592012-09-08 04:00:03 +00002861 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002862 const analyze_format_string::FormatSpecifier &FS,
2863 const analyze_format_string::ConversionSpecifier &CS,
2864 const char *startSpecifier, unsigned specifierLen,
2865 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002866
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002867 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002868 const analyze_format_string::FormatSpecifier &FS,
2869 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002870
2871 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002872 const analyze_format_string::ConversionSpecifier &CS,
2873 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002874
Craig Toppere14c0f82014-03-12 04:55:44 +00002875 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002876
Craig Toppere14c0f82014-03-12 04:55:44 +00002877 void HandleInvalidPosition(const char *startSpecifier,
2878 unsigned specifierLen,
2879 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002880
Craig Toppere14c0f82014-03-12 04:55:44 +00002881 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002882
Craig Toppere14c0f82014-03-12 04:55:44 +00002883 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002884
Richard Trieu03cf7b72011-10-28 00:41:25 +00002885 template <typename Range>
2886 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2887 const Expr *ArgumentExpr,
2888 PartialDiagnostic PDiag,
2889 SourceLocation StringLoc,
2890 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002891 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002892
Ted Kremenek02087932010-07-16 02:11:22 +00002893protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002894 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2895 const char *startSpec,
2896 unsigned specifierLen,
2897 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002898
2899 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2900 const char *startSpec,
2901 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002902
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002903 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002904 CharSourceRange getSpecifierRange(const char *startSpecifier,
2905 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002906 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002907
Ted Kremenek5739de72010-01-29 01:06:55 +00002908 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002909
2910 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2911 const analyze_format_string::ConversionSpecifier &CS,
2912 const char *startSpecifier, unsigned specifierLen,
2913 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002914
2915 template <typename Range>
2916 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2917 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002918 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002919};
2920}
2921
Ted Kremenek02087932010-07-16 02:11:22 +00002922SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002923 return OrigFormatExpr->getSourceRange();
2924}
2925
Ted Kremenek02087932010-07-16 02:11:22 +00002926CharSourceRange CheckFormatHandler::
2927getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002928 SourceLocation Start = getLocationOfByte(startSpecifier);
2929 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2930
2931 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002932 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002933
2934 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002935}
2936
Ted Kremenek02087932010-07-16 02:11:22 +00002937SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002938 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002939}
2940
Ted Kremenek02087932010-07-16 02:11:22 +00002941void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2942 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002943 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2944 getLocationOfByte(startSpecifier),
2945 /*IsStringLocation*/true,
2946 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002947}
2948
Jordan Rose92303592012-09-08 04:00:03 +00002949void CheckFormatHandler::HandleInvalidLengthModifier(
2950 const analyze_format_string::FormatSpecifier &FS,
2951 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002952 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002953 using namespace analyze_format_string;
2954
2955 const LengthModifier &LM = FS.getLengthModifier();
2956 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2957
2958 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002959 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002960 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002961 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002962 getLocationOfByte(LM.getStart()),
2963 /*IsStringLocation*/true,
2964 getSpecifierRange(startSpecifier, specifierLen));
2965
2966 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2967 << FixedLM->toString()
2968 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2969
2970 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002971 FixItHint Hint;
2972 if (DiagID == diag::warn_format_nonsensical_length)
2973 Hint = FixItHint::CreateRemoval(LMRange);
2974
2975 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002976 getLocationOfByte(LM.getStart()),
2977 /*IsStringLocation*/true,
2978 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002979 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002980 }
2981}
2982
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002983void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002984 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002985 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002986 using namespace analyze_format_string;
2987
2988 const LengthModifier &LM = FS.getLengthModifier();
2989 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2990
2991 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002992 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002993 if (FixedLM) {
2994 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2995 << LM.toString() << 0,
2996 getLocationOfByte(LM.getStart()),
2997 /*IsStringLocation*/true,
2998 getSpecifierRange(startSpecifier, specifierLen));
2999
3000 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3001 << FixedLM->toString()
3002 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3003
3004 } else {
3005 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3006 << LM.toString() << 0,
3007 getLocationOfByte(LM.getStart()),
3008 /*IsStringLocation*/true,
3009 getSpecifierRange(startSpecifier, specifierLen));
3010 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003011}
3012
3013void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3014 const analyze_format_string::ConversionSpecifier &CS,
3015 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00003016 using namespace analyze_format_string;
3017
3018 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00003019 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00003020 if (FixedCS) {
3021 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3022 << CS.toString() << /*conversion specifier*/1,
3023 getLocationOfByte(CS.getStart()),
3024 /*IsStringLocation*/true,
3025 getSpecifierRange(startSpecifier, specifierLen));
3026
3027 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3028 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3029 << FixedCS->toString()
3030 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3031 } else {
3032 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3033 << CS.toString() << /*conversion specifier*/1,
3034 getLocationOfByte(CS.getStart()),
3035 /*IsStringLocation*/true,
3036 getSpecifierRange(startSpecifier, specifierLen));
3037 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003038}
3039
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003040void CheckFormatHandler::HandlePosition(const char *startPos,
3041 unsigned posLen) {
3042 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3043 getLocationOfByte(startPos),
3044 /*IsStringLocation*/true,
3045 getSpecifierRange(startPos, posLen));
3046}
3047
Ted Kremenekd1668192010-02-27 01:41:03 +00003048void
Ted Kremenek02087932010-07-16 02:11:22 +00003049CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3050 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003051 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3052 << (unsigned) p,
3053 getLocationOfByte(startPos), /*IsStringLocation*/true,
3054 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003055}
3056
Ted Kremenek02087932010-07-16 02:11:22 +00003057void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003058 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003059 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3060 getLocationOfByte(startPos),
3061 /*IsStringLocation*/true,
3062 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003063}
3064
Ted Kremenek02087932010-07-16 02:11:22 +00003065void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003066 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003067 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003068 EmitFormatDiagnostic(
3069 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3070 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3071 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003072 }
Ted Kremenek02087932010-07-16 02:11:22 +00003073}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003074
Jordan Rose58bbe422012-07-19 18:10:08 +00003075// Note that this may return NULL if there was an error parsing or building
3076// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003077const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003078 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003079}
3080
3081void CheckFormatHandler::DoneProcessing() {
3082 // Does the number of data arguments exceed the number of
3083 // format conversions in the format string?
3084 if (!HasVAListArg) {
3085 // Find any arguments that weren't covered.
3086 CoveredArgs.flip();
3087 signed notCoveredArg = CoveredArgs.find_first();
3088 if (notCoveredArg >= 0) {
3089 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00003090 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3091 SourceLocation Loc = E->getLocStart();
3092 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3093 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3094 Loc, /*IsStringLocation*/false,
3095 getFormatStringRange());
3096 }
Bob Wilson23cd4342012-05-03 19:47:19 +00003097 }
Ted Kremenek02087932010-07-16 02:11:22 +00003098 }
3099 }
3100}
3101
Ted Kremenekce815422010-07-19 21:25:57 +00003102bool
3103CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3104 SourceLocation Loc,
3105 const char *startSpec,
3106 unsigned specifierLen,
3107 const char *csStart,
3108 unsigned csLen) {
3109
3110 bool keepGoing = true;
3111 if (argIndex < NumDataArgs) {
3112 // Consider the argument coverered, even though the specifier doesn't
3113 // make sense.
3114 CoveredArgs.set(argIndex);
3115 }
3116 else {
3117 // If argIndex exceeds the number of data arguments we
3118 // don't issue a warning because that is just a cascade of warnings (and
3119 // they may have intended '%%' anyway). We don't want to continue processing
3120 // the format string after this point, however, as we will like just get
3121 // gibberish when trying to match arguments.
3122 keepGoing = false;
3123 }
3124
Richard Trieu03cf7b72011-10-28 00:41:25 +00003125 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3126 << StringRef(csStart, csLen),
3127 Loc, /*IsStringLocation*/true,
3128 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003129
3130 return keepGoing;
3131}
3132
Richard Trieu03cf7b72011-10-28 00:41:25 +00003133void
3134CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3135 const char *startSpec,
3136 unsigned specifierLen) {
3137 EmitFormatDiagnostic(
3138 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3139 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3140}
3141
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003142bool
3143CheckFormatHandler::CheckNumArgs(
3144 const analyze_format_string::FormatSpecifier &FS,
3145 const analyze_format_string::ConversionSpecifier &CS,
3146 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3147
3148 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003149 PartialDiagnostic PDiag = FS.usesPositionalArg()
3150 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3151 << (argIndex+1) << NumDataArgs)
3152 : S.PDiag(diag::warn_printf_insufficient_data_args);
3153 EmitFormatDiagnostic(
3154 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3155 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003156 return false;
3157 }
3158 return true;
3159}
3160
Richard Trieu03cf7b72011-10-28 00:41:25 +00003161template<typename Range>
3162void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3163 SourceLocation Loc,
3164 bool IsStringLocation,
3165 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003166 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003167 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003168 Loc, IsStringLocation, StringRange, FixIt);
3169}
3170
3171/// \brief If the format string is not within the funcion call, emit a note
3172/// so that the function call and string are in diagnostic messages.
3173///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003174/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003175/// call and only one diagnostic message will be produced. Otherwise, an
3176/// extra note will be emitted pointing to location of the format string.
3177///
3178/// \param ArgumentExpr the expression that is passed as the format string
3179/// argument in the function call. Used for getting locations when two
3180/// diagnostics are emitted.
3181///
3182/// \param PDiag the callee should already have provided any strings for the
3183/// diagnostic message. This function only adds locations and fixits
3184/// to diagnostics.
3185///
3186/// \param Loc primary location for diagnostic. If two diagnostics are
3187/// required, one will be at Loc and a new SourceLocation will be created for
3188/// the other one.
3189///
3190/// \param IsStringLocation if true, Loc points to the format string should be
3191/// used for the note. Otherwise, Loc points to the argument list and will
3192/// be used with PDiag.
3193///
3194/// \param StringRange some or all of the string to highlight. This is
3195/// templated so it can accept either a CharSourceRange or a SourceRange.
3196///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003197/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003198template<typename Range>
3199void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3200 const Expr *ArgumentExpr,
3201 PartialDiagnostic PDiag,
3202 SourceLocation Loc,
3203 bool IsStringLocation,
3204 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003205 ArrayRef<FixItHint> FixIt) {
3206 if (InFunctionCall) {
3207 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3208 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003209 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00003210 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003211 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3212 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003213
3214 const Sema::SemaDiagnosticBuilder &Note =
3215 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3216 diag::note_format_string_defined);
3217
3218 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003219 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003220 }
3221}
3222
Ted Kremenek02087932010-07-16 02:11:22 +00003223//===--- CHECK: Printf format string checking ------------------------------===//
3224
3225namespace {
3226class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003227 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00003228public:
3229 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3230 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003231 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003232 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003233 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003234 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003235 Sema::VariadicCallType CallType,
3236 llvm::SmallBitVector &CheckedVarArgs)
3237 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3238 numDataArgs, beg, hasVAListArg, Args,
3239 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3240 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003241 {}
3242
Craig Toppere14c0f82014-03-12 04:55:44 +00003243
Ted Kremenek02087932010-07-16 02:11:22 +00003244 bool HandleInvalidPrintfConversionSpecifier(
3245 const analyze_printf::PrintfSpecifier &FS,
3246 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003247 unsigned specifierLen) override;
3248
Ted Kremenek02087932010-07-16 02:11:22 +00003249 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3250 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003251 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003252 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3253 const char *StartSpecifier,
3254 unsigned SpecifierLen,
3255 const Expr *E);
3256
Ted Kremenek02087932010-07-16 02:11:22 +00003257 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3258 const char *startSpecifier, unsigned specifierLen);
3259 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3260 const analyze_printf::OptionalAmount &Amt,
3261 unsigned type,
3262 const char *startSpecifier, unsigned specifierLen);
3263 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3264 const analyze_printf::OptionalFlag &flag,
3265 const char *startSpecifier, unsigned specifierLen);
3266 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3267 const analyze_printf::OptionalFlag &ignoredFlag,
3268 const analyze_printf::OptionalFlag &flag,
3269 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003270 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003271 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00003272
Ted Kremenek02087932010-07-16 02:11:22 +00003273};
3274}
3275
3276bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3277 const analyze_printf::PrintfSpecifier &FS,
3278 const char *startSpecifier,
3279 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003280 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003281 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003282
Ted Kremenekce815422010-07-19 21:25:57 +00003283 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3284 getLocationOfByte(CS.getStart()),
3285 startSpecifier, specifierLen,
3286 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003287}
3288
Ted Kremenek02087932010-07-16 02:11:22 +00003289bool CheckPrintfHandler::HandleAmount(
3290 const analyze_format_string::OptionalAmount &Amt,
3291 unsigned k, const char *startSpecifier,
3292 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003293
3294 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003295 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003296 unsigned argIndex = Amt.getArgIndex();
3297 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003298 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3299 << k,
3300 getLocationOfByte(Amt.getStart()),
3301 /*IsStringLocation*/true,
3302 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003303 // Don't do any more checking. We will just emit
3304 // spurious errors.
3305 return false;
3306 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003307
Ted Kremenek5739de72010-01-29 01:06:55 +00003308 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00003309 // Although not in conformance with C99, we also allow the argument to be
3310 // an 'unsigned int' as that is a reasonably safe case. GCC also
3311 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003312 CoveredArgs.set(argIndex);
3313 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003314 if (!Arg)
3315 return false;
3316
Ted Kremenek5739de72010-01-29 01:06:55 +00003317 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003318
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003319 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3320 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003321
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003322 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003323 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003324 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003325 << T << Arg->getSourceRange(),
3326 getLocationOfByte(Amt.getStart()),
3327 /*IsStringLocation*/true,
3328 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003329 // Don't do any more checking. We will just emit
3330 // spurious errors.
3331 return false;
3332 }
3333 }
3334 }
3335 return true;
3336}
Ted Kremenek5739de72010-01-29 01:06:55 +00003337
Tom Careb49ec692010-06-17 19:00:27 +00003338void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003339 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003340 const analyze_printf::OptionalAmount &Amt,
3341 unsigned type,
3342 const char *startSpecifier,
3343 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003344 const analyze_printf::PrintfConversionSpecifier &CS =
3345 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003346
Richard Trieu03cf7b72011-10-28 00:41:25 +00003347 FixItHint fixit =
3348 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3349 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3350 Amt.getConstantLength()))
3351 : FixItHint();
3352
3353 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3354 << type << CS.toString(),
3355 getLocationOfByte(Amt.getStart()),
3356 /*IsStringLocation*/true,
3357 getSpecifierRange(startSpecifier, specifierLen),
3358 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003359}
3360
Ted Kremenek02087932010-07-16 02:11:22 +00003361void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003362 const analyze_printf::OptionalFlag &flag,
3363 const char *startSpecifier,
3364 unsigned specifierLen) {
3365 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003366 const analyze_printf::PrintfConversionSpecifier &CS =
3367 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003368 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3369 << flag.toString() << CS.toString(),
3370 getLocationOfByte(flag.getPosition()),
3371 /*IsStringLocation*/true,
3372 getSpecifierRange(startSpecifier, specifierLen),
3373 FixItHint::CreateRemoval(
3374 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003375}
3376
3377void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003378 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003379 const analyze_printf::OptionalFlag &ignoredFlag,
3380 const analyze_printf::OptionalFlag &flag,
3381 const char *startSpecifier,
3382 unsigned specifierLen) {
3383 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003384 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3385 << ignoredFlag.toString() << flag.toString(),
3386 getLocationOfByte(ignoredFlag.getPosition()),
3387 /*IsStringLocation*/true,
3388 getSpecifierRange(startSpecifier, specifierLen),
3389 FixItHint::CreateRemoval(
3390 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003391}
3392
Richard Smith55ce3522012-06-25 20:30:08 +00003393// Determines if the specified is a C++ class or struct containing
3394// a member with the specified name and kind (e.g. a CXXMethodDecl named
3395// "c_str()").
3396template<typename MemberKind>
3397static llvm::SmallPtrSet<MemberKind*, 1>
3398CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3399 const RecordType *RT = Ty->getAs<RecordType>();
3400 llvm::SmallPtrSet<MemberKind*, 1> Results;
3401
3402 if (!RT)
3403 return Results;
3404 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003405 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003406 return Results;
3407
Alp Tokerb6cc5922014-05-03 03:45:55 +00003408 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003409 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003410 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003411
3412 // We just need to include all members of the right kind turned up by the
3413 // filter, at this point.
3414 if (S.LookupQualifiedName(R, RT->getDecl()))
3415 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3416 NamedDecl *decl = (*I)->getUnderlyingDecl();
3417 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3418 Results.insert(FK);
3419 }
3420 return Results;
3421}
3422
Richard Smith2868a732014-02-28 01:36:39 +00003423/// Check if we could call '.c_str()' on an object.
3424///
3425/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3426/// allow the call, or if it would be ambiguous).
3427bool Sema::hasCStrMethod(const Expr *E) {
3428 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3429 MethodSet Results =
3430 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3431 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3432 MI != ME; ++MI)
3433 if ((*MI)->getMinRequiredArguments() == 0)
3434 return true;
3435 return false;
3436}
3437
Richard Smith55ce3522012-06-25 20:30:08 +00003438// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003439// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003440// Returns true when a c_str() conversion method is found.
3441bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003442 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003443 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3444
3445 MethodSet Results =
3446 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3447
3448 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3449 MI != ME; ++MI) {
3450 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003451 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003452 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003453 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003454 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003455 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3456 << "c_str()"
3457 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3458 return true;
3459 }
3460 }
3461
3462 return false;
3463}
3464
Ted Kremenekab278de2010-01-28 23:39:18 +00003465bool
Ted Kremenek02087932010-07-16 02:11:22 +00003466CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003467 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003468 const char *startSpecifier,
3469 unsigned specifierLen) {
3470
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003471 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003472 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003473 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003474
Ted Kremenek6cd69422010-07-19 22:01:06 +00003475 if (FS.consumesDataArgument()) {
3476 if (atFirstArg) {
3477 atFirstArg = false;
3478 usesPositionalArgs = FS.usesPositionalArg();
3479 }
3480 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003481 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3482 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003483 return false;
3484 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003485 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003486
Ted Kremenekd1668192010-02-27 01:41:03 +00003487 // First check if the field width, precision, and conversion specifier
3488 // have matching data arguments.
3489 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3490 startSpecifier, specifierLen)) {
3491 return false;
3492 }
3493
3494 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3495 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003496 return false;
3497 }
3498
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003499 if (!CS.consumesDataArgument()) {
3500 // FIXME: Technically specifying a precision or field width here
3501 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003502 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003503 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003504
Ted Kremenek4a49d982010-02-26 19:18:41 +00003505 // Consume the argument.
3506 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003507 if (argIndex < NumDataArgs) {
3508 // The check to see if the argIndex is valid will come later.
3509 // We set the bit here because we may exit early from this
3510 // function if we encounter some other error.
3511 CoveredArgs.set(argIndex);
3512 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003513
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003514 // FreeBSD kernel extensions.
3515 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
3516 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
3517 // We need at least two arguments.
3518 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
3519 return false;
3520
3521 // Claim the second argument.
3522 CoveredArgs.set(argIndex + 1);
3523
3524 // Type check the first argument (int for %b, pointer for %D)
3525 const Expr *Ex = getDataArg(argIndex);
3526 const analyze_printf::ArgType &AT =
3527 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
3528 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
3529 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
3530 EmitFormatDiagnostic(
3531 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3532 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3533 << false << Ex->getSourceRange(),
3534 Ex->getLocStart(), /*IsStringLocation*/false,
3535 getSpecifierRange(startSpecifier, specifierLen));
3536
3537 // Type check the second argument (char * for both %b and %D)
3538 Ex = getDataArg(argIndex + 1);
3539 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
3540 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
3541 EmitFormatDiagnostic(
3542 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3543 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
3544 << false << Ex->getSourceRange(),
3545 Ex->getLocStart(), /*IsStringLocation*/false,
3546 getSpecifierRange(startSpecifier, specifierLen));
3547
3548 return true;
3549 }
3550
Ted Kremenek4a49d982010-02-26 19:18:41 +00003551 // Check for using an Objective-C specific conversion specifier
3552 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003553 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003554 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3555 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003556 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003557
Tom Careb49ec692010-06-17 19:00:27 +00003558 // Check for invalid use of field width
3559 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003560 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003561 startSpecifier, specifierLen);
3562 }
3563
3564 // Check for invalid use of precision
3565 if (!FS.hasValidPrecision()) {
3566 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3567 startSpecifier, specifierLen);
3568 }
3569
3570 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003571 if (!FS.hasValidThousandsGroupingPrefix())
3572 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003573 if (!FS.hasValidLeadingZeros())
3574 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3575 if (!FS.hasValidPlusPrefix())
3576 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003577 if (!FS.hasValidSpacePrefix())
3578 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003579 if (!FS.hasValidAlternativeForm())
3580 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3581 if (!FS.hasValidLeftJustified())
3582 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3583
3584 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003585 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3586 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3587 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003588 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3589 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3590 startSpecifier, specifierLen);
3591
3592 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003593 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003594 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3595 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003596 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003597 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003598 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003599 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3600 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003601
Jordan Rose92303592012-09-08 04:00:03 +00003602 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3603 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3604
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003605 // The remaining checks depend on the data arguments.
3606 if (HasVAListArg)
3607 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003608
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003609 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003610 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003611
Jordan Rose58bbe422012-07-19 18:10:08 +00003612 const Expr *Arg = getDataArg(argIndex);
3613 if (!Arg)
3614 return true;
3615
3616 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003617}
3618
Jordan Roseaee34382012-09-05 22:56:26 +00003619static bool requiresParensToAddCast(const Expr *E) {
3620 // FIXME: We should have a general way to reason about operator
3621 // precedence and whether parens are actually needed here.
3622 // Take care of a few common cases where they aren't.
3623 const Expr *Inside = E->IgnoreImpCasts();
3624 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3625 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3626
3627 switch (Inside->getStmtClass()) {
3628 case Stmt::ArraySubscriptExprClass:
3629 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003630 case Stmt::CharacterLiteralClass:
3631 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003632 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003633 case Stmt::FloatingLiteralClass:
3634 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003635 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003636 case Stmt::ObjCArrayLiteralClass:
3637 case Stmt::ObjCBoolLiteralExprClass:
3638 case Stmt::ObjCBoxedExprClass:
3639 case Stmt::ObjCDictionaryLiteralClass:
3640 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003641 case Stmt::ObjCIvarRefExprClass:
3642 case Stmt::ObjCMessageExprClass:
3643 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003644 case Stmt::ObjCStringLiteralClass:
3645 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003646 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003647 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003648 case Stmt::UnaryOperatorClass:
3649 return false;
3650 default:
3651 return true;
3652 }
3653}
3654
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003655static std::pair<QualType, StringRef>
3656shouldNotPrintDirectly(const ASTContext &Context,
3657 QualType IntendedTy,
3658 const Expr *E) {
3659 // Use a 'while' to peel off layers of typedefs.
3660 QualType TyTy = IntendedTy;
3661 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3662 StringRef Name = UserTy->getDecl()->getName();
3663 QualType CastTy = llvm::StringSwitch<QualType>(Name)
3664 .Case("NSInteger", Context.LongTy)
3665 .Case("NSUInteger", Context.UnsignedLongTy)
3666 .Case("SInt32", Context.IntTy)
3667 .Case("UInt32", Context.UnsignedIntTy)
3668 .Default(QualType());
3669
3670 if (!CastTy.isNull())
3671 return std::make_pair(CastTy, Name);
3672
3673 TyTy = UserTy->desugar();
3674 }
3675
3676 // Strip parens if necessary.
3677 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
3678 return shouldNotPrintDirectly(Context,
3679 PE->getSubExpr()->getType(),
3680 PE->getSubExpr());
3681
3682 // If this is a conditional expression, then its result type is constructed
3683 // via usual arithmetic conversions and thus there might be no necessary
3684 // typedef sugar there. Recurse to operands to check for NSInteger &
3685 // Co. usage condition.
3686 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3687 QualType TrueTy, FalseTy;
3688 StringRef TrueName, FalseName;
3689
3690 std::tie(TrueTy, TrueName) =
3691 shouldNotPrintDirectly(Context,
3692 CO->getTrueExpr()->getType(),
3693 CO->getTrueExpr());
3694 std::tie(FalseTy, FalseName) =
3695 shouldNotPrintDirectly(Context,
3696 CO->getFalseExpr()->getType(),
3697 CO->getFalseExpr());
3698
3699 if (TrueTy == FalseTy)
3700 return std::make_pair(TrueTy, TrueName);
3701 else if (TrueTy.isNull())
3702 return std::make_pair(FalseTy, FalseName);
3703 else if (FalseTy.isNull())
3704 return std::make_pair(TrueTy, TrueName);
3705 }
3706
3707 return std::make_pair(QualType(), StringRef());
3708}
3709
Richard Smith55ce3522012-06-25 20:30:08 +00003710bool
3711CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3712 const char *StartSpecifier,
3713 unsigned SpecifierLen,
3714 const Expr *E) {
3715 using namespace analyze_format_string;
3716 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003717 // Now type check the data expression that matches the
3718 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003719 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3720 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003721 if (!AT.isValid())
3722 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003723
Jordan Rose598ec092012-12-05 18:44:40 +00003724 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003725 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3726 ExprTy = TET->getUnderlyingExpr()->getType();
3727 }
3728
Seth Cantrellb4802962015-03-04 03:12:10 +00003729 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
3730
3731 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00003732 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00003733 }
Jordan Rose98709982012-06-04 22:48:57 +00003734
Jordan Rose22b74712012-09-05 22:56:19 +00003735 // Look through argument promotions for our error message's reported type.
3736 // This includes the integral and floating promotions, but excludes array
3737 // and function pointer decay; seeing that an argument intended to be a
3738 // string has type 'char [6]' is probably more confusing than 'char *'.
3739 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3740 if (ICE->getCastKind() == CK_IntegralCast ||
3741 ICE->getCastKind() == CK_FloatingCast) {
3742 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003743 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003744
3745 // Check if we didn't match because of an implicit cast from a 'char'
3746 // or 'short' to an 'int'. This is done because printf is a varargs
3747 // function.
3748 if (ICE->getType() == S.Context.IntTy ||
3749 ICE->getType() == S.Context.UnsignedIntTy) {
3750 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003751 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003752 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003753 }
Jordan Rose98709982012-06-04 22:48:57 +00003754 }
Jordan Rose598ec092012-12-05 18:44:40 +00003755 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3756 // Special case for 'a', which has type 'int' in C.
3757 // Note, however, that we do /not/ want to treat multibyte constants like
3758 // 'MooV' as characters! This form is deprecated but still exists.
3759 if (ExprTy == S.Context.IntTy)
3760 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3761 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003762 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003763
Jordan Rosebc53ed12014-05-31 04:12:14 +00003764 // Look through enums to their underlying type.
3765 bool IsEnum = false;
3766 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3767 ExprTy = EnumTy->getDecl()->getIntegerType();
3768 IsEnum = true;
3769 }
3770
Jordan Rose0e5badd2012-12-05 18:44:49 +00003771 // %C in an Objective-C context prints a unichar, not a wchar_t.
3772 // If the argument is an integer of some kind, believe the %C and suggest
3773 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003774 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003775 if (ObjCContext &&
3776 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3777 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3778 !ExprTy->isCharType()) {
3779 // 'unichar' is defined as a typedef of unsigned short, but we should
3780 // prefer using the typedef if it is visible.
3781 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003782
3783 // While we are here, check if the value is an IntegerLiteral that happens
3784 // to be within the valid range.
3785 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3786 const llvm::APInt &V = IL->getValue();
3787 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3788 return true;
3789 }
3790
Jordan Rose0e5badd2012-12-05 18:44:49 +00003791 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3792 Sema::LookupOrdinaryName);
3793 if (S.LookupName(Result, S.getCurScope())) {
3794 NamedDecl *ND = Result.getFoundDecl();
3795 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3796 if (TD->getUnderlyingType() == IntendedTy)
3797 IntendedTy = S.Context.getTypedefType(TD);
3798 }
3799 }
3800 }
3801
3802 // Special-case some of Darwin's platform-independence types by suggesting
3803 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003804 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00003805 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003806 QualType CastTy;
3807 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
3808 if (!CastTy.isNull()) {
3809 IntendedTy = CastTy;
3810 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00003811 }
3812 }
3813
Jordan Rose22b74712012-09-05 22:56:19 +00003814 // We may be able to offer a FixItHint if it is a supported type.
3815 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003816 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003817 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003818
Jordan Rose22b74712012-09-05 22:56:19 +00003819 if (success) {
3820 // Get the fix string from the fixed format specifier
3821 SmallString<16> buf;
3822 llvm::raw_svector_ostream os(buf);
3823 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003824
Jordan Roseaee34382012-09-05 22:56:26 +00003825 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3826
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003827 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00003828 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
3829 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
3830 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
3831 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00003832 // In this case, the specifier is wrong and should be changed to match
3833 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00003834 EmitFormatDiagnostic(S.PDiag(diag)
3835 << AT.getRepresentativeTypeName(S.Context)
3836 << IntendedTy << IsEnum << E->getSourceRange(),
3837 E->getLocStart(),
3838 /*IsStringLocation*/ false, SpecRange,
3839 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00003840
3841 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003842 // The canonical type for formatting this value is different from the
3843 // actual type of the expression. (This occurs, for example, with Darwin's
3844 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3845 // should be printed as 'long' for 64-bit compatibility.)
3846 // Rather than emitting a normal format/argument mismatch, we want to
3847 // add a cast to the recommended type (and correct the format string
3848 // if necessary).
3849 SmallString<16> CastBuf;
3850 llvm::raw_svector_ostream CastFix(CastBuf);
3851 CastFix << "(";
3852 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3853 CastFix << ")";
3854
3855 SmallVector<FixItHint,4> Hints;
3856 if (!AT.matchesType(S.Context, IntendedTy))
3857 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3858
3859 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3860 // If there's already a cast present, just replace it.
3861 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3862 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3863
3864 } else if (!requiresParensToAddCast(E)) {
3865 // If the expression has high enough precedence,
3866 // just write the C-style cast.
3867 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3868 CastFix.str()));
3869 } else {
3870 // Otherwise, add parens around the expression as well as the cast.
3871 CastFix << "(";
3872 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3873 CastFix.str()));
3874
Alp Tokerb6cc5922014-05-03 03:45:55 +00003875 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003876 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3877 }
3878
Jordan Rose0e5badd2012-12-05 18:44:49 +00003879 if (ShouldNotPrintDirectly) {
3880 // The expression has a type that should not be printed directly.
3881 // We extract the name from the typedef because we don't want to show
3882 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003883 StringRef Name;
3884 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
3885 Name = TypedefTy->getDecl()->getName();
3886 else
3887 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003888 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00003889 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003890 << E->getSourceRange(),
3891 E->getLocStart(), /*IsStringLocation=*/false,
3892 SpecRange, Hints);
3893 } else {
3894 // In this case, the expression could be printed using a different
3895 // specifier, but we've decided that the specifier is probably correct
3896 // and we should cast instead. Just use the normal warning message.
3897 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003898 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3899 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003900 << E->getSourceRange(),
3901 E->getLocStart(), /*IsStringLocation*/false,
3902 SpecRange, Hints);
3903 }
Jordan Roseaee34382012-09-05 22:56:26 +00003904 }
Jordan Rose22b74712012-09-05 22:56:19 +00003905 } else {
3906 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3907 SpecifierLen);
3908 // Since the warning for passing non-POD types to variadic functions
3909 // was deferred until now, we emit a warning for non-POD
3910 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003911 switch (S.isValidVarArgType(ExprTy)) {
3912 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00003913 case Sema::VAK_ValidInCXX11: {
3914 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
3915 if (match == analyze_printf::ArgType::NoMatchPedantic) {
3916 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
3917 }
Richard Smithd7293d72013-08-05 18:49:43 +00003918
Seth Cantrellb4802962015-03-04 03:12:10 +00003919 EmitFormatDiagnostic(
3920 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
3921 << IsEnum << CSR << E->getSourceRange(),
3922 E->getLocStart(), /*IsStringLocation*/ false, CSR);
3923 break;
3924 }
Richard Smithd7293d72013-08-05 18:49:43 +00003925 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00003926 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00003927 EmitFormatDiagnostic(
3928 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003929 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003930 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003931 << CallType
3932 << AT.getRepresentativeTypeName(S.Context)
3933 << CSR
3934 << E->getSourceRange(),
3935 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003936 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003937 break;
3938
3939 case Sema::VAK_Invalid:
3940 if (ExprTy->isObjCObjectType())
3941 EmitFormatDiagnostic(
3942 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3943 << S.getLangOpts().CPlusPlus11
3944 << ExprTy
3945 << CallType
3946 << AT.getRepresentativeTypeName(S.Context)
3947 << CSR
3948 << E->getSourceRange(),
3949 E->getLocStart(), /*IsStringLocation*/false, CSR);
3950 else
3951 // FIXME: If this is an initializer list, suggest removing the braces
3952 // or inserting a cast to the target type.
3953 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3954 << isa<InitListExpr>(E) << ExprTy << CallType
3955 << AT.getRepresentativeTypeName(S.Context)
3956 << E->getSourceRange();
3957 break;
3958 }
3959
3960 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3961 "format string specifier index out of range");
3962 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003963 }
3964
Ted Kremenekab278de2010-01-28 23:39:18 +00003965 return true;
3966}
3967
Ted Kremenek02087932010-07-16 02:11:22 +00003968//===--- CHECK: Scanf format string checking ------------------------------===//
3969
3970namespace {
3971class CheckScanfHandler : public CheckFormatHandler {
3972public:
3973 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3974 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003975 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003976 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003977 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003978 Sema::VariadicCallType CallType,
3979 llvm::SmallBitVector &CheckedVarArgs)
3980 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3981 numDataArgs, beg, hasVAListArg,
3982 Args, formatIdx, inFunctionCall, CallType,
3983 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003984 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003985
3986 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3987 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003988 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003989
3990 bool HandleInvalidScanfConversionSpecifier(
3991 const analyze_scanf::ScanfSpecifier &FS,
3992 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003993 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003994
Craig Toppere14c0f82014-03-12 04:55:44 +00003995 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003996};
Ted Kremenek019d2242010-01-29 01:50:07 +00003997}
Ted Kremenekab278de2010-01-28 23:39:18 +00003998
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003999void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4000 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004001 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4002 getLocationOfByte(end), /*IsStringLocation*/true,
4003 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004004}
4005
Ted Kremenekce815422010-07-19 21:25:57 +00004006bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4007 const analyze_scanf::ScanfSpecifier &FS,
4008 const char *startSpecifier,
4009 unsigned specifierLen) {
4010
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004011 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004012 FS.getConversionSpecifier();
4013
4014 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4015 getLocationOfByte(CS.getStart()),
4016 startSpecifier, specifierLen,
4017 CS.getStart(), CS.getLength());
4018}
4019
Ted Kremenek02087932010-07-16 02:11:22 +00004020bool CheckScanfHandler::HandleScanfSpecifier(
4021 const analyze_scanf::ScanfSpecifier &FS,
4022 const char *startSpecifier,
4023 unsigned specifierLen) {
4024
4025 using namespace analyze_scanf;
4026 using namespace analyze_format_string;
4027
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004028 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004029
Ted Kremenek6cd69422010-07-19 22:01:06 +00004030 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4031 // be used to decide if we are using positional arguments consistently.
4032 if (FS.consumesDataArgument()) {
4033 if (atFirstArg) {
4034 atFirstArg = false;
4035 usesPositionalArgs = FS.usesPositionalArg();
4036 }
4037 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004038 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4039 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004040 return false;
4041 }
Ted Kremenek02087932010-07-16 02:11:22 +00004042 }
4043
4044 // Check if the field with is non-zero.
4045 const OptionalAmount &Amt = FS.getFieldWidth();
4046 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4047 if (Amt.getConstantAmount() == 0) {
4048 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4049 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00004050 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4051 getLocationOfByte(Amt.getStart()),
4052 /*IsStringLocation*/true, R,
4053 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00004054 }
4055 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004056
Ted Kremenek02087932010-07-16 02:11:22 +00004057 if (!FS.consumesDataArgument()) {
4058 // FIXME: Technically specifying a precision or field width here
4059 // makes no sense. Worth issuing a warning at some point.
4060 return true;
4061 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004062
Ted Kremenek02087932010-07-16 02:11:22 +00004063 // Consume the argument.
4064 unsigned argIndex = FS.getArgIndex();
4065 if (argIndex < NumDataArgs) {
4066 // The check to see if the argIndex is valid will come later.
4067 // We set the bit here because we may exit early from this
4068 // function if we encounter some other error.
4069 CoveredArgs.set(argIndex);
4070 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004071
Ted Kremenek4407ea42010-07-20 20:04:47 +00004072 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004073 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004074 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4075 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004076 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004077 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004078 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004079 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4080 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004081
Jordan Rose92303592012-09-08 04:00:03 +00004082 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4083 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4084
Ted Kremenek02087932010-07-16 02:11:22 +00004085 // The remaining checks depend on the data arguments.
4086 if (HasVAListArg)
4087 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004088
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004089 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004090 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00004091
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004092 // Check that the argument type matches the format specifier.
4093 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004094 if (!Ex)
4095 return true;
4096
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004097 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00004098
4099 if (!AT.isValid()) {
4100 return true;
4101 }
4102
Seth Cantrellb4802962015-03-04 03:12:10 +00004103 analyze_format_string::ArgType::MatchKind match =
4104 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00004105 if (match == analyze_format_string::ArgType::Match) {
4106 return true;
4107 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004108
Seth Cantrell79340072015-03-04 05:58:08 +00004109 ScanfSpecifier fixedFS = FS;
4110 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4111 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004112
Seth Cantrell79340072015-03-04 05:58:08 +00004113 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4114 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4115 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4116 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004117
Seth Cantrell79340072015-03-04 05:58:08 +00004118 if (success) {
4119 // Get the fix string from the fixed format specifier.
4120 SmallString<128> buf;
4121 llvm::raw_svector_ostream os(buf);
4122 fixedFS.toString(os);
4123
4124 EmitFormatDiagnostic(
4125 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4126 << Ex->getType() << false << Ex->getSourceRange(),
4127 Ex->getLocStart(),
4128 /*IsStringLocation*/ false,
4129 getSpecifierRange(startSpecifier, specifierLen),
4130 FixItHint::CreateReplacement(
4131 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4132 } else {
4133 EmitFormatDiagnostic(S.PDiag(diag)
4134 << AT.getRepresentativeTypeName(S.Context)
4135 << Ex->getType() << false << Ex->getSourceRange(),
4136 Ex->getLocStart(),
4137 /*IsStringLocation*/ false,
4138 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004139 }
4140
Ted Kremenek02087932010-07-16 02:11:22 +00004141 return true;
4142}
4143
4144void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00004145 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004146 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004147 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004148 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00004149 bool inFunctionCall, VariadicCallType CallType,
4150 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004151
Ted Kremenekab278de2010-01-28 23:39:18 +00004152 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004153 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004154 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004155 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004156 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4157 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004158 return;
4159 }
Ted Kremenek02087932010-07-16 02:11:22 +00004160
Ted Kremenekab278de2010-01-28 23:39:18 +00004161 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004162 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004163 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004164 // Account for cases where the string literal is truncated in a declaration.
4165 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4166 assert(T && "String literal not of constant array type!");
4167 size_t TypeSize = T->getSize().getZExtValue();
4168 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004169 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004170
4171 // Emit a warning if the string literal is truncated and does not contain an
4172 // embedded null character.
4173 if (TypeSize <= StrRef.size() &&
4174 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4175 CheckFormatHandler::EmitFormatDiagnostic(
4176 *this, inFunctionCall, Args[format_idx],
4177 PDiag(diag::warn_printf_format_string_not_null_terminated),
4178 FExpr->getLocStart(),
4179 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4180 return;
4181 }
4182
Ted Kremenekab278de2010-01-28 23:39:18 +00004183 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004184 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004185 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004186 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004187 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4188 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004189 return;
4190 }
Ted Kremenek02087932010-07-16 02:11:22 +00004191
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004192 if (Type == FST_Printf || Type == FST_NSString ||
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004193 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek02087932010-07-16 02:11:22 +00004194 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004195 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004196 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004197 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004198
Hans Wennborg23926bd2011-12-15 10:25:47 +00004199 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004200 getLangOpts(),
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004201 Context.getTargetInfo(),
4202 Type == FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00004203 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004204 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004205 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004206 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004207 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004208
Hans Wennborg23926bd2011-12-15 10:25:47 +00004209 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004210 getLangOpts(),
4211 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004212 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004213 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004214}
4215
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004216bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4217 // Str - The format string. NOTE: this is NOT null-terminated!
4218 StringRef StrRef = FExpr->getString();
4219 const char *Str = StrRef.data();
4220 // Account for cases where the string literal is truncated in a declaration.
4221 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4222 assert(T && "String literal not of constant array type!");
4223 size_t TypeSize = T->getSize().getZExtValue();
4224 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4225 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4226 getLangOpts(),
4227 Context.getTargetInfo());
4228}
4229
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004230//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4231
4232// Returns the related absolute value function that is larger, of 0 if one
4233// does not exist.
4234static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4235 switch (AbsFunction) {
4236 default:
4237 return 0;
4238
4239 case Builtin::BI__builtin_abs:
4240 return Builtin::BI__builtin_labs;
4241 case Builtin::BI__builtin_labs:
4242 return Builtin::BI__builtin_llabs;
4243 case Builtin::BI__builtin_llabs:
4244 return 0;
4245
4246 case Builtin::BI__builtin_fabsf:
4247 return Builtin::BI__builtin_fabs;
4248 case Builtin::BI__builtin_fabs:
4249 return Builtin::BI__builtin_fabsl;
4250 case Builtin::BI__builtin_fabsl:
4251 return 0;
4252
4253 case Builtin::BI__builtin_cabsf:
4254 return Builtin::BI__builtin_cabs;
4255 case Builtin::BI__builtin_cabs:
4256 return Builtin::BI__builtin_cabsl;
4257 case Builtin::BI__builtin_cabsl:
4258 return 0;
4259
4260 case Builtin::BIabs:
4261 return Builtin::BIlabs;
4262 case Builtin::BIlabs:
4263 return Builtin::BIllabs;
4264 case Builtin::BIllabs:
4265 return 0;
4266
4267 case Builtin::BIfabsf:
4268 return Builtin::BIfabs;
4269 case Builtin::BIfabs:
4270 return Builtin::BIfabsl;
4271 case Builtin::BIfabsl:
4272 return 0;
4273
4274 case Builtin::BIcabsf:
4275 return Builtin::BIcabs;
4276 case Builtin::BIcabs:
4277 return Builtin::BIcabsl;
4278 case Builtin::BIcabsl:
4279 return 0;
4280 }
4281}
4282
4283// Returns the argument type of the absolute value function.
4284static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4285 unsigned AbsType) {
4286 if (AbsType == 0)
4287 return QualType();
4288
4289 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4290 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4291 if (Error != ASTContext::GE_None)
4292 return QualType();
4293
4294 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4295 if (!FT)
4296 return QualType();
4297
4298 if (FT->getNumParams() != 1)
4299 return QualType();
4300
4301 return FT->getParamType(0);
4302}
4303
4304// Returns the best absolute value function, or zero, based on type and
4305// current absolute value function.
4306static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4307 unsigned AbsFunctionKind) {
4308 unsigned BestKind = 0;
4309 uint64_t ArgSize = Context.getTypeSize(ArgType);
4310 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4311 Kind = getLargerAbsoluteValueFunction(Kind)) {
4312 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4313 if (Context.getTypeSize(ParamType) >= ArgSize) {
4314 if (BestKind == 0)
4315 BestKind = Kind;
4316 else if (Context.hasSameType(ParamType, ArgType)) {
4317 BestKind = Kind;
4318 break;
4319 }
4320 }
4321 }
4322 return BestKind;
4323}
4324
4325enum AbsoluteValueKind {
4326 AVK_Integer,
4327 AVK_Floating,
4328 AVK_Complex
4329};
4330
4331static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4332 if (T->isIntegralOrEnumerationType())
4333 return AVK_Integer;
4334 if (T->isRealFloatingType())
4335 return AVK_Floating;
4336 if (T->isAnyComplexType())
4337 return AVK_Complex;
4338
4339 llvm_unreachable("Type not integer, floating, or complex");
4340}
4341
4342// Changes the absolute value function to a different type. Preserves whether
4343// the function is a builtin.
4344static unsigned changeAbsFunction(unsigned AbsKind,
4345 AbsoluteValueKind ValueKind) {
4346 switch (ValueKind) {
4347 case AVK_Integer:
4348 switch (AbsKind) {
4349 default:
4350 return 0;
4351 case Builtin::BI__builtin_fabsf:
4352 case Builtin::BI__builtin_fabs:
4353 case Builtin::BI__builtin_fabsl:
4354 case Builtin::BI__builtin_cabsf:
4355 case Builtin::BI__builtin_cabs:
4356 case Builtin::BI__builtin_cabsl:
4357 return Builtin::BI__builtin_abs;
4358 case Builtin::BIfabsf:
4359 case Builtin::BIfabs:
4360 case Builtin::BIfabsl:
4361 case Builtin::BIcabsf:
4362 case Builtin::BIcabs:
4363 case Builtin::BIcabsl:
4364 return Builtin::BIabs;
4365 }
4366 case AVK_Floating:
4367 switch (AbsKind) {
4368 default:
4369 return 0;
4370 case Builtin::BI__builtin_abs:
4371 case Builtin::BI__builtin_labs:
4372 case Builtin::BI__builtin_llabs:
4373 case Builtin::BI__builtin_cabsf:
4374 case Builtin::BI__builtin_cabs:
4375 case Builtin::BI__builtin_cabsl:
4376 return Builtin::BI__builtin_fabsf;
4377 case Builtin::BIabs:
4378 case Builtin::BIlabs:
4379 case Builtin::BIllabs:
4380 case Builtin::BIcabsf:
4381 case Builtin::BIcabs:
4382 case Builtin::BIcabsl:
4383 return Builtin::BIfabsf;
4384 }
4385 case AVK_Complex:
4386 switch (AbsKind) {
4387 default:
4388 return 0;
4389 case Builtin::BI__builtin_abs:
4390 case Builtin::BI__builtin_labs:
4391 case Builtin::BI__builtin_llabs:
4392 case Builtin::BI__builtin_fabsf:
4393 case Builtin::BI__builtin_fabs:
4394 case Builtin::BI__builtin_fabsl:
4395 return Builtin::BI__builtin_cabsf;
4396 case Builtin::BIabs:
4397 case Builtin::BIlabs:
4398 case Builtin::BIllabs:
4399 case Builtin::BIfabsf:
4400 case Builtin::BIfabs:
4401 case Builtin::BIfabsl:
4402 return Builtin::BIcabsf;
4403 }
4404 }
4405 llvm_unreachable("Unable to convert function");
4406}
4407
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004408static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004409 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4410 if (!FnInfo)
4411 return 0;
4412
4413 switch (FDecl->getBuiltinID()) {
4414 default:
4415 return 0;
4416 case Builtin::BI__builtin_abs:
4417 case Builtin::BI__builtin_fabs:
4418 case Builtin::BI__builtin_fabsf:
4419 case Builtin::BI__builtin_fabsl:
4420 case Builtin::BI__builtin_labs:
4421 case Builtin::BI__builtin_llabs:
4422 case Builtin::BI__builtin_cabs:
4423 case Builtin::BI__builtin_cabsf:
4424 case Builtin::BI__builtin_cabsl:
4425 case Builtin::BIabs:
4426 case Builtin::BIlabs:
4427 case Builtin::BIllabs:
4428 case Builtin::BIfabs:
4429 case Builtin::BIfabsf:
4430 case Builtin::BIfabsl:
4431 case Builtin::BIcabs:
4432 case Builtin::BIcabsf:
4433 case Builtin::BIcabsl:
4434 return FDecl->getBuiltinID();
4435 }
4436 llvm_unreachable("Unknown Builtin type");
4437}
4438
4439// If the replacement is valid, emit a note with replacement function.
4440// Additionally, suggest including the proper header if not already included.
4441static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004442 unsigned AbsKind, QualType ArgType) {
4443 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004444 const char *HeaderName = nullptr;
4445 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004446 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4447 FunctionName = "std::abs";
4448 if (ArgType->isIntegralOrEnumerationType()) {
4449 HeaderName = "cstdlib";
4450 } else if (ArgType->isRealFloatingType()) {
4451 HeaderName = "cmath";
4452 } else {
4453 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004454 }
Richard Trieubeffb832014-04-15 23:47:53 +00004455
4456 // Lookup all std::abs
4457 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004458 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004459 R.suppressDiagnostics();
4460 S.LookupQualifiedName(R, Std);
4461
4462 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004463 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004464 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4465 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4466 } else {
4467 FDecl = dyn_cast<FunctionDecl>(I);
4468 }
4469 if (!FDecl)
4470 continue;
4471
4472 // Found std::abs(), check that they are the right ones.
4473 if (FDecl->getNumParams() != 1)
4474 continue;
4475
4476 // Check that the parameter type can handle the argument.
4477 QualType ParamType = FDecl->getParamDecl(0)->getType();
4478 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4479 S.Context.getTypeSize(ArgType) <=
4480 S.Context.getTypeSize(ParamType)) {
4481 // Found a function, don't need the header hint.
4482 EmitHeaderHint = false;
4483 break;
4484 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004485 }
Richard Trieubeffb832014-04-15 23:47:53 +00004486 }
4487 } else {
4488 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4489 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4490
4491 if (HeaderName) {
4492 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4493 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4494 R.suppressDiagnostics();
4495 S.LookupName(R, S.getCurScope());
4496
4497 if (R.isSingleResult()) {
4498 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4499 if (FD && FD->getBuiltinID() == AbsKind) {
4500 EmitHeaderHint = false;
4501 } else {
4502 return;
4503 }
4504 } else if (!R.empty()) {
4505 return;
4506 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004507 }
4508 }
4509
4510 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00004511 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004512
Richard Trieubeffb832014-04-15 23:47:53 +00004513 if (!HeaderName)
4514 return;
4515
4516 if (!EmitHeaderHint)
4517 return;
4518
Alp Toker5d96e0a2014-07-11 20:53:51 +00004519 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4520 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00004521}
4522
4523static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4524 if (!FDecl)
4525 return false;
4526
4527 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4528 return false;
4529
4530 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4531
4532 while (ND && ND->isInlineNamespace()) {
4533 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004534 }
Richard Trieubeffb832014-04-15 23:47:53 +00004535
4536 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4537 return false;
4538
4539 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4540 return false;
4541
4542 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004543}
4544
4545// Warn when using the wrong abs() function.
4546void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4547 const FunctionDecl *FDecl,
4548 IdentifierInfo *FnInfo) {
4549 if (Call->getNumArgs() != 1)
4550 return;
4551
4552 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00004553 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4554 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004555 return;
4556
4557 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4558 QualType ParamType = Call->getArg(0)->getType();
4559
Alp Toker5d96e0a2014-07-11 20:53:51 +00004560 // Unsigned types cannot be negative. Suggest removing the absolute value
4561 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004562 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00004563 const char *FunctionName =
4564 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004565 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4566 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00004567 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004568 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4569 return;
4570 }
4571
Richard Trieubeffb832014-04-15 23:47:53 +00004572 // std::abs has overloads which prevent most of the absolute value problems
4573 // from occurring.
4574 if (IsStdAbs)
4575 return;
4576
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004577 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4578 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4579
4580 // The argument and parameter are the same kind. Check if they are the right
4581 // size.
4582 if (ArgValueKind == ParamValueKind) {
4583 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4584 return;
4585
4586 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4587 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4588 << FDecl << ArgType << ParamType;
4589
4590 if (NewAbsKind == 0)
4591 return;
4592
4593 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004594 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004595 return;
4596 }
4597
4598 // ArgValueKind != ParamValueKind
4599 // The wrong type of absolute value function was used. Attempt to find the
4600 // proper one.
4601 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4602 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4603 if (NewAbsKind == 0)
4604 return;
4605
4606 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4607 << FDecl << ParamValueKind << ArgValueKind;
4608
4609 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004610 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004611 return;
4612}
4613
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004614//===--- CHECK: Standard memory functions ---------------------------------===//
4615
Nico Weber0e6daef2013-12-26 23:38:39 +00004616/// \brief Takes the expression passed to the size_t parameter of functions
4617/// such as memcmp, strncat, etc and warns if it's a comparison.
4618///
4619/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4620static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4621 IdentifierInfo *FnName,
4622 SourceLocation FnLoc,
4623 SourceLocation RParenLoc) {
4624 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4625 if (!Size)
4626 return false;
4627
4628 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4629 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4630 return false;
4631
Nico Weber0e6daef2013-12-26 23:38:39 +00004632 SourceRange SizeRange = Size->getSourceRange();
4633 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4634 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00004635 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004636 << FnName << FixItHint::CreateInsertion(
4637 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00004638 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00004639 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00004640 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00004641 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4642 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00004643
4644 return true;
4645}
4646
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004647/// \brief Determine whether the given type is or contains a dynamic class type
4648/// (e.g., whether it has a vtable).
4649static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4650 bool &IsContained) {
4651 // Look through array types while ignoring qualifiers.
4652 const Type *Ty = T->getBaseElementTypeUnsafe();
4653 IsContained = false;
4654
4655 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4656 RD = RD ? RD->getDefinition() : nullptr;
4657 if (!RD)
4658 return nullptr;
4659
4660 if (RD->isDynamicClass())
4661 return RD;
4662
4663 // Check all the fields. If any bases were dynamic, the class is dynamic.
4664 // It's impossible for a class to transitively contain itself by value, so
4665 // infinite recursion is impossible.
4666 for (auto *FD : RD->fields()) {
4667 bool SubContained;
4668 if (const CXXRecordDecl *ContainedRD =
4669 getContainedDynamicClass(FD->getType(), SubContained)) {
4670 IsContained = true;
4671 return ContainedRD;
4672 }
4673 }
4674
4675 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004676}
4677
Chandler Carruth889ed862011-06-21 23:04:20 +00004678/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004679/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00004680static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004681 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004682 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4683 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4684 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004685
Craig Topperc3ec1492014-05-26 06:22:03 +00004686 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004687}
4688
Chandler Carruth889ed862011-06-21 23:04:20 +00004689/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00004690static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004691 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4692 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4693 if (SizeOf->getKind() == clang::UETT_SizeOf)
4694 return SizeOf->getTypeOfArgument();
4695
4696 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004697}
4698
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004699/// \brief Check for dangerous or invalid arguments to memset().
4700///
Chandler Carruthac687262011-06-03 06:23:57 +00004701/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004702/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4703/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004704///
4705/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004706void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004707 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004708 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004709 assert(BId != 0);
4710
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004711 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004712 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004713 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004714 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004715 return;
4716
Anna Zaks22122702012-01-17 00:37:07 +00004717 unsigned LastArg = (BId == Builtin::BImemset ||
4718 BId == Builtin::BIstrndup ? 1 : 2);
4719 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004720 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004721
Nico Weber0e6daef2013-12-26 23:38:39 +00004722 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4723 Call->getLocStart(), Call->getRParenLoc()))
4724 return;
4725
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004726 // We have special checking when the length is a sizeof expression.
4727 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4728 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4729 llvm::FoldingSetNodeID SizeOfArgID;
4730
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004731 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4732 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004733 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004734
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004735 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00004736 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004737 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00004738 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004739
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004740 // Never warn about void type pointers. This can be used to suppress
4741 // false positives.
4742 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004743 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004744
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004745 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4746 // actually comparing the expressions for equality. Because computing the
4747 // expression IDs can be expensive, we only do this if the diagnostic is
4748 // enabled.
4749 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004750 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4751 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004752 // We only compute IDs for expressions if the warning is enabled, and
4753 // cache the sizeof arg's ID.
4754 if (SizeOfArgID == llvm::FoldingSetNodeID())
4755 SizeOfArg->Profile(SizeOfArgID, Context, true);
4756 llvm::FoldingSetNodeID DestID;
4757 Dest->Profile(DestID, Context, true);
4758 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004759 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4760 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004761 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004762 StringRef ReadableName = FnName->getName();
4763
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004764 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004765 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004766 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004767 if (!PointeeTy->isIncompleteType() &&
4768 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004769 ActionIdx = 2; // If the pointee's size is sizeof(char),
4770 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004771
4772 // If the function is defined as a builtin macro, do not show macro
4773 // expansion.
4774 SourceLocation SL = SizeOfArg->getExprLoc();
4775 SourceRange DSR = Dest->getSourceRange();
4776 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004777 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004778
4779 if (SM.isMacroArgExpansion(SL)) {
4780 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4781 SL = SM.getSpellingLoc(SL);
4782 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4783 SM.getSpellingLoc(DSR.getEnd()));
4784 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4785 SM.getSpellingLoc(SSR.getEnd()));
4786 }
4787
Anna Zaksd08d9152012-05-30 23:14:52 +00004788 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004789 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004790 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004791 << PointeeTy
4792 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004793 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004794 << SSR);
4795 DiagRuntimeBehavior(SL, SizeOfArg,
4796 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4797 << ActionIdx
4798 << SSR);
4799
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004800 break;
4801 }
4802 }
4803
4804 // Also check for cases where the sizeof argument is the exact same
4805 // type as the memory argument, and where it points to a user-defined
4806 // record type.
4807 if (SizeOfArgTy != QualType()) {
4808 if (PointeeTy->isRecordType() &&
4809 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4810 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4811 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4812 << FnName << SizeOfArgTy << ArgIdx
4813 << PointeeTy << Dest->getSourceRange()
4814 << LenExpr->getSourceRange());
4815 break;
4816 }
Nico Weberc5e73862011-06-14 16:14:58 +00004817 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00004818 } else if (DestTy->isArrayType()) {
4819 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00004820 }
Nico Weberc5e73862011-06-14 16:14:58 +00004821
Nico Weberc44b35e2015-03-21 17:37:46 +00004822 if (PointeeTy == QualType())
4823 continue;
Anna Zaks22122702012-01-17 00:37:07 +00004824
Nico Weberc44b35e2015-03-21 17:37:46 +00004825 // Always complain about dynamic classes.
4826 bool IsContained;
4827 if (const CXXRecordDecl *ContainedRD =
4828 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00004829
Nico Weberc44b35e2015-03-21 17:37:46 +00004830 unsigned OperationType = 0;
4831 // "overwritten" if we're warning about the destination for any call
4832 // but memcmp; otherwise a verb appropriate to the call.
4833 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4834 if (BId == Builtin::BImemcpy)
4835 OperationType = 1;
4836 else if(BId == Builtin::BImemmove)
4837 OperationType = 2;
4838 else if (BId == Builtin::BImemcmp)
4839 OperationType = 3;
4840 }
4841
John McCall31168b02011-06-15 23:02:42 +00004842 DiagRuntimeBehavior(
4843 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00004844 PDiag(diag::warn_dyn_class_memaccess)
4845 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
4846 << FnName << IsContained << ContainedRD << OperationType
4847 << Call->getCallee()->getSourceRange());
4848 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4849 BId != Builtin::BImemset)
4850 DiagRuntimeBehavior(
4851 Dest->getExprLoc(), Dest,
4852 PDiag(diag::warn_arc_object_memaccess)
4853 << ArgIdx << FnName << PointeeTy
4854 << Call->getCallee()->getSourceRange());
4855 else
4856 continue;
4857
4858 DiagRuntimeBehavior(
4859 Dest->getExprLoc(), Dest,
4860 PDiag(diag::note_bad_memaccess_silence)
4861 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4862 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004863 }
Nico Weberc44b35e2015-03-21 17:37:46 +00004864
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004865}
4866
Ted Kremenek6865f772011-08-18 20:55:45 +00004867// A little helper routine: ignore addition and subtraction of integer literals.
4868// This intentionally does not ignore all integer constant expressions because
4869// we don't want to remove sizeof().
4870static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4871 Ex = Ex->IgnoreParenCasts();
4872
4873 for (;;) {
4874 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4875 if (!BO || !BO->isAdditiveOp())
4876 break;
4877
4878 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4879 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4880
4881 if (isa<IntegerLiteral>(RHS))
4882 Ex = LHS;
4883 else if (isa<IntegerLiteral>(LHS))
4884 Ex = RHS;
4885 else
4886 break;
4887 }
4888
4889 return Ex;
4890}
4891
Anna Zaks13b08572012-08-08 21:42:23 +00004892static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4893 ASTContext &Context) {
4894 // Only handle constant-sized or VLAs, but not flexible members.
4895 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4896 // Only issue the FIXIT for arrays of size > 1.
4897 if (CAT->getSize().getSExtValue() <= 1)
4898 return false;
4899 } else if (!Ty->isVariableArrayType()) {
4900 return false;
4901 }
4902 return true;
4903}
4904
Ted Kremenek6865f772011-08-18 20:55:45 +00004905// Warn if the user has made the 'size' argument to strlcpy or strlcat
4906// be the size of the source, instead of the destination.
4907void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4908 IdentifierInfo *FnName) {
4909
4910 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00004911 unsigned NumArgs = Call->getNumArgs();
4912 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00004913 return;
4914
4915 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4916 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004917 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00004918
4919 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4920 Call->getLocStart(), Call->getRParenLoc()))
4921 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004922
4923 // Look for 'strlcpy(dst, x, sizeof(x))'
4924 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4925 CompareWithSrc = Ex;
4926 else {
4927 // Look for 'strlcpy(dst, x, strlen(x))'
4928 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004929 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4930 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004931 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4932 }
4933 }
4934
4935 if (!CompareWithSrc)
4936 return;
4937
4938 // Determine if the argument to sizeof/strlen is equal to the source
4939 // argument. In principle there's all kinds of things you could do
4940 // here, for instance creating an == expression and evaluating it with
4941 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4942 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4943 if (!SrcArgDRE)
4944 return;
4945
4946 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4947 if (!CompareWithSrcDRE ||
4948 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4949 return;
4950
4951 const Expr *OriginalSizeArg = Call->getArg(2);
4952 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4953 << OriginalSizeArg->getSourceRange() << FnName;
4954
4955 // Output a FIXIT hint if the destination is an array (rather than a
4956 // pointer to an array). This could be enhanced to handle some
4957 // pointers if we know the actual size, like if DstArg is 'array+2'
4958 // we could say 'sizeof(array)-2'.
4959 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004960 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004961 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004962
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004963 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004964 llvm::raw_svector_ostream OS(sizeString);
4965 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004966 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004967 OS << ")";
4968
4969 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4970 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4971 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004972}
4973
Anna Zaks314cd092012-02-01 19:08:57 +00004974/// Check if two expressions refer to the same declaration.
4975static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4976 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4977 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4978 return D1->getDecl() == D2->getDecl();
4979 return false;
4980}
4981
4982static const Expr *getStrlenExprArg(const Expr *E) {
4983 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4984 const FunctionDecl *FD = CE->getDirectCallee();
4985 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00004986 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004987 return CE->getArg(0)->IgnoreParenCasts();
4988 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004989 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004990}
4991
4992// Warn on anti-patterns as the 'size' argument to strncat.
4993// The correct size argument should look like following:
4994// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4995void Sema::CheckStrncatArguments(const CallExpr *CE,
4996 IdentifierInfo *FnName) {
4997 // Don't crash if the user has the wrong number of arguments.
4998 if (CE->getNumArgs() < 3)
4999 return;
5000 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5001 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5002 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5003
Nico Weber0e6daef2013-12-26 23:38:39 +00005004 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5005 CE->getRParenLoc()))
5006 return;
5007
Anna Zaks314cd092012-02-01 19:08:57 +00005008 // Identify common expressions, which are wrongly used as the size argument
5009 // to strncat and may lead to buffer overflows.
5010 unsigned PatternType = 0;
5011 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5012 // - sizeof(dst)
5013 if (referToTheSameDecl(SizeOfArg, DstArg))
5014 PatternType = 1;
5015 // - sizeof(src)
5016 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5017 PatternType = 2;
5018 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5019 if (BE->getOpcode() == BO_Sub) {
5020 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5021 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5022 // - sizeof(dst) - strlen(dst)
5023 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5024 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5025 PatternType = 1;
5026 // - sizeof(src) - (anything)
5027 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5028 PatternType = 2;
5029 }
5030 }
5031
5032 if (PatternType == 0)
5033 return;
5034
Anna Zaks5069aa32012-02-03 01:27:37 +00005035 // Generate the diagnostic.
5036 SourceLocation SL = LenArg->getLocStart();
5037 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005038 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00005039
5040 // If the function is defined as a builtin macro, do not show macro expansion.
5041 if (SM.isMacroArgExpansion(SL)) {
5042 SL = SM.getSpellingLoc(SL);
5043 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5044 SM.getSpellingLoc(SR.getEnd()));
5045 }
5046
Anna Zaks13b08572012-08-08 21:42:23 +00005047 // Check if the destination is an array (rather than a pointer to an array).
5048 QualType DstTy = DstArg->getType();
5049 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5050 Context);
5051 if (!isKnownSizeArray) {
5052 if (PatternType == 1)
5053 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5054 else
5055 Diag(SL, diag::warn_strncat_src_size) << SR;
5056 return;
5057 }
5058
Anna Zaks314cd092012-02-01 19:08:57 +00005059 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00005060 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005061 else
Anna Zaks5069aa32012-02-03 01:27:37 +00005062 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005063
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005064 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00005065 llvm::raw_svector_ostream OS(sizeString);
5066 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005067 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005068 OS << ") - ";
5069 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005070 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005071 OS << ") - 1";
5072
Anna Zaks5069aa32012-02-03 01:27:37 +00005073 Diag(SL, diag::note_strncat_wrong_size)
5074 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005075}
5076
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005077//===--- CHECK: Return Address of Stack Variable --------------------------===//
5078
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005079static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5080 Decl *ParentDecl);
5081static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5082 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005083
5084/// CheckReturnStackAddr - Check if a return statement returns the address
5085/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005086static void
5087CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5088 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005089
Craig Topperc3ec1492014-05-26 06:22:03 +00005090 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005091 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005092
5093 // Perform checking for returned stack addresses, local blocks,
5094 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005095 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005096 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005097 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005098 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005099 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005100 }
5101
Craig Topperc3ec1492014-05-26 06:22:03 +00005102 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005103 return; // Nothing suspicious was found.
5104
5105 SourceLocation diagLoc;
5106 SourceRange diagRange;
5107 if (refVars.empty()) {
5108 diagLoc = stackE->getLocStart();
5109 diagRange = stackE->getSourceRange();
5110 } else {
5111 // We followed through a reference variable. 'stackE' contains the
5112 // problematic expression but we will warn at the return statement pointing
5113 // at the reference variable. We will later display the "trail" of
5114 // reference variables using notes.
5115 diagLoc = refVars[0]->getLocStart();
5116 diagRange = refVars[0]->getSourceRange();
5117 }
5118
5119 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005120 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005121 : diag::warn_ret_stack_addr)
5122 << DR->getDecl()->getDeclName() << diagRange;
5123 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005124 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005125 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005126 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005127 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005128 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
5129 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005130 << diagRange;
5131 }
5132
5133 // Display the "trail" of reference variables that we followed until we
5134 // found the problematic expression using notes.
5135 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5136 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5137 // If this var binds to another reference var, show the range of the next
5138 // var, otherwise the var binds to the problematic expression, in which case
5139 // show the range of the expression.
5140 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5141 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005142 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5143 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005144 }
5145}
5146
5147/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5148/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005149/// to a location on the stack, a local block, an address of a label, or a
5150/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005151/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005152/// encounter a subexpression that (1) clearly does not lead to one of the
5153/// above problematic expressions (2) is something we cannot determine leads to
5154/// a problematic expression based on such local checking.
5155///
5156/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5157/// the expression that they point to. Such variables are added to the
5158/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005159///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005160/// EvalAddr processes expressions that are pointers that are used as
5161/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005162/// At the base case of the recursion is a check for the above problematic
5163/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005164///
5165/// This implementation handles:
5166///
5167/// * pointer-to-pointer casts
5168/// * implicit conversions from array references to pointers
5169/// * taking the address of fields
5170/// * arbitrary interplay between "&" and "*" operators
5171/// * pointer arithmetic from an address of a stack variable
5172/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005173static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5174 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005175 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005176 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005177
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005178 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005179 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005180 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005181 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005182 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005183
Peter Collingbourne91147592011-04-15 00:35:48 +00005184 E = E->IgnoreParens();
5185
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005186 // Our "symbolic interpreter" is just a dispatch off the currently
5187 // viewed AST node. We then recursively traverse the AST by calling
5188 // EvalAddr and EvalVal appropriately.
5189 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005190 case Stmt::DeclRefExprClass: {
5191 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5192
Richard Smith40f08eb2014-01-30 22:05:38 +00005193 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005194 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005195 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005196
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005197 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5198 // If this is a reference variable, follow through to the expression that
5199 // it points to.
5200 if (V->hasLocalStorage() &&
5201 V->getType()->isReferenceType() && V->hasInit()) {
5202 // Add the reference variable to the "trail".
5203 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005204 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005205 }
5206
Craig Topperc3ec1492014-05-26 06:22:03 +00005207 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005208 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005209
Chris Lattner934edb22007-12-28 05:31:15 +00005210 case Stmt::UnaryOperatorClass: {
5211 // The only unary operator that make sense to handle here
5212 // is AddrOf. All others don't make sense as pointers.
5213 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005214
John McCalle3027922010-08-25 11:45:40 +00005215 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005216 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005217 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005218 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005219 }
Mike Stump11289f42009-09-09 15:08:12 +00005220
Chris Lattner934edb22007-12-28 05:31:15 +00005221 case Stmt::BinaryOperatorClass: {
5222 // Handle pointer arithmetic. All other binary operators are not valid
5223 // in this context.
5224 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005225 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005226
John McCalle3027922010-08-25 11:45:40 +00005227 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005228 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005229
Chris Lattner934edb22007-12-28 05:31:15 +00005230 Expr *Base = B->getLHS();
5231
5232 // Determine which argument is the real pointer base. It could be
5233 // the RHS argument instead of the LHS.
5234 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005235
Chris Lattner934edb22007-12-28 05:31:15 +00005236 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005237 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005238 }
Steve Naroff2752a172008-09-10 19:17:48 +00005239
Chris Lattner934edb22007-12-28 05:31:15 +00005240 // For conditional operators we need to see if either the LHS or RHS are
5241 // valid DeclRefExpr*s. If one of them is valid, we return it.
5242 case Stmt::ConditionalOperatorClass: {
5243 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005244
Chris Lattner934edb22007-12-28 05:31:15 +00005245 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005246 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5247 if (Expr *LHSExpr = C->getLHS()) {
5248 // In C++, we can have a throw-expression, which has 'void' type.
5249 if (!LHSExpr->getType()->isVoidType())
5250 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005251 return LHS;
5252 }
Chris Lattner934edb22007-12-28 05:31:15 +00005253
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005254 // In C++, we can have a throw-expression, which has 'void' type.
5255 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005256 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005257
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005258 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005259 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005260
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005261 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00005262 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005263 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00005264 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005265
5266 case Stmt::AddrLabelExprClass:
5267 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00005268
John McCall28fc7092011-11-10 05:35:25 +00005269 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005270 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5271 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005272
Ted Kremenekc3b4c522008-08-07 00:49:01 +00005273 // For casts, we need to handle conversions from arrays to
5274 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00005275 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00005276 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005277 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00005278 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00005279 case Stmt::CXXStaticCastExprClass:
5280 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00005281 case Stmt::CXXConstCastExprClass:
5282 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00005283 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5284 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00005285 case CK_LValueToRValue:
5286 case CK_NoOp:
5287 case CK_BaseToDerived:
5288 case CK_DerivedToBase:
5289 case CK_UncheckedDerivedToBase:
5290 case CK_Dynamic:
5291 case CK_CPointerToObjCPointerCast:
5292 case CK_BlockPointerToObjCPointerCast:
5293 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005294 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005295
5296 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005297 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005298
Richard Trieudadefde2014-07-02 04:39:38 +00005299 case CK_BitCast:
5300 if (SubExpr->getType()->isAnyPointerType() ||
5301 SubExpr->getType()->isBlockPointerType() ||
5302 SubExpr->getType()->isObjCQualifiedIdType())
5303 return EvalAddr(SubExpr, refVars, ParentDecl);
5304 else
5305 return nullptr;
5306
Eli Friedman8195ad72012-02-23 23:04:32 +00005307 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005308 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00005309 }
Chris Lattner934edb22007-12-28 05:31:15 +00005310 }
Mike Stump11289f42009-09-09 15:08:12 +00005311
Douglas Gregorfe314812011-06-21 17:03:29 +00005312 case Stmt::MaterializeTemporaryExprClass:
5313 if (Expr *Result = EvalAddr(
5314 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005315 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005316 return Result;
5317
5318 return E;
5319
Chris Lattner934edb22007-12-28 05:31:15 +00005320 // Everything else: we simply don't reason about them.
5321 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005322 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00005323 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005324}
Mike Stump11289f42009-09-09 15:08:12 +00005325
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005326
5327/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5328/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005329static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5330 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005331do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005332 // We should only be called for evaluating non-pointer expressions, or
5333 // expressions with a pointer type that are not used as references but instead
5334 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00005335
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005336 // Our "symbolic interpreter" is just a dispatch off the currently
5337 // viewed AST node. We then recursively traverse the AST by calling
5338 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00005339
5340 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005341 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005342 case Stmt::ImplicitCastExprClass: {
5343 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00005344 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005345 E = IE->getSubExpr();
5346 continue;
5347 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005348 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00005349 }
5350
John McCall28fc7092011-11-10 05:35:25 +00005351 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005352 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005353
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005354 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005355 // When we hit a DeclRefExpr we are looking at code that refers to a
5356 // variable's name. If it's not a reference variable we check if it has
5357 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005358 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005359
Richard Smith40f08eb2014-01-30 22:05:38 +00005360 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005361 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005362 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005363
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005364 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5365 // Check if it refers to itself, e.g. "int& i = i;".
5366 if (V == ParentDecl)
5367 return DR;
5368
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005369 if (V->hasLocalStorage()) {
5370 if (!V->getType()->isReferenceType())
5371 return DR;
5372
5373 // Reference variable, follow through to the expression that
5374 // it points to.
5375 if (V->hasInit()) {
5376 // Add the reference variable to the "trail".
5377 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005378 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005379 }
5380 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005381 }
Mike Stump11289f42009-09-09 15:08:12 +00005382
Craig Topperc3ec1492014-05-26 06:22:03 +00005383 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005384 }
Mike Stump11289f42009-09-09 15:08:12 +00005385
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005386 case Stmt::UnaryOperatorClass: {
5387 // The only unary operator that make sense to handle here
5388 // is Deref. All others don't resolve to a "name." This includes
5389 // handling all sorts of rvalues passed to a unary operator.
5390 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005391
John McCalle3027922010-08-25 11:45:40 +00005392 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005393 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005394
Craig Topperc3ec1492014-05-26 06:22:03 +00005395 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005396 }
Mike Stump11289f42009-09-09 15:08:12 +00005397
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005398 case Stmt::ArraySubscriptExprClass: {
5399 // Array subscripts are potential references to data on the stack. We
5400 // retrieve the DeclRefExpr* for the array variable if it indeed
5401 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005402 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005403 }
Mike Stump11289f42009-09-09 15:08:12 +00005404
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005405 case Stmt::ConditionalOperatorClass: {
5406 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005407 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005408 ConditionalOperator *C = cast<ConditionalOperator>(E);
5409
Anders Carlsson801c5c72007-11-30 19:04:31 +00005410 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005411 if (Expr *LHSExpr = C->getLHS()) {
5412 // In C++, we can have a throw-expression, which has 'void' type.
5413 if (!LHSExpr->getType()->isVoidType())
5414 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5415 return LHS;
5416 }
5417
5418 // In C++, we can have a throw-expression, which has 'void' type.
5419 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005420 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005421
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005422 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005423 }
Mike Stump11289f42009-09-09 15:08:12 +00005424
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005425 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005426 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005427 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005428
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005429 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005430 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005431 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005432
5433 // Check whether the member type is itself a reference, in which case
5434 // we're not going to refer to the member, but to what the member refers to.
5435 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005436 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005437
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005438 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005439 }
Mike Stump11289f42009-09-09 15:08:12 +00005440
Douglas Gregorfe314812011-06-21 17:03:29 +00005441 case Stmt::MaterializeTemporaryExprClass:
5442 if (Expr *Result = EvalVal(
5443 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005444 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005445 return Result;
5446
5447 return E;
5448
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005449 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005450 // Check that we don't return or take the address of a reference to a
5451 // temporary. This is only useful in C++.
5452 if (!E->isTypeDependent() && E->isRValue())
5453 return E;
5454
5455 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005456 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005457 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005458} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005459}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005460
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005461void
5462Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5463 SourceLocation ReturnLoc,
5464 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005465 const AttrVec *Attrs,
5466 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005467 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5468
5469 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00005470 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5471 CheckNonNullExpr(*this, RetValExp))
5472 Diag(ReturnLoc, diag::warn_null_ret)
5473 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00005474
5475 // C++11 [basic.stc.dynamic.allocation]p4:
5476 // If an allocation function declared with a non-throwing
5477 // exception-specification fails to allocate storage, it shall return
5478 // a null pointer. Any other allocation function that fails to allocate
5479 // storage shall indicate failure only by throwing an exception [...]
5480 if (FD) {
5481 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5482 if (Op == OO_New || Op == OO_Array_New) {
5483 const FunctionProtoType *Proto
5484 = FD->getType()->castAs<FunctionProtoType>();
5485 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5486 CheckNonNullExpr(*this, RetValExp))
5487 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5488 << FD << getLangOpts().CPlusPlus11;
5489 }
5490 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005491}
5492
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005493//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5494
5495/// Check for comparisons of floating point operands using != and ==.
5496/// Issue a warning if these are no self-comparisons, as they are not likely
5497/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00005498void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00005499 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5500 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005501
5502 // Special case: check for x == x (which is OK).
5503 // Do not emit warnings for such cases.
5504 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5505 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5506 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00005507 return;
Mike Stump11289f42009-09-09 15:08:12 +00005508
5509
Ted Kremenekeda40e22007-11-29 00:59:04 +00005510 // Special case: check for comparisons against literals that can be exactly
5511 // represented by APFloat. In such cases, do not emit a warning. This
5512 // is a heuristic: often comparison against such literals are used to
5513 // detect if a value in a variable has not changed. This clearly can
5514 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00005515 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5516 if (FLL->isExact())
5517 return;
5518 } else
5519 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5520 if (FLR->isExact())
5521 return;
Mike Stump11289f42009-09-09 15:08:12 +00005522
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005523 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00005524 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005525 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005526 return;
Mike Stump11289f42009-09-09 15:08:12 +00005527
David Blaikie1f4ff152012-07-16 20:47:22 +00005528 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005529 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005530 return;
Mike Stump11289f42009-09-09 15:08:12 +00005531
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005532 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00005533 Diag(Loc, diag::warn_floatingpoint_eq)
5534 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005535}
John McCallca01b222010-01-04 23:21:16 +00005536
John McCall70aa5392010-01-06 05:24:50 +00005537//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5538//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00005539
John McCall70aa5392010-01-06 05:24:50 +00005540namespace {
John McCallca01b222010-01-04 23:21:16 +00005541
John McCall70aa5392010-01-06 05:24:50 +00005542/// Structure recording the 'active' range of an integer-valued
5543/// expression.
5544struct IntRange {
5545 /// The number of bits active in the int.
5546 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00005547
John McCall70aa5392010-01-06 05:24:50 +00005548 /// True if the int is known not to have negative values.
5549 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00005550
John McCall70aa5392010-01-06 05:24:50 +00005551 IntRange(unsigned Width, bool NonNegative)
5552 : Width(Width), NonNegative(NonNegative)
5553 {}
John McCallca01b222010-01-04 23:21:16 +00005554
John McCall817d4af2010-11-10 23:38:19 +00005555 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00005556 static IntRange forBoolType() {
5557 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00005558 }
5559
John McCall817d4af2010-11-10 23:38:19 +00005560 /// Returns the range of an opaque value of the given integral type.
5561 static IntRange forValueOfType(ASTContext &C, QualType T) {
5562 return forValueOfCanonicalType(C,
5563 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00005564 }
5565
John McCall817d4af2010-11-10 23:38:19 +00005566 /// Returns the range of an opaque value of a canonical integral type.
5567 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00005568 assert(T->isCanonicalUnqualified());
5569
5570 if (const VectorType *VT = dyn_cast<VectorType>(T))
5571 T = VT->getElementType().getTypePtr();
5572 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5573 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005574 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5575 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00005576
David Majnemer6a426652013-06-07 22:07:20 +00005577 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00005578 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00005579 EnumDecl *Enum = ET->getDecl();
5580 if (!Enum->isCompleteDefinition())
5581 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00005582
David Majnemer6a426652013-06-07 22:07:20 +00005583 unsigned NumPositive = Enum->getNumPositiveBits();
5584 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00005585
David Majnemer6a426652013-06-07 22:07:20 +00005586 if (NumNegative == 0)
5587 return IntRange(NumPositive, true/*NonNegative*/);
5588 else
5589 return IntRange(std::max(NumPositive + 1, NumNegative),
5590 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00005591 }
John McCall70aa5392010-01-06 05:24:50 +00005592
5593 const BuiltinType *BT = cast<BuiltinType>(T);
5594 assert(BT->isInteger());
5595
5596 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5597 }
5598
John McCall817d4af2010-11-10 23:38:19 +00005599 /// Returns the "target" range of a canonical integral type, i.e.
5600 /// the range of values expressible in the type.
5601 ///
5602 /// This matches forValueOfCanonicalType except that enums have the
5603 /// full range of their type, not the range of their enumerators.
5604 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5605 assert(T->isCanonicalUnqualified());
5606
5607 if (const VectorType *VT = dyn_cast<VectorType>(T))
5608 T = VT->getElementType().getTypePtr();
5609 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5610 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005611 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5612 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005613 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00005614 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005615
5616 const BuiltinType *BT = cast<BuiltinType>(T);
5617 assert(BT->isInteger());
5618
5619 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5620 }
5621
5622 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00005623 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00005624 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00005625 L.NonNegative && R.NonNegative);
5626 }
5627
John McCall817d4af2010-11-10 23:38:19 +00005628 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00005629 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00005630 return IntRange(std::min(L.Width, R.Width),
5631 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00005632 }
5633};
5634
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005635static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5636 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005637 if (value.isSigned() && value.isNegative())
5638 return IntRange(value.getMinSignedBits(), false);
5639
5640 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005641 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005642
5643 // isNonNegative() just checks the sign bit without considering
5644 // signedness.
5645 return IntRange(value.getActiveBits(), true);
5646}
5647
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005648static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5649 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005650 if (result.isInt())
5651 return GetValueRange(C, result.getInt(), MaxWidth);
5652
5653 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00005654 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5655 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5656 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5657 R = IntRange::join(R, El);
5658 }
John McCall70aa5392010-01-06 05:24:50 +00005659 return R;
5660 }
5661
5662 if (result.isComplexInt()) {
5663 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5664 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5665 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00005666 }
5667
5668 // This can happen with lossless casts to intptr_t of "based" lvalues.
5669 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00005670 // FIXME: The only reason we need to pass the type in here is to get
5671 // the sign right on this one case. It would be nice if APValue
5672 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005673 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00005674 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005675}
John McCall70aa5392010-01-06 05:24:50 +00005676
Eli Friedmane6d33952013-07-08 20:20:06 +00005677static QualType GetExprType(Expr *E) {
5678 QualType Ty = E->getType();
5679 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5680 Ty = AtomicRHS->getValueType();
5681 return Ty;
5682}
5683
John McCall70aa5392010-01-06 05:24:50 +00005684/// Pseudo-evaluate the given integer expression, estimating the
5685/// range of values it might take.
5686///
5687/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005688static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005689 E = E->IgnoreParens();
5690
5691 // Try a full evaluation first.
5692 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005693 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005694 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005695
5696 // I think we only want to look through implicit casts here; if the
5697 // user has an explicit widening cast, we should treat the value as
5698 // being of the new, wider type.
5699 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005700 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005701 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5702
Eli Friedmane6d33952013-07-08 20:20:06 +00005703 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005704
John McCalle3027922010-08-25 11:45:40 +00005705 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005706
John McCall70aa5392010-01-06 05:24:50 +00005707 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005708 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005709 return OutputTypeRange;
5710
5711 IntRange SubRange
5712 = GetExprRange(C, CE->getSubExpr(),
5713 std::min(MaxWidth, OutputTypeRange.Width));
5714
5715 // Bail out if the subexpr's range is as wide as the cast type.
5716 if (SubRange.Width >= OutputTypeRange.Width)
5717 return OutputTypeRange;
5718
5719 // Otherwise, we take the smaller width, and we're non-negative if
5720 // either the output type or the subexpr is.
5721 return IntRange(SubRange.Width,
5722 SubRange.NonNegative || OutputTypeRange.NonNegative);
5723 }
5724
5725 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5726 // If we can fold the condition, just take that operand.
5727 bool CondResult;
5728 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5729 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5730 : CO->getFalseExpr(),
5731 MaxWidth);
5732
5733 // Otherwise, conservatively merge.
5734 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5735 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5736 return IntRange::join(L, R);
5737 }
5738
5739 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5740 switch (BO->getOpcode()) {
5741
5742 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005743 case BO_LAnd:
5744 case BO_LOr:
5745 case BO_LT:
5746 case BO_GT:
5747 case BO_LE:
5748 case BO_GE:
5749 case BO_EQ:
5750 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005751 return IntRange::forBoolType();
5752
John McCallc3688382011-07-13 06:35:24 +00005753 // The type of the assignments is the type of the LHS, so the RHS
5754 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005755 case BO_MulAssign:
5756 case BO_DivAssign:
5757 case BO_RemAssign:
5758 case BO_AddAssign:
5759 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005760 case BO_XorAssign:
5761 case BO_OrAssign:
5762 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005763 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005764
John McCallc3688382011-07-13 06:35:24 +00005765 // Simple assignments just pass through the RHS, which will have
5766 // been coerced to the LHS type.
5767 case BO_Assign:
5768 // TODO: bitfields?
5769 return GetExprRange(C, BO->getRHS(), MaxWidth);
5770
John McCall70aa5392010-01-06 05:24:50 +00005771 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005772 case BO_PtrMemD:
5773 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005774 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005775
John McCall2ce81ad2010-01-06 22:07:33 +00005776 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005777 case BO_And:
5778 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005779 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5780 GetExprRange(C, BO->getRHS(), MaxWidth));
5781
John McCall70aa5392010-01-06 05:24:50 +00005782 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005783 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005784 // ...except that we want to treat '1 << (blah)' as logically
5785 // positive. It's an important idiom.
5786 if (IntegerLiteral *I
5787 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5788 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005789 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005790 return IntRange(R.Width, /*NonNegative*/ true);
5791 }
5792 }
5793 // fallthrough
5794
John McCalle3027922010-08-25 11:45:40 +00005795 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005796 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005797
John McCall2ce81ad2010-01-06 22:07:33 +00005798 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005799 case BO_Shr:
5800 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005801 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5802
5803 // If the shift amount is a positive constant, drop the width by
5804 // that much.
5805 llvm::APSInt shift;
5806 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5807 shift.isNonNegative()) {
5808 unsigned zext = shift.getZExtValue();
5809 if (zext >= L.Width)
5810 L.Width = (L.NonNegative ? 0 : 1);
5811 else
5812 L.Width -= zext;
5813 }
5814
5815 return L;
5816 }
5817
5818 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005819 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005820 return GetExprRange(C, BO->getRHS(), MaxWidth);
5821
John McCall2ce81ad2010-01-06 22:07:33 +00005822 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005823 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005824 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005825 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005826 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005827
John McCall51431812011-07-14 22:39:48 +00005828 // The width of a division result is mostly determined by the size
5829 // of the LHS.
5830 case BO_Div: {
5831 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005832 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005833 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5834
5835 // If the divisor is constant, use that.
5836 llvm::APSInt divisor;
5837 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5838 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5839 if (log2 >= L.Width)
5840 L.Width = (L.NonNegative ? 0 : 1);
5841 else
5842 L.Width = std::min(L.Width - log2, MaxWidth);
5843 return L;
5844 }
5845
5846 // Otherwise, just use the LHS's width.
5847 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5848 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5849 }
5850
5851 // The result of a remainder can't be larger than the result of
5852 // either side.
5853 case BO_Rem: {
5854 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005855 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005856 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5857 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5858
5859 IntRange meet = IntRange::meet(L, R);
5860 meet.Width = std::min(meet.Width, MaxWidth);
5861 return meet;
5862 }
5863
5864 // The default behavior is okay for these.
5865 case BO_Mul:
5866 case BO_Add:
5867 case BO_Xor:
5868 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005869 break;
5870 }
5871
John McCall51431812011-07-14 22:39:48 +00005872 // The default case is to treat the operation as if it were closed
5873 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005874 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5875 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5876 return IntRange::join(L, R);
5877 }
5878
5879 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5880 switch (UO->getOpcode()) {
5881 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005882 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005883 return IntRange::forBoolType();
5884
5885 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005886 case UO_Deref:
5887 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005888 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005889
5890 default:
5891 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5892 }
5893 }
5894
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005895 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5896 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5897
John McCalld25db7e2013-05-06 21:39:12 +00005898 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005899 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005900 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005901
Eli Friedmane6d33952013-07-08 20:20:06 +00005902 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005903}
John McCall263a48b2010-01-04 23:31:57 +00005904
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005905static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005906 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005907}
5908
John McCall263a48b2010-01-04 23:31:57 +00005909/// Checks whether the given value, which currently has the given
5910/// source semantics, has the same value when coerced through the
5911/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005912static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5913 const llvm::fltSemantics &Src,
5914 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005915 llvm::APFloat truncated = value;
5916
5917 bool ignored;
5918 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5919 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5920
5921 return truncated.bitwiseIsEqual(value);
5922}
5923
5924/// Checks whether the given value, which currently has the given
5925/// source semantics, has the same value when coerced through the
5926/// target semantics.
5927///
5928/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005929static bool IsSameFloatAfterCast(const APValue &value,
5930 const llvm::fltSemantics &Src,
5931 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005932 if (value.isFloat())
5933 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5934
5935 if (value.isVector()) {
5936 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5937 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5938 return false;
5939 return true;
5940 }
5941
5942 assert(value.isComplexFloat());
5943 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5944 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5945}
5946
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005947static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005948
Ted Kremenek6274be42010-09-23 21:43:44 +00005949static bool IsZero(Sema &S, Expr *E) {
5950 // Suppress cases where we are comparing against an enum constant.
5951 if (const DeclRefExpr *DR =
5952 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5953 if (isa<EnumConstantDecl>(DR->getDecl()))
5954 return false;
5955
5956 // Suppress cases where the '0' value is expanded from a macro.
5957 if (E->getLocStart().isMacroID())
5958 return false;
5959
John McCallcc7e5bf2010-05-06 08:58:33 +00005960 llvm::APSInt Value;
5961 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5962}
5963
John McCall2551c1b2010-10-06 00:25:24 +00005964static bool HasEnumType(Expr *E) {
5965 // Strip off implicit integral promotions.
5966 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005967 if (ICE->getCastKind() != CK_IntegralCast &&
5968 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005969 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005970 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005971 }
5972
5973 return E->getType()->isEnumeralType();
5974}
5975
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005976static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005977 // Disable warning in template instantiations.
5978 if (!S.ActiveTemplateInstantiations.empty())
5979 return;
5980
John McCalle3027922010-08-25 11:45:40 +00005981 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005982 if (E->isValueDependent())
5983 return;
5984
John McCalle3027922010-08-25 11:45:40 +00005985 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005986 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005987 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005988 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005989 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005990 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005991 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005992 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005993 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005994 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005995 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005996 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005997 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005998 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005999 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006000 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6001 }
6002}
6003
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006004static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006005 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006006 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006007 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00006008 // Disable warning in template instantiations.
6009 if (!S.ActiveTemplateInstantiations.empty())
6010 return;
6011
Richard Trieu0f097742014-04-04 04:13:47 +00006012 // TODO: Investigate using GetExprRange() to get tighter bounds
6013 // on the bit ranges.
6014 QualType OtherT = Other->getType();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006015 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
6016 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00006017 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6018 unsigned OtherWidth = OtherRange.Width;
6019
6020 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6021
Richard Trieu560910c2012-11-14 22:50:24 +00006022 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00006023 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00006024 return;
6025
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006026 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00006027 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006028
Richard Trieu0f097742014-04-04 04:13:47 +00006029 // Used for diagnostic printout.
6030 enum {
6031 LiteralConstant = 0,
6032 CXXBoolLiteralTrue,
6033 CXXBoolLiteralFalse
6034 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006035
Richard Trieu0f097742014-04-04 04:13:47 +00006036 if (!OtherIsBooleanType) {
6037 QualType ConstantT = Constant->getType();
6038 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00006039
Richard Trieu0f097742014-04-04 04:13:47 +00006040 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6041 return;
6042 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6043 "comparison with non-integer type");
6044
6045 bool ConstantSigned = ConstantT->isSignedIntegerType();
6046 bool CommonSigned = CommonT->isSignedIntegerType();
6047
6048 bool EqualityOnly = false;
6049
6050 if (CommonSigned) {
6051 // The common type is signed, therefore no signed to unsigned conversion.
6052 if (!OtherRange.NonNegative) {
6053 // Check that the constant is representable in type OtherT.
6054 if (ConstantSigned) {
6055 if (OtherWidth >= Value.getMinSignedBits())
6056 return;
6057 } else { // !ConstantSigned
6058 if (OtherWidth >= Value.getActiveBits() + 1)
6059 return;
6060 }
6061 } else { // !OtherSigned
6062 // Check that the constant is representable in type OtherT.
6063 // Negative values are out of range.
6064 if (ConstantSigned) {
6065 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6066 return;
6067 } else { // !ConstantSigned
6068 if (OtherWidth >= Value.getActiveBits())
6069 return;
6070 }
Richard Trieu560910c2012-11-14 22:50:24 +00006071 }
Richard Trieu0f097742014-04-04 04:13:47 +00006072 } else { // !CommonSigned
6073 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006074 if (OtherWidth >= Value.getActiveBits())
6075 return;
Craig Toppercf360162014-06-18 05:13:11 +00006076 } else { // OtherSigned
6077 assert(!ConstantSigned &&
6078 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006079 // Check to see if the constant is representable in OtherT.
6080 if (OtherWidth > Value.getActiveBits())
6081 return;
6082 // Check to see if the constant is equivalent to a negative value
6083 // cast to CommonT.
6084 if (S.Context.getIntWidth(ConstantT) ==
6085 S.Context.getIntWidth(CommonT) &&
6086 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6087 return;
6088 // The constant value rests between values that OtherT can represent
6089 // after conversion. Relational comparison still works, but equality
6090 // comparisons will be tautological.
6091 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006092 }
6093 }
Richard Trieu0f097742014-04-04 04:13:47 +00006094
6095 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6096
6097 if (op == BO_EQ || op == BO_NE) {
6098 IsTrue = op == BO_NE;
6099 } else if (EqualityOnly) {
6100 return;
6101 } else if (RhsConstant) {
6102 if (op == BO_GT || op == BO_GE)
6103 IsTrue = !PositiveConstant;
6104 else // op == BO_LT || op == BO_LE
6105 IsTrue = PositiveConstant;
6106 } else {
6107 if (op == BO_LT || op == BO_LE)
6108 IsTrue = !PositiveConstant;
6109 else // op == BO_GT || op == BO_GE
6110 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006111 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006112 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00006113 // Other isKnownToHaveBooleanValue
6114 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6115 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6116 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6117
6118 static const struct LinkedConditions {
6119 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6120 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6121 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6122 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6123 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6124 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6125
6126 } TruthTable = {
6127 // Constant on LHS. | Constant on RHS. |
6128 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6129 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6130 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6131 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6132 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6133 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6134 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6135 };
6136
6137 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6138
6139 enum ConstantValue ConstVal = Zero;
6140 if (Value.isUnsigned() || Value.isNonNegative()) {
6141 if (Value == 0) {
6142 LiteralOrBoolConstant =
6143 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6144 ConstVal = Zero;
6145 } else if (Value == 1) {
6146 LiteralOrBoolConstant =
6147 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6148 ConstVal = One;
6149 } else {
6150 LiteralOrBoolConstant = LiteralConstant;
6151 ConstVal = GT_One;
6152 }
6153 } else {
6154 ConstVal = LT_Zero;
6155 }
6156
6157 CompareBoolWithConstantResult CmpRes;
6158
6159 switch (op) {
6160 case BO_LT:
6161 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6162 break;
6163 case BO_GT:
6164 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6165 break;
6166 case BO_LE:
6167 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6168 break;
6169 case BO_GE:
6170 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6171 break;
6172 case BO_EQ:
6173 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6174 break;
6175 case BO_NE:
6176 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6177 break;
6178 default:
6179 CmpRes = Unkwn;
6180 break;
6181 }
6182
6183 if (CmpRes == AFals) {
6184 IsTrue = false;
6185 } else if (CmpRes == ATrue) {
6186 IsTrue = true;
6187 } else {
6188 return;
6189 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006190 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006191
6192 // If this is a comparison to an enum constant, include that
6193 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006194 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006195 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6196 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6197
6198 SmallString<64> PrettySourceValue;
6199 llvm::raw_svector_ostream OS(PrettySourceValue);
6200 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00006201 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006202 else
6203 OS << Value;
6204
Richard Trieu0f097742014-04-04 04:13:47 +00006205 S.DiagRuntimeBehavior(
6206 E->getOperatorLoc(), E,
6207 S.PDiag(diag::warn_out_of_range_compare)
6208 << OS.str() << LiteralOrBoolConstant
6209 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6210 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006211}
6212
John McCallcc7e5bf2010-05-06 08:58:33 +00006213/// Analyze the operands of the given comparison. Implements the
6214/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006215static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00006216 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6217 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006218}
John McCall263a48b2010-01-04 23:31:57 +00006219
John McCallca01b222010-01-04 23:21:16 +00006220/// \brief Implements -Wsign-compare.
6221///
Richard Trieu82402a02011-09-15 21:56:47 +00006222/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006223static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006224 // The type the comparison is being performed in.
6225 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006226
6227 // Only analyze comparison operators where both sides have been converted to
6228 // the same type.
6229 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6230 return AnalyzeImpConvsInComparison(S, E);
6231
6232 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006233 if (E->isValueDependent())
6234 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006235
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006236 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6237 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006238
6239 bool IsComparisonConstant = false;
6240
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006241 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006242 // of 'true' or 'false'.
6243 if (T->isIntegralType(S.Context)) {
6244 llvm::APSInt RHSValue;
6245 bool IsRHSIntegralLiteral =
6246 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6247 llvm::APSInt LHSValue;
6248 bool IsLHSIntegralLiteral =
6249 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6250 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6251 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6252 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6253 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6254 else
6255 IsComparisonConstant =
6256 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006257 } else if (!T->hasUnsignedIntegerRepresentation())
6258 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006259
John McCallcc7e5bf2010-05-06 08:58:33 +00006260 // We don't do anything special if this isn't an unsigned integral
6261 // comparison: we're only interested in integral comparisons, and
6262 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00006263 //
6264 // We also don't care about value-dependent expressions or expressions
6265 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006266 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00006267 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006268
John McCallcc7e5bf2010-05-06 08:58:33 +00006269 // Check to see if one of the (unmodified) operands is of different
6270 // signedness.
6271 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00006272 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6273 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00006274 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00006275 signedOperand = LHS;
6276 unsignedOperand = RHS;
6277 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6278 signedOperand = RHS;
6279 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00006280 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00006281 CheckTrivialUnsignedComparison(S, E);
6282 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006283 }
6284
John McCallcc7e5bf2010-05-06 08:58:33 +00006285 // Otherwise, calculate the effective range of the signed operand.
6286 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00006287
John McCallcc7e5bf2010-05-06 08:58:33 +00006288 // Go ahead and analyze implicit conversions in the operands. Note
6289 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00006290 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6291 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00006292
John McCallcc7e5bf2010-05-06 08:58:33 +00006293 // If the signed range is non-negative, -Wsign-compare won't fire,
6294 // but we should still check for comparisons which are always true
6295 // or false.
6296 if (signedRange.NonNegative)
6297 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006298
6299 // For (in)equality comparisons, if the unsigned operand is a
6300 // constant which cannot collide with a overflowed signed operand,
6301 // then reinterpreting the signed operand as unsigned will not
6302 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00006303 if (E->isEqualityOp()) {
6304 unsigned comparisonWidth = S.Context.getIntWidth(T);
6305 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00006306
John McCallcc7e5bf2010-05-06 08:58:33 +00006307 // We should never be unable to prove that the unsigned operand is
6308 // non-negative.
6309 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6310
6311 if (unsignedRange.Width < comparisonWidth)
6312 return;
6313 }
6314
Douglas Gregorbfb4a212012-05-01 01:53:49 +00006315 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6316 S.PDiag(diag::warn_mixed_sign_comparison)
6317 << LHS->getType() << RHS->getType()
6318 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00006319}
6320
John McCall1f425642010-11-11 03:21:53 +00006321/// Analyzes an attempt to assign the given value to a bitfield.
6322///
6323/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006324static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6325 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00006326 assert(Bitfield->isBitField());
6327 if (Bitfield->isInvalidDecl())
6328 return false;
6329
John McCalldeebbcf2010-11-11 05:33:51 +00006330 // White-list bool bitfields.
6331 if (Bitfield->getType()->isBooleanType())
6332 return false;
6333
Douglas Gregor789adec2011-02-04 13:09:01 +00006334 // Ignore value- or type-dependent expressions.
6335 if (Bitfield->getBitWidth()->isValueDependent() ||
6336 Bitfield->getBitWidth()->isTypeDependent() ||
6337 Init->isValueDependent() ||
6338 Init->isTypeDependent())
6339 return false;
6340
John McCall1f425642010-11-11 03:21:53 +00006341 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6342
Richard Smith5fab0c92011-12-28 19:48:30 +00006343 llvm::APSInt Value;
6344 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00006345 return false;
6346
John McCall1f425642010-11-11 03:21:53 +00006347 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00006348 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00006349
6350 if (OriginalWidth <= FieldWidth)
6351 return false;
6352
Eli Friedmanc267a322012-01-26 23:11:39 +00006353 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006354 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00006355 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00006356
Eli Friedmanc267a322012-01-26 23:11:39 +00006357 // Check whether the stored value is equal to the original value.
6358 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00006359 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00006360 return false;
6361
Eli Friedmanc267a322012-01-26 23:11:39 +00006362 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00006363 // therefore don't strictly fit into a signed bitfield of width 1.
6364 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00006365 return false;
6366
John McCall1f425642010-11-11 03:21:53 +00006367 std::string PrettyValue = Value.toString(10);
6368 std::string PrettyTrunc = TruncatedValue.toString(10);
6369
6370 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6371 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6372 << Init->getSourceRange();
6373
6374 return true;
6375}
6376
John McCalld2a53122010-11-09 23:24:47 +00006377/// Analyze the given simple or compound assignment for warning-worthy
6378/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006379static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006380 // Just recurse on the LHS.
6381 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6382
6383 // We want to recurse on the RHS as normal unless we're assigning to
6384 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006385 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006386 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006387 E->getOperatorLoc())) {
6388 // Recurse, ignoring any implicit conversions on the RHS.
6389 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6390 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006391 }
6392 }
6393
6394 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6395}
6396
John McCall263a48b2010-01-04 23:31:57 +00006397/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006398static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006399 SourceLocation CContext, unsigned diag,
6400 bool pruneControlFlow = false) {
6401 if (pruneControlFlow) {
6402 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6403 S.PDiag(diag)
6404 << SourceType << T << E->getSourceRange()
6405 << SourceRange(CContext));
6406 return;
6407 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006408 S.Diag(E->getExprLoc(), diag)
6409 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6410}
6411
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006412/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006413static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006414 SourceLocation CContext, unsigned diag,
6415 bool pruneControlFlow = false) {
6416 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006417}
6418
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006419/// Diagnose an implicit cast from a literal expression. Does not warn when the
6420/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006421void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6422 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006423 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006424 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006425 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006426 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6427 T->hasUnsignedIntegerRepresentation());
6428 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006429 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006430 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006431 return;
6432
Eli Friedman07185912013-08-29 23:44:43 +00006433 // FIXME: Force the precision of the source value down so we don't print
6434 // digits which are usually useless (we don't really care here if we
6435 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6436 // would automatically print the shortest representation, but it's a bit
6437 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006438 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006439 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6440 precision = (precision * 59 + 195) / 196;
6441 Value.toString(PrettySourceValue, precision);
6442
David Blaikie9b88cc02012-05-15 17:18:27 +00006443 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006444 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6445 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6446 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006447 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006448
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006449 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006450 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6451 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006452}
6453
John McCall18a2c2c2010-11-09 22:22:12 +00006454std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6455 if (!Range.Width) return "0";
6456
6457 llvm::APSInt ValueInRange = Value;
6458 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006459 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006460 return ValueInRange.toString(10);
6461}
6462
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006463static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6464 if (!isa<ImplicitCastExpr>(Ex))
6465 return false;
6466
6467 Expr *InnerE = Ex->IgnoreParenImpCasts();
6468 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6469 const Type *Source =
6470 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6471 if (Target->isDependentType())
6472 return false;
6473
6474 const BuiltinType *FloatCandidateBT =
6475 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6476 const Type *BoolCandidateType = ToBool ? Target : Source;
6477
6478 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6479 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6480}
6481
6482void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6483 SourceLocation CC) {
6484 unsigned NumArgs = TheCall->getNumArgs();
6485 for (unsigned i = 0; i < NumArgs; ++i) {
6486 Expr *CurrA = TheCall->getArg(i);
6487 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6488 continue;
6489
6490 bool IsSwapped = ((i > 0) &&
6491 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6492 IsSwapped |= ((i < (NumArgs - 1)) &&
6493 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6494 if (IsSwapped) {
6495 // Warn on this floating-point to bool conversion.
6496 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6497 CurrA->getType(), CC,
6498 diag::warn_impcast_floating_point_to_bool);
6499 }
6500 }
6501}
6502
Richard Trieu5b993502014-10-15 03:42:06 +00006503static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6504 SourceLocation CC) {
6505 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6506 E->getExprLoc()))
6507 return;
6508
6509 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6510 const Expr::NullPointerConstantKind NullKind =
6511 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6512 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6513 return;
6514
6515 // Return if target type is a safe conversion.
6516 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6517 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6518 return;
6519
6520 SourceLocation Loc = E->getSourceRange().getBegin();
6521
6522 // __null is usually wrapped in a macro. Go up a macro if that is the case.
6523 if (NullKind == Expr::NPCK_GNUNull) {
6524 if (Loc.isMacroID())
6525 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6526 }
6527
6528 // Only warn if the null and context location are in the same macro expansion.
6529 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6530 return;
6531
6532 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6533 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6534 << FixItHint::CreateReplacement(Loc,
6535 S.getFixItZeroLiteralForType(T, Loc));
6536}
6537
John McCallcc7e5bf2010-05-06 08:58:33 +00006538void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00006539 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006540 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00006541
John McCallcc7e5bf2010-05-06 08:58:33 +00006542 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6543 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6544 if (Source == Target) return;
6545 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00006546
Chandler Carruthc22845a2011-07-26 05:40:03 +00006547 // If the conversion context location is invalid don't complain. We also
6548 // don't want to emit a warning if the issue occurs from the expansion of
6549 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6550 // delay this check as long as possible. Once we detect we are in that
6551 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006552 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00006553 return;
6554
Richard Trieu021baa32011-09-23 20:10:00 +00006555 // Diagnose implicit casts to bool.
6556 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6557 if (isa<StringLiteral>(E))
6558 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00006559 // and expressions, for instance, assert(0 && "error here"), are
6560 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00006561 return DiagnoseImpCast(S, E, T, CC,
6562 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00006563 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6564 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6565 // This covers the literal expressions that evaluate to Objective-C
6566 // objects.
6567 return DiagnoseImpCast(S, E, T, CC,
6568 diag::warn_impcast_objective_c_literal_to_bool);
6569 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006570 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6571 // Warn on pointer to bool conversion that is always true.
6572 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6573 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00006574 }
Richard Trieu021baa32011-09-23 20:10:00 +00006575 }
John McCall263a48b2010-01-04 23:31:57 +00006576
6577 // Strip vector types.
6578 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006579 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006580 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006581 return;
John McCallacf0ee52010-10-08 02:01:28 +00006582 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006583 }
Chris Lattneree7286f2011-06-14 04:51:15 +00006584
6585 // If the vector cast is cast between two vectors of the same size, it is
6586 // a bitcast, not a conversion.
6587 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6588 return;
John McCall263a48b2010-01-04 23:31:57 +00006589
6590 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6591 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6592 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00006593 if (auto VecTy = dyn_cast<VectorType>(Target))
6594 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00006595
6596 // Strip complex types.
6597 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006598 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006599 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006600 return;
6601
John McCallacf0ee52010-10-08 02:01:28 +00006602 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006603 }
John McCall263a48b2010-01-04 23:31:57 +00006604
6605 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6606 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6607 }
6608
6609 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6610 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6611
6612 // If the source is floating point...
6613 if (SourceBT && SourceBT->isFloatingPoint()) {
6614 // ...and the target is floating point...
6615 if (TargetBT && TargetBT->isFloatingPoint()) {
6616 // ...then warn if we're dropping FP rank.
6617
6618 // Builtin FP kinds are ordered by increasing FP rank.
6619 if (SourceBT->getKind() > TargetBT->getKind()) {
6620 // Don't warn about float constants that are precisely
6621 // representable in the target type.
6622 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006623 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00006624 // Value might be a float, a float vector, or a float complex.
6625 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00006626 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6627 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00006628 return;
6629 }
6630
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006631 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006632 return;
6633
John McCallacf0ee52010-10-08 02:01:28 +00006634 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00006635 }
6636 return;
6637 }
6638
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006639 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00006640 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006641 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006642 return;
6643
Chandler Carruth22c7a792011-02-17 11:05:49 +00006644 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00006645 // We also want to warn on, e.g., "int i = -1.234"
6646 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6647 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6648 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6649
Chandler Carruth016ef402011-04-10 08:36:24 +00006650 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6651 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00006652 } else {
6653 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6654 }
6655 }
John McCall263a48b2010-01-04 23:31:57 +00006656
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006657 // If the target is bool, warn if expr is a function or method call.
6658 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6659 isa<CallExpr>(E)) {
6660 // Check last argument of function call to see if it is an
6661 // implicit cast from a type matching the type the result
6662 // is being cast to.
6663 CallExpr *CEx = cast<CallExpr>(E);
6664 unsigned NumArgs = CEx->getNumArgs();
6665 if (NumArgs > 0) {
6666 Expr *LastA = CEx->getArg(NumArgs - 1);
6667 Expr *InnerE = LastA->IgnoreParenImpCasts();
6668 const Type *InnerType =
6669 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6670 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6671 // Warn on this floating-point to bool conversion
6672 DiagnoseImpCast(S, E, T, CC,
6673 diag::warn_impcast_floating_point_to_bool);
6674 }
6675 }
6676 }
John McCall263a48b2010-01-04 23:31:57 +00006677 return;
6678 }
6679
Richard Trieu5b993502014-10-15 03:42:06 +00006680 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00006681
David Blaikie9366d2b2012-06-19 21:19:06 +00006682 if (!Source->isIntegerType() || !Target->isIntegerType())
6683 return;
6684
David Blaikie7555b6a2012-05-15 16:56:36 +00006685 // TODO: remove this early return once the false positives for constant->bool
6686 // in templates, macros, etc, are reduced or removed.
6687 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6688 return;
6689
John McCallcc7e5bf2010-05-06 08:58:33 +00006690 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00006691 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00006692
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006693 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00006694 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006695 // TODO: this should happen for bitfield stores, too.
6696 llvm::APSInt Value(32);
6697 if (E->isIntegerConstantExpr(Value, S.Context)) {
6698 if (S.SourceMgr.isInSystemMacro(CC))
6699 return;
6700
John McCall18a2c2c2010-11-09 22:22:12 +00006701 std::string PrettySourceValue = Value.toString(10);
6702 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006703
Ted Kremenek33ba9952011-10-22 02:37:33 +00006704 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6705 S.PDiag(diag::warn_impcast_integer_precision_constant)
6706 << PrettySourceValue << PrettyTargetValue
6707 << E->getType() << T << E->getSourceRange()
6708 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006709 return;
6710 }
6711
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006712 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6713 if (S.SourceMgr.isInSystemMacro(CC))
6714 return;
6715
David Blaikie9455da02012-04-12 22:40:54 +00006716 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006717 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6718 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006719 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006720 }
6721
6722 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6723 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6724 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006725
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006726 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006727 return;
6728
John McCallcc7e5bf2010-05-06 08:58:33 +00006729 unsigned DiagID = diag::warn_impcast_integer_sign;
6730
6731 // Traditionally, gcc has warned about this under -Wsign-compare.
6732 // We also want to warn about it in -Wconversion.
6733 // So if -Wconversion is off, use a completely identical diagnostic
6734 // in the sign-compare group.
6735 // The conditional-checking code will
6736 if (ICContext) {
6737 DiagID = diag::warn_impcast_integer_sign_conditional;
6738 *ICContext = true;
6739 }
6740
John McCallacf0ee52010-10-08 02:01:28 +00006741 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006742 }
6743
Douglas Gregora78f1932011-02-22 02:45:07 +00006744 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006745 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6746 // type, to give us better diagnostics.
6747 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006748 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006749 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6750 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6751 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6752 SourceType = S.Context.getTypeDeclType(Enum);
6753 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6754 }
6755 }
6756
Douglas Gregora78f1932011-02-22 02:45:07 +00006757 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6758 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006759 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6760 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006761 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006762 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006763 return;
6764
Douglas Gregor364f7db2011-03-12 00:14:31 +00006765 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006766 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006767 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006768
John McCall263a48b2010-01-04 23:31:57 +00006769 return;
6770}
6771
David Blaikie18e9ac72012-05-15 21:57:38 +00006772void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6773 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006774
6775void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006776 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006777 E = E->IgnoreParenImpCasts();
6778
6779 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006780 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006781
John McCallacf0ee52010-10-08 02:01:28 +00006782 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006783 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006784 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006785 return;
6786}
6787
David Blaikie18e9ac72012-05-15 21:57:38 +00006788void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6789 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00006790 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006791
6792 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006793 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6794 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006795
6796 // If -Wconversion would have warned about either of the candidates
6797 // for a signedness conversion to the context type...
6798 if (!Suspicious) return;
6799
6800 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006801 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006802 return;
6803
John McCallcc7e5bf2010-05-06 08:58:33 +00006804 // ...then check whether it would have warned about either of the
6805 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006806 if (E->getType() == T) return;
6807
6808 Suspicious = false;
6809 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6810 E->getType(), CC, &Suspicious);
6811 if (!Suspicious)
6812 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006813 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006814}
6815
Richard Trieu65724892014-11-15 06:37:39 +00006816/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6817/// Input argument E is a logical expression.
6818static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
6819 if (S.getLangOpts().Bool)
6820 return;
6821 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
6822}
6823
John McCallcc7e5bf2010-05-06 08:58:33 +00006824/// AnalyzeImplicitConversions - Find and report any interesting
6825/// implicit conversions in the given expression. There are a couple
6826/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006827void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006828 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006829 Expr *E = OrigE->IgnoreParenImpCasts();
6830
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006831 if (E->isTypeDependent() || E->isValueDependent())
6832 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006833
John McCallcc7e5bf2010-05-06 08:58:33 +00006834 // For conditional operators, we analyze the arguments as if they
6835 // were being fed directly into the output.
6836 if (isa<ConditionalOperator>(E)) {
6837 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006838 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006839 return;
6840 }
6841
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006842 // Check implicit argument conversions for function calls.
6843 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6844 CheckImplicitArgumentConversions(S, Call, CC);
6845
John McCallcc7e5bf2010-05-06 08:58:33 +00006846 // Go ahead and check any implicit conversions we might have skipped.
6847 // The non-canonical typecheck is just an optimization;
6848 // CheckImplicitConversion will filter out dead implicit conversions.
6849 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006850 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006851
6852 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006853
6854 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006855 if (POE->getResultExpr())
6856 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006857 }
6858
Fariborz Jahanian947efbc2015-02-26 17:59:54 +00006859 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
6860 if (OVE->getSourceExpr())
6861 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6862 return;
6863 }
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006864
John McCallcc7e5bf2010-05-06 08:58:33 +00006865 // Skip past explicit casts.
6866 if (isa<ExplicitCastExpr>(E)) {
6867 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006868 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006869 }
6870
John McCalld2a53122010-11-09 23:24:47 +00006871 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6872 // Do a somewhat different check with comparison operators.
6873 if (BO->isComparisonOp())
6874 return AnalyzeComparison(S, BO);
6875
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006876 // And with simple assignments.
6877 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006878 return AnalyzeAssignment(S, BO);
6879 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006880
6881 // These break the otherwise-useful invariant below. Fortunately,
6882 // we don't really need to recurse into them, because any internal
6883 // expressions should have been analyzed already when they were
6884 // built into statements.
6885 if (isa<StmtExpr>(E)) return;
6886
6887 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006888 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006889
6890 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006891 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006892 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006893 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006894 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006895 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006896 if (!ChildExpr)
6897 continue;
6898
Richard Trieu955231d2014-01-25 01:10:35 +00006899 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006900 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006901 // Ignore checking string literals that are in logical and operators.
6902 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006903 continue;
6904 AnalyzeImplicitConversions(S, ChildExpr, CC);
6905 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006906
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006907 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00006908 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
6909 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006910 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00006911
6912 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
6913 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006914 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006915 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006916
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006917 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
6918 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00006919 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006920}
6921
6922} // end anonymous namespace
6923
Richard Trieu3bb8b562014-02-26 02:36:06 +00006924enum {
6925 AddressOf,
6926 FunctionPointer,
6927 ArrayPointer
6928};
6929
Richard Trieuc1888e02014-06-28 23:25:37 +00006930// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6931// Returns true when emitting a warning about taking the address of a reference.
6932static bool CheckForReference(Sema &SemaRef, const Expr *E,
6933 PartialDiagnostic PD) {
6934 E = E->IgnoreParenImpCasts();
6935
6936 const FunctionDecl *FD = nullptr;
6937
6938 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6939 if (!DRE->getDecl()->getType()->isReferenceType())
6940 return false;
6941 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6942 if (!M->getMemberDecl()->getType()->isReferenceType())
6943 return false;
6944 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00006945 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00006946 return false;
6947 FD = Call->getDirectCallee();
6948 } else {
6949 return false;
6950 }
6951
6952 SemaRef.Diag(E->getExprLoc(), PD);
6953
6954 // If possible, point to location of function.
6955 if (FD) {
6956 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6957 }
6958
6959 return true;
6960}
6961
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006962// Returns true if the SourceLocation is expanded from any macro body.
6963// Returns false if the SourceLocation is invalid, is from not in a macro
6964// expansion, or is from expanded from a top-level macro argument.
6965static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
6966 if (Loc.isInvalid())
6967 return false;
6968
6969 while (Loc.isMacroID()) {
6970 if (SM.isMacroBodyExpansion(Loc))
6971 return true;
6972 Loc = SM.getImmediateMacroCallerLoc(Loc);
6973 }
6974
6975 return false;
6976}
6977
Richard Trieu3bb8b562014-02-26 02:36:06 +00006978/// \brief Diagnose pointers that are always non-null.
6979/// \param E the expression containing the pointer
6980/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6981/// compared to a null pointer
6982/// \param IsEqual True when the comparison is equal to a null pointer
6983/// \param Range Extra SourceRange to highlight in the diagnostic
6984void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6985 Expr::NullPointerConstantKind NullKind,
6986 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00006987 if (!E)
6988 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006989
6990 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006991 if (E->getExprLoc().isMacroID()) {
6992 const SourceManager &SM = getSourceManager();
6993 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
6994 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00006995 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006996 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006997 E = E->IgnoreImpCasts();
6998
6999 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
7000
Richard Trieuf7432752014-06-06 21:39:26 +00007001 if (isa<CXXThisExpr>(E)) {
7002 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
7003 : diag::warn_this_bool_conversion;
7004 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
7005 return;
7006 }
7007
Richard Trieu3bb8b562014-02-26 02:36:06 +00007008 bool IsAddressOf = false;
7009
7010 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7011 if (UO->getOpcode() != UO_AddrOf)
7012 return;
7013 IsAddressOf = true;
7014 E = UO->getSubExpr();
7015 }
7016
Richard Trieuc1888e02014-06-28 23:25:37 +00007017 if (IsAddressOf) {
7018 unsigned DiagID = IsCompare
7019 ? diag::warn_address_of_reference_null_compare
7020 : diag::warn_address_of_reference_bool_conversion;
7021 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
7022 << IsEqual;
7023 if (CheckForReference(*this, E, PD)) {
7024 return;
7025 }
7026 }
7027
Richard Trieu3bb8b562014-02-26 02:36:06 +00007028 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00007029 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007030 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
7031 D = R->getDecl();
7032 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7033 D = M->getMemberDecl();
7034 }
7035
7036 // Weak Decls can be null.
7037 if (!D || D->isWeak())
7038 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007039
7040 // Check for parameter decl with nonnull attribute
7041 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
7042 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
7043 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
7044 unsigned NumArgs = FD->getNumParams();
7045 llvm::SmallBitVector AttrNonNull(NumArgs);
7046 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
7047 if (!NonNull->args_size()) {
7048 AttrNonNull.set(0, NumArgs);
7049 break;
7050 }
7051 for (unsigned Val : NonNull->args()) {
7052 if (Val >= NumArgs)
7053 continue;
7054 AttrNonNull.set(Val);
7055 }
7056 }
7057 if (!AttrNonNull.empty())
7058 for (unsigned i = 0; i < NumArgs; ++i)
Aaron Ballman2521f362014-12-11 19:35:42 +00007059 if (FD->getParamDecl(i) == PV &&
7060 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007061 std::string Str;
7062 llvm::raw_string_ostream S(Str);
7063 E->printPretty(S, nullptr, getPrintingPolicy());
7064 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
7065 : diag::warn_cast_nonnull_to_bool;
7066 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
7067 << Range << IsEqual;
7068 return;
7069 }
7070 }
7071 }
7072
Richard Trieu3bb8b562014-02-26 02:36:06 +00007073 QualType T = D->getType();
7074 const bool IsArray = T->isArrayType();
7075 const bool IsFunction = T->isFunctionType();
7076
Richard Trieuc1888e02014-06-28 23:25:37 +00007077 // Address of function is used to silence the function warning.
7078 if (IsAddressOf && IsFunction) {
7079 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007080 }
7081
7082 // Found nothing.
7083 if (!IsAddressOf && !IsFunction && !IsArray)
7084 return;
7085
7086 // Pretty print the expression for the diagnostic.
7087 std::string Str;
7088 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00007089 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00007090
7091 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7092 : diag::warn_impcast_pointer_to_bool;
7093 unsigned DiagType;
7094 if (IsAddressOf)
7095 DiagType = AddressOf;
7096 else if (IsFunction)
7097 DiagType = FunctionPointer;
7098 else if (IsArray)
7099 DiagType = ArrayPointer;
7100 else
7101 llvm_unreachable("Could not determine diagnostic.");
7102 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7103 << Range << IsEqual;
7104
7105 if (!IsFunction)
7106 return;
7107
7108 // Suggest '&' to silence the function warning.
7109 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7110 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7111
7112 // Check to see if '()' fixit should be emitted.
7113 QualType ReturnType;
7114 UnresolvedSet<4> NonTemplateOverloads;
7115 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7116 if (ReturnType.isNull())
7117 return;
7118
7119 if (IsCompare) {
7120 // There are two cases here. If there is null constant, the only suggest
7121 // for a pointer return type. If the null is 0, then suggest if the return
7122 // type is a pointer or an integer type.
7123 if (!ReturnType->isPointerType()) {
7124 if (NullKind == Expr::NPCK_ZeroExpression ||
7125 NullKind == Expr::NPCK_ZeroLiteral) {
7126 if (!ReturnType->isIntegerType())
7127 return;
7128 } else {
7129 return;
7130 }
7131 }
7132 } else { // !IsCompare
7133 // For function to bool, only suggest if the function pointer has bool
7134 // return type.
7135 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7136 return;
7137 }
7138 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007139 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00007140}
7141
7142
John McCallcc7e5bf2010-05-06 08:58:33 +00007143/// Diagnoses "dangerous" implicit conversions within the given
7144/// expression (which is a full expression). Implements -Wconversion
7145/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007146///
7147/// \param CC the "context" location of the implicit conversion, i.e.
7148/// the most location of the syntactic entity requiring the implicit
7149/// conversion
7150void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007151 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00007152 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00007153 return;
7154
7155 // Don't diagnose for value- or type-dependent expressions.
7156 if (E->isTypeDependent() || E->isValueDependent())
7157 return;
7158
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007159 // Check for array bounds violations in cases where the check isn't triggered
7160 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7161 // ArraySubscriptExpr is on the RHS of a variable initialization.
7162 CheckArrayAccess(E);
7163
John McCallacf0ee52010-10-08 02:01:28 +00007164 // This is not the right CC for (e.g.) a variable initialization.
7165 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007166}
7167
Richard Trieu65724892014-11-15 06:37:39 +00007168/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7169/// Input argument E is a logical expression.
7170void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7171 ::CheckBoolLikeConversion(*this, E, CC);
7172}
7173
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007174/// Diagnose when expression is an integer constant expression and its evaluation
7175/// results in integer overflow
7176void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00007177 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7178 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007179}
7180
Richard Smithc406cb72013-01-17 01:17:56 +00007181namespace {
7182/// \brief Visitor for expressions which looks for unsequenced operations on the
7183/// same object.
7184class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007185 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7186
Richard Smithc406cb72013-01-17 01:17:56 +00007187 /// \brief A tree of sequenced regions within an expression. Two regions are
7188 /// unsequenced if one is an ancestor or a descendent of the other. When we
7189 /// finish processing an expression with sequencing, such as a comma
7190 /// expression, we fold its tree nodes into its parent, since they are
7191 /// unsequenced with respect to nodes we will visit later.
7192 class SequenceTree {
7193 struct Value {
7194 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7195 unsigned Parent : 31;
7196 bool Merged : 1;
7197 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007198 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00007199
7200 public:
7201 /// \brief A region within an expression which may be sequenced with respect
7202 /// to some other region.
7203 class Seq {
7204 explicit Seq(unsigned N) : Index(N) {}
7205 unsigned Index;
7206 friend class SequenceTree;
7207 public:
7208 Seq() : Index(0) {}
7209 };
7210
7211 SequenceTree() { Values.push_back(Value(0)); }
7212 Seq root() const { return Seq(0); }
7213
7214 /// \brief Create a new sequence of operations, which is an unsequenced
7215 /// subset of \p Parent. This sequence of operations is sequenced with
7216 /// respect to other children of \p Parent.
7217 Seq allocate(Seq Parent) {
7218 Values.push_back(Value(Parent.Index));
7219 return Seq(Values.size() - 1);
7220 }
7221
7222 /// \brief Merge a sequence of operations into its parent.
7223 void merge(Seq S) {
7224 Values[S.Index].Merged = true;
7225 }
7226
7227 /// \brief Determine whether two operations are unsequenced. This operation
7228 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7229 /// should have been merged into its parent as appropriate.
7230 bool isUnsequenced(Seq Cur, Seq Old) {
7231 unsigned C = representative(Cur.Index);
7232 unsigned Target = representative(Old.Index);
7233 while (C >= Target) {
7234 if (C == Target)
7235 return true;
7236 C = Values[C].Parent;
7237 }
7238 return false;
7239 }
7240
7241 private:
7242 /// \brief Pick a representative for a sequence.
7243 unsigned representative(unsigned K) {
7244 if (Values[K].Merged)
7245 // Perform path compression as we go.
7246 return Values[K].Parent = representative(Values[K].Parent);
7247 return K;
7248 }
7249 };
7250
7251 /// An object for which we can track unsequenced uses.
7252 typedef NamedDecl *Object;
7253
7254 /// Different flavors of object usage which we track. We only track the
7255 /// least-sequenced usage of each kind.
7256 enum UsageKind {
7257 /// A read of an object. Multiple unsequenced reads are OK.
7258 UK_Use,
7259 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00007260 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00007261 UK_ModAsValue,
7262 /// A modification of an object which is not sequenced before the value
7263 /// computation of the expression, such as n++.
7264 UK_ModAsSideEffect,
7265
7266 UK_Count = UK_ModAsSideEffect + 1
7267 };
7268
7269 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00007270 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00007271 Expr *Use;
7272 SequenceTree::Seq Seq;
7273 };
7274
7275 struct UsageInfo {
7276 UsageInfo() : Diagnosed(false) {}
7277 Usage Uses[UK_Count];
7278 /// Have we issued a diagnostic for this variable already?
7279 bool Diagnosed;
7280 };
7281 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7282
7283 Sema &SemaRef;
7284 /// Sequenced regions within the expression.
7285 SequenceTree Tree;
7286 /// Declaration modifications and references which we have seen.
7287 UsageInfoMap UsageMap;
7288 /// The region we are currently within.
7289 SequenceTree::Seq Region;
7290 /// Filled in with declarations which were modified as a side-effect
7291 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007292 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00007293 /// Expressions to check later. We defer checking these to reduce
7294 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007295 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00007296
7297 /// RAII object wrapping the visitation of a sequenced subexpression of an
7298 /// expression. At the end of this process, the side-effects of the evaluation
7299 /// become sequenced with respect to the value computation of the result, so
7300 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7301 /// UK_ModAsValue.
7302 struct SequencedSubexpression {
7303 SequencedSubexpression(SequenceChecker &Self)
7304 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7305 Self.ModAsSideEffect = &ModAsSideEffect;
7306 }
7307 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00007308 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7309 MI != ME; ++MI) {
7310 UsageInfo &U = Self.UsageMap[MI->first];
7311 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7312 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7313 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00007314 }
7315 Self.ModAsSideEffect = OldModAsSideEffect;
7316 }
7317
7318 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007319 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7320 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00007321 };
7322
Richard Smith40238f02013-06-20 22:21:56 +00007323 /// RAII object wrapping the visitation of a subexpression which we might
7324 /// choose to evaluate as a constant. If any subexpression is evaluated and
7325 /// found to be non-constant, this allows us to suppress the evaluation of
7326 /// the outer expression.
7327 class EvaluationTracker {
7328 public:
7329 EvaluationTracker(SequenceChecker &Self)
7330 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7331 Self.EvalTracker = this;
7332 }
7333 ~EvaluationTracker() {
7334 Self.EvalTracker = Prev;
7335 if (Prev)
7336 Prev->EvalOK &= EvalOK;
7337 }
7338
7339 bool evaluate(const Expr *E, bool &Result) {
7340 if (!EvalOK || E->isValueDependent())
7341 return false;
7342 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7343 return EvalOK;
7344 }
7345
7346 private:
7347 SequenceChecker &Self;
7348 EvaluationTracker *Prev;
7349 bool EvalOK;
7350 } *EvalTracker;
7351
Richard Smithc406cb72013-01-17 01:17:56 +00007352 /// \brief Find the object which is produced by the specified expression,
7353 /// if any.
7354 Object getObject(Expr *E, bool Mod) const {
7355 E = E->IgnoreParenCasts();
7356 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7357 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7358 return getObject(UO->getSubExpr(), Mod);
7359 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7360 if (BO->getOpcode() == BO_Comma)
7361 return getObject(BO->getRHS(), Mod);
7362 if (Mod && BO->isAssignmentOp())
7363 return getObject(BO->getLHS(), Mod);
7364 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7365 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7366 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7367 return ME->getMemberDecl();
7368 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7369 // FIXME: If this is a reference, map through to its value.
7370 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00007371 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00007372 }
7373
7374 /// \brief Note that an object was modified or used by an expression.
7375 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7376 Usage &U = UI.Uses[UK];
7377 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7378 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7379 ModAsSideEffect->push_back(std::make_pair(O, U));
7380 U.Use = Ref;
7381 U.Seq = Region;
7382 }
7383 }
7384 /// \brief Check whether a modification or use conflicts with a prior usage.
7385 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7386 bool IsModMod) {
7387 if (UI.Diagnosed)
7388 return;
7389
7390 const Usage &U = UI.Uses[OtherKind];
7391 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7392 return;
7393
7394 Expr *Mod = U.Use;
7395 Expr *ModOrUse = Ref;
7396 if (OtherKind == UK_Use)
7397 std::swap(Mod, ModOrUse);
7398
7399 SemaRef.Diag(Mod->getExprLoc(),
7400 IsModMod ? diag::warn_unsequenced_mod_mod
7401 : diag::warn_unsequenced_mod_use)
7402 << O << SourceRange(ModOrUse->getExprLoc());
7403 UI.Diagnosed = true;
7404 }
7405
7406 void notePreUse(Object O, Expr *Use) {
7407 UsageInfo &U = UsageMap[O];
7408 // Uses conflict with other modifications.
7409 checkUsage(O, U, Use, UK_ModAsValue, false);
7410 }
7411 void notePostUse(Object O, Expr *Use) {
7412 UsageInfo &U = UsageMap[O];
7413 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7414 addUsage(U, O, Use, UK_Use);
7415 }
7416
7417 void notePreMod(Object O, Expr *Mod) {
7418 UsageInfo &U = UsageMap[O];
7419 // Modifications conflict with other modifications and with uses.
7420 checkUsage(O, U, Mod, UK_ModAsValue, true);
7421 checkUsage(O, U, Mod, UK_Use, false);
7422 }
7423 void notePostMod(Object O, Expr *Use, UsageKind UK) {
7424 UsageInfo &U = UsageMap[O];
7425 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7426 addUsage(U, O, Use, UK);
7427 }
7428
7429public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007430 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00007431 : Base(S.Context), SemaRef(S), Region(Tree.root()),
7432 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007433 Visit(E);
7434 }
7435
7436 void VisitStmt(Stmt *S) {
7437 // Skip all statements which aren't expressions for now.
7438 }
7439
7440 void VisitExpr(Expr *E) {
7441 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00007442 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007443 }
7444
7445 void VisitCastExpr(CastExpr *E) {
7446 Object O = Object();
7447 if (E->getCastKind() == CK_LValueToRValue)
7448 O = getObject(E->getSubExpr(), false);
7449
7450 if (O)
7451 notePreUse(O, E);
7452 VisitExpr(E);
7453 if (O)
7454 notePostUse(O, E);
7455 }
7456
7457 void VisitBinComma(BinaryOperator *BO) {
7458 // C++11 [expr.comma]p1:
7459 // Every value computation and side effect associated with the left
7460 // expression is sequenced before every value computation and side
7461 // effect associated with the right expression.
7462 SequenceTree::Seq LHS = Tree.allocate(Region);
7463 SequenceTree::Seq RHS = Tree.allocate(Region);
7464 SequenceTree::Seq OldRegion = Region;
7465
7466 {
7467 SequencedSubexpression SeqLHS(*this);
7468 Region = LHS;
7469 Visit(BO->getLHS());
7470 }
7471
7472 Region = RHS;
7473 Visit(BO->getRHS());
7474
7475 Region = OldRegion;
7476
7477 // Forget that LHS and RHS are sequenced. They are both unsequenced
7478 // with respect to other stuff.
7479 Tree.merge(LHS);
7480 Tree.merge(RHS);
7481 }
7482
7483 void VisitBinAssign(BinaryOperator *BO) {
7484 // The modification is sequenced after the value computation of the LHS
7485 // and RHS, so check it before inspecting the operands and update the
7486 // map afterwards.
7487 Object O = getObject(BO->getLHS(), true);
7488 if (!O)
7489 return VisitExpr(BO);
7490
7491 notePreMod(O, BO);
7492
7493 // C++11 [expr.ass]p7:
7494 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7495 // only once.
7496 //
7497 // Therefore, for a compound assignment operator, O is considered used
7498 // everywhere except within the evaluation of E1 itself.
7499 if (isa<CompoundAssignOperator>(BO))
7500 notePreUse(O, BO);
7501
7502 Visit(BO->getLHS());
7503
7504 if (isa<CompoundAssignOperator>(BO))
7505 notePostUse(O, BO);
7506
7507 Visit(BO->getRHS());
7508
Richard Smith83e37bee2013-06-26 23:16:51 +00007509 // C++11 [expr.ass]p1:
7510 // the assignment is sequenced [...] before the value computation of the
7511 // assignment expression.
7512 // C11 6.5.16/3 has no such rule.
7513 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7514 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007515 }
7516 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7517 VisitBinAssign(CAO);
7518 }
7519
7520 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7521 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7522 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7523 Object O = getObject(UO->getSubExpr(), true);
7524 if (!O)
7525 return VisitExpr(UO);
7526
7527 notePreMod(O, UO);
7528 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00007529 // C++11 [expr.pre.incr]p1:
7530 // the expression ++x is equivalent to x+=1
7531 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7532 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007533 }
7534
7535 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7536 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7537 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7538 Object O = getObject(UO->getSubExpr(), true);
7539 if (!O)
7540 return VisitExpr(UO);
7541
7542 notePreMod(O, UO);
7543 Visit(UO->getSubExpr());
7544 notePostMod(O, UO, UK_ModAsSideEffect);
7545 }
7546
7547 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7548 void VisitBinLOr(BinaryOperator *BO) {
7549 // The side-effects of the LHS of an '&&' are sequenced before the
7550 // value computation of the RHS, and hence before the value computation
7551 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7552 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00007553 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007554 {
7555 SequencedSubexpression Sequenced(*this);
7556 Visit(BO->getLHS());
7557 }
7558
7559 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007560 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007561 if (!Result)
7562 Visit(BO->getRHS());
7563 } else {
7564 // Check for unsequenced operations in the RHS, treating it as an
7565 // entirely separate evaluation.
7566 //
7567 // FIXME: If there are operations in the RHS which are unsequenced
7568 // with respect to operations outside the RHS, and those operations
7569 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00007570 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007571 }
Richard Smithc406cb72013-01-17 01:17:56 +00007572 }
7573 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00007574 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007575 {
7576 SequencedSubexpression Sequenced(*this);
7577 Visit(BO->getLHS());
7578 }
7579
7580 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007581 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007582 if (Result)
7583 Visit(BO->getRHS());
7584 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00007585 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007586 }
Richard Smithc406cb72013-01-17 01:17:56 +00007587 }
7588
7589 // Only visit the condition, unless we can be sure which subexpression will
7590 // be chosen.
7591 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00007592 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00007593 {
7594 SequencedSubexpression Sequenced(*this);
7595 Visit(CO->getCond());
7596 }
Richard Smithc406cb72013-01-17 01:17:56 +00007597
7598 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007599 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00007600 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007601 else {
Richard Smithd33f5202013-01-17 23:18:09 +00007602 WorkList.push_back(CO->getTrueExpr());
7603 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007604 }
Richard Smithc406cb72013-01-17 01:17:56 +00007605 }
7606
Richard Smithe3dbfe02013-06-30 10:40:20 +00007607 void VisitCallExpr(CallExpr *CE) {
7608 // C++11 [intro.execution]p15:
7609 // When calling a function [...], every value computation and side effect
7610 // associated with any argument expression, or with the postfix expression
7611 // designating the called function, is sequenced before execution of every
7612 // expression or statement in the body of the function [and thus before
7613 // the value computation of its result].
7614 SequencedSubexpression Sequenced(*this);
7615 Base::VisitCallExpr(CE);
7616
7617 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7618 }
7619
Richard Smithc406cb72013-01-17 01:17:56 +00007620 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007621 // This is a call, so all subexpressions are sequenced before the result.
7622 SequencedSubexpression Sequenced(*this);
7623
Richard Smithc406cb72013-01-17 01:17:56 +00007624 if (!CCE->isListInitialization())
7625 return VisitExpr(CCE);
7626
7627 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007628 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007629 SequenceTree::Seq Parent = Region;
7630 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7631 E = CCE->arg_end();
7632 I != E; ++I) {
7633 Region = Tree.allocate(Parent);
7634 Elts.push_back(Region);
7635 Visit(*I);
7636 }
7637
7638 // Forget that the initializers are sequenced.
7639 Region = Parent;
7640 for (unsigned I = 0; I < Elts.size(); ++I)
7641 Tree.merge(Elts[I]);
7642 }
7643
7644 void VisitInitListExpr(InitListExpr *ILE) {
7645 if (!SemaRef.getLangOpts().CPlusPlus11)
7646 return VisitExpr(ILE);
7647
7648 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007649 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007650 SequenceTree::Seq Parent = Region;
7651 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7652 Expr *E = ILE->getInit(I);
7653 if (!E) continue;
7654 Region = Tree.allocate(Parent);
7655 Elts.push_back(Region);
7656 Visit(E);
7657 }
7658
7659 // Forget that the initializers are sequenced.
7660 Region = Parent;
7661 for (unsigned I = 0; I < Elts.size(); ++I)
7662 Tree.merge(Elts[I]);
7663 }
7664};
7665}
7666
7667void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007668 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00007669 WorkList.push_back(E);
7670 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00007671 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00007672 SequenceChecker(*this, Item, WorkList);
7673 }
Richard Smithc406cb72013-01-17 01:17:56 +00007674}
7675
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007676void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7677 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007678 CheckImplicitConversions(E, CheckLoc);
7679 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007680 if (!IsConstexpr && !E->isValueDependent())
7681 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007682}
7683
John McCall1f425642010-11-11 03:21:53 +00007684void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7685 FieldDecl *BitField,
7686 Expr *Init) {
7687 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7688}
7689
Mike Stump0c2ec772010-01-21 03:59:47 +00007690/// CheckParmsForFunctionDef - Check that the parameters of the given
7691/// function are appropriate for the definition of a function. This
7692/// takes care of any checks that cannot be performed on the
7693/// declaration itself, e.g., that the types of each of the function
7694/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00007695bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7696 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00007697 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007698 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00007699 for (; P != PEnd; ++P) {
7700 ParmVarDecl *Param = *P;
7701
Mike Stump0c2ec772010-01-21 03:59:47 +00007702 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7703 // function declarator that is part of a function definition of
7704 // that function shall not have incomplete type.
7705 //
7706 // This is also C++ [dcl.fct]p6.
7707 if (!Param->isInvalidDecl() &&
7708 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007709 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007710 Param->setInvalidDecl();
7711 HasInvalidParm = true;
7712 }
7713
7714 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7715 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00007716 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00007717 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00007718 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007719 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00007720 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00007721
7722 // C99 6.7.5.3p12:
7723 // If the function declarator is not part of a definition of that
7724 // function, parameters may have incomplete type and may use the [*]
7725 // notation in their sequences of declarator specifiers to specify
7726 // variable length array types.
7727 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007728 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00007729 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00007730 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00007731 // information is added for it.
7732 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007733 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00007734 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007735 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00007736 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007737
7738 // MSVC destroys objects passed by value in the callee. Therefore a
7739 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007740 // object's destructor. However, we don't perform any direct access check
7741 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00007742 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7743 .getCXXABI()
7744 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00007745 if (!Param->isInvalidDecl()) {
7746 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7747 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7748 if (!ClassDecl->isInvalidDecl() &&
7749 !ClassDecl->hasIrrelevantDestructor() &&
7750 !ClassDecl->isDependentContext()) {
7751 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7752 MarkFunctionReferenced(Param->getLocation(), Destructor);
7753 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7754 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007755 }
7756 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007757 }
Mike Stump0c2ec772010-01-21 03:59:47 +00007758 }
7759
7760 return HasInvalidParm;
7761}
John McCall2b5c1b22010-08-12 21:44:57 +00007762
7763/// CheckCastAlign - Implements -Wcast-align, which warns when a
7764/// pointer cast increases the alignment requirements.
7765void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7766 // This is actually a lot of work to potentially be doing on every
7767 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007768 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00007769 return;
7770
7771 // Ignore dependent types.
7772 if (T->isDependentType() || Op->getType()->isDependentType())
7773 return;
7774
7775 // Require that the destination be a pointer type.
7776 const PointerType *DestPtr = T->getAs<PointerType>();
7777 if (!DestPtr) return;
7778
7779 // If the destination has alignment 1, we're done.
7780 QualType DestPointee = DestPtr->getPointeeType();
7781 if (DestPointee->isIncompleteType()) return;
7782 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7783 if (DestAlign.isOne()) return;
7784
7785 // Require that the source be a pointer type.
7786 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7787 if (!SrcPtr) return;
7788 QualType SrcPointee = SrcPtr->getPointeeType();
7789
7790 // Whitelist casts from cv void*. We already implicitly
7791 // whitelisted casts to cv void*, since they have alignment 1.
7792 // Also whitelist casts involving incomplete types, which implicitly
7793 // includes 'void'.
7794 if (SrcPointee->isIncompleteType()) return;
7795
7796 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7797 if (SrcAlign >= DestAlign) return;
7798
7799 Diag(TRange.getBegin(), diag::warn_cast_align)
7800 << Op->getType() << T
7801 << static_cast<unsigned>(SrcAlign.getQuantity())
7802 << static_cast<unsigned>(DestAlign.getQuantity())
7803 << TRange << Op->getSourceRange();
7804}
7805
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007806static const Type* getElementType(const Expr *BaseExpr) {
7807 const Type* EltType = BaseExpr->getType().getTypePtr();
7808 if (EltType->isAnyPointerType())
7809 return EltType->getPointeeType().getTypePtr();
7810 else if (EltType->isArrayType())
7811 return EltType->getBaseElementTypeUnsafe();
7812 return EltType;
7813}
7814
Chandler Carruth28389f02011-08-05 09:10:50 +00007815/// \brief Check whether this array fits the idiom of a size-one tail padded
7816/// array member of a struct.
7817///
7818/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7819/// commonly used to emulate flexible arrays in C89 code.
7820static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7821 const NamedDecl *ND) {
7822 if (Size != 1 || !ND) return false;
7823
7824 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7825 if (!FD) return false;
7826
7827 // Don't consider sizes resulting from macro expansions or template argument
7828 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00007829
7830 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007831 while (TInfo) {
7832 TypeLoc TL = TInfo->getTypeLoc();
7833 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007834 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7835 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007836 TInfo = TDL->getTypeSourceInfo();
7837 continue;
7838 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007839 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7840 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007841 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7842 return false;
7843 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007844 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007845 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007846
7847 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007848 if (!RD) return false;
7849 if (RD->isUnion()) return false;
7850 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7851 if (!CRD->isStandardLayout()) return false;
7852 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007853
Benjamin Kramer8c543672011-08-06 03:04:42 +00007854 // See if this is the last field decl in the record.
7855 const Decl *D = FD;
7856 while ((D = D->getNextDeclInContext()))
7857 if (isa<FieldDecl>(D))
7858 return false;
7859 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007860}
7861
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007862void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007863 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007864 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007865 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007866 if (IndexExpr->isValueDependent())
7867 return;
7868
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007869 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007870 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007871 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007872 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007873 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007874 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007875
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007876 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007877 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007878 return;
Richard Smith13f67182011-12-16 19:31:14 +00007879 if (IndexNegated)
7880 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007881
Craig Topperc3ec1492014-05-26 06:22:03 +00007882 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007883 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7884 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007885 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007886 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007887
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007888 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007889 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007890 if (!size.isStrictlyPositive())
7891 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007892
7893 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007894 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007895 // Make sure we're comparing apples to apples when comparing index to size
7896 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7897 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007898 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007899 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007900 if (ptrarith_typesize != array_typesize) {
7901 // There's a cast to a different size type involved
7902 uint64_t ratio = array_typesize / ptrarith_typesize;
7903 // TODO: Be smarter about handling cases where array_typesize is not a
7904 // multiple of ptrarith_typesize
7905 if (ptrarith_typesize * ratio == array_typesize)
7906 size *= llvm::APInt(size.getBitWidth(), ratio);
7907 }
7908 }
7909
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007910 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007911 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007912 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007913 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007914
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007915 // For array subscripting the index must be less than size, but for pointer
7916 // arithmetic also allow the index (offset) to be equal to size since
7917 // computing the next address after the end of the array is legal and
7918 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007919 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007920 return;
7921
7922 // Also don't warn for arrays of size 1 which are members of some
7923 // structure. These are often used to approximate flexible arrays in C89
7924 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007925 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007926 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007927
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007928 // Suppress the warning if the subscript expression (as identified by the
7929 // ']' location) and the index expression are both from macro expansions
7930 // within a system header.
7931 if (ASE) {
7932 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7933 ASE->getRBracketLoc());
7934 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7935 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7936 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007937 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007938 return;
7939 }
7940 }
7941
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007942 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007943 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007944 DiagID = diag::warn_array_index_exceeds_bounds;
7945
7946 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7947 PDiag(DiagID) << index.toString(10, true)
7948 << size.toString(10, true)
7949 << (unsigned)size.getLimitedValue(~0U)
7950 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007951 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007952 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007953 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007954 DiagID = diag::warn_ptr_arith_precedes_bounds;
7955 if (index.isNegative()) index = -index;
7956 }
7957
7958 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7959 PDiag(DiagID) << index.toString(10, true)
7960 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007961 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007962
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007963 if (!ND) {
7964 // Try harder to find a NamedDecl to point at in the note.
7965 while (const ArraySubscriptExpr *ASE =
7966 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7967 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7968 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7969 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7970 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7971 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7972 }
7973
Chandler Carruth1af88f12011-02-17 21:10:52 +00007974 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007975 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7976 PDiag(diag::note_array_index_out_of_bounds)
7977 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007978}
7979
Ted Kremenekdf26df72011-03-01 18:41:00 +00007980void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007981 int AllowOnePastEnd = 0;
7982 while (expr) {
7983 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007984 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007985 case Stmt::ArraySubscriptExprClass: {
7986 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007987 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007988 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007989 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007990 }
7991 case Stmt::UnaryOperatorClass: {
7992 // Only unwrap the * and & unary operators
7993 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7994 expr = UO->getSubExpr();
7995 switch (UO->getOpcode()) {
7996 case UO_AddrOf:
7997 AllowOnePastEnd++;
7998 break;
7999 case UO_Deref:
8000 AllowOnePastEnd--;
8001 break;
8002 default:
8003 return;
8004 }
8005 break;
8006 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008007 case Stmt::ConditionalOperatorClass: {
8008 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
8009 if (const Expr *lhs = cond->getLHS())
8010 CheckArrayAccess(lhs);
8011 if (const Expr *rhs = cond->getRHS())
8012 CheckArrayAccess(rhs);
8013 return;
8014 }
8015 default:
8016 return;
8017 }
Peter Collingbourne91147592011-04-15 00:35:48 +00008018 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008019}
John McCall31168b02011-06-15 23:02:42 +00008020
8021//===--- CHECK: Objective-C retain cycles ----------------------------------//
8022
8023namespace {
8024 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00008025 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00008026 VarDecl *Variable;
8027 SourceRange Range;
8028 SourceLocation Loc;
8029 bool Indirect;
8030
8031 void setLocsFrom(Expr *e) {
8032 Loc = e->getExprLoc();
8033 Range = e->getSourceRange();
8034 }
8035 };
8036}
8037
8038/// Consider whether capturing the given variable can possibly lead to
8039/// a retain cycle.
8040static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00008041 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00008042 // lifetime. In MRR, it's captured strongly if the variable is
8043 // __block and has an appropriate type.
8044 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8045 return false;
8046
8047 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008048 if (ref)
8049 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00008050 return true;
8051}
8052
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008053static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00008054 while (true) {
8055 e = e->IgnoreParens();
8056 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
8057 switch (cast->getCastKind()) {
8058 case CK_BitCast:
8059 case CK_LValueBitCast:
8060 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00008061 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00008062 e = cast->getSubExpr();
8063 continue;
8064
John McCall31168b02011-06-15 23:02:42 +00008065 default:
8066 return false;
8067 }
8068 }
8069
8070 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
8071 ObjCIvarDecl *ivar = ref->getDecl();
8072 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8073 return false;
8074
8075 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008076 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00008077 return false;
8078
8079 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8080 owner.Indirect = true;
8081 return true;
8082 }
8083
8084 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8085 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8086 if (!var) return false;
8087 return considerVariable(var, ref, owner);
8088 }
8089
John McCall31168b02011-06-15 23:02:42 +00008090 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8091 if (member->isArrow()) return false;
8092
8093 // Don't count this as an indirect ownership.
8094 e = member->getBase();
8095 continue;
8096 }
8097
John McCallfe96e0b2011-11-06 09:01:30 +00008098 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8099 // Only pay attention to pseudo-objects on property references.
8100 ObjCPropertyRefExpr *pre
8101 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8102 ->IgnoreParens());
8103 if (!pre) return false;
8104 if (pre->isImplicitProperty()) return false;
8105 ObjCPropertyDecl *property = pre->getExplicitProperty();
8106 if (!property->isRetaining() &&
8107 !(property->getPropertyIvarDecl() &&
8108 property->getPropertyIvarDecl()->getType()
8109 .getObjCLifetime() == Qualifiers::OCL_Strong))
8110 return false;
8111
8112 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008113 if (pre->isSuperReceiver()) {
8114 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8115 if (!owner.Variable)
8116 return false;
8117 owner.Loc = pre->getLocation();
8118 owner.Range = pre->getSourceRange();
8119 return true;
8120 }
John McCallfe96e0b2011-11-06 09:01:30 +00008121 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8122 ->getSourceExpr());
8123 continue;
8124 }
8125
John McCall31168b02011-06-15 23:02:42 +00008126 // Array ivars?
8127
8128 return false;
8129 }
8130}
8131
8132namespace {
8133 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8134 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8135 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008136 Context(Context), Variable(variable), Capturer(nullptr),
8137 VarWillBeReased(false) {}
8138 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00008139 VarDecl *Variable;
8140 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008141 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00008142
8143 void VisitDeclRefExpr(DeclRefExpr *ref) {
8144 if (ref->getDecl() == Variable && !Capturer)
8145 Capturer = ref;
8146 }
8147
John McCall31168b02011-06-15 23:02:42 +00008148 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8149 if (Capturer) return;
8150 Visit(ref->getBase());
8151 if (Capturer && ref->isFreeIvar())
8152 Capturer = ref;
8153 }
8154
8155 void VisitBlockExpr(BlockExpr *block) {
8156 // Look inside nested blocks
8157 if (block->getBlockDecl()->capturesVariable(Variable))
8158 Visit(block->getBlockDecl()->getBody());
8159 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00008160
8161 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8162 if (Capturer) return;
8163 if (OVE->getSourceExpr())
8164 Visit(OVE->getSourceExpr());
8165 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008166 void VisitBinaryOperator(BinaryOperator *BinOp) {
8167 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8168 return;
8169 Expr *LHS = BinOp->getLHS();
8170 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8171 if (DRE->getDecl() != Variable)
8172 return;
8173 if (Expr *RHS = BinOp->getRHS()) {
8174 RHS = RHS->IgnoreParenCasts();
8175 llvm::APSInt Value;
8176 VarWillBeReased =
8177 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8178 }
8179 }
8180 }
John McCall31168b02011-06-15 23:02:42 +00008181 };
8182}
8183
8184/// Check whether the given argument is a block which captures a
8185/// variable.
8186static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8187 assert(owner.Variable && owner.Loc.isValid());
8188
8189 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00008190
8191 // Look through [^{...} copy] and Block_copy(^{...}).
8192 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8193 Selector Cmd = ME->getSelector();
8194 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8195 e = ME->getInstanceReceiver();
8196 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00008197 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00008198 e = e->IgnoreParenCasts();
8199 }
8200 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8201 if (CE->getNumArgs() == 1) {
8202 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00008203 if (Fn) {
8204 const IdentifierInfo *FnI = Fn->getIdentifier();
8205 if (FnI && FnI->isStr("_Block_copy")) {
8206 e = CE->getArg(0)->IgnoreParenCasts();
8207 }
8208 }
Jordan Rose67e887c2012-09-17 17:54:30 +00008209 }
8210 }
8211
John McCall31168b02011-06-15 23:02:42 +00008212 BlockExpr *block = dyn_cast<BlockExpr>(e);
8213 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00008214 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00008215
8216 FindCaptureVisitor visitor(S.Context, owner.Variable);
8217 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008218 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00008219}
8220
8221static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8222 RetainCycleOwner &owner) {
8223 assert(capturer);
8224 assert(owner.Variable && owner.Loc.isValid());
8225
8226 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8227 << owner.Variable << capturer->getSourceRange();
8228 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8229 << owner.Indirect << owner.Range;
8230}
8231
8232/// Check for a keyword selector that starts with the word 'add' or
8233/// 'set'.
8234static bool isSetterLikeSelector(Selector sel) {
8235 if (sel.isUnarySelector()) return false;
8236
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008237 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00008238 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008239 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00008240 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008241 else if (str.startswith("add")) {
8242 // Specially whitelist 'addOperationWithBlock:'.
8243 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8244 return false;
8245 str = str.substr(3);
8246 }
John McCall31168b02011-06-15 23:02:42 +00008247 else
8248 return false;
8249
8250 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00008251 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00008252}
8253
Benjamin Kramer3a743452015-03-09 15:03:32 +00008254static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
8255 ObjCMessageExpr *Message) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008256 if (S.NSMutableArrayPointer.isNull()) {
8257 IdentifierInfo *NSMutableArrayId =
8258 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableArray);
8259 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableArrayId,
8260 Message->getLocStart(),
8261 Sema::LookupOrdinaryName);
8262 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8263 if (!InterfaceDecl) {
8264 return None;
8265 }
8266 QualType NSMutableArrayObject =
8267 S.Context.getObjCInterfaceType(InterfaceDecl);
8268 S.NSMutableArrayPointer =
8269 S.Context.getObjCObjectPointerType(NSMutableArrayObject);
8270 }
8271
8272 if (S.NSMutableArrayPointer != Message->getReceiverType()) {
8273 return None;
8274 }
8275
8276 Selector Sel = Message->getSelector();
8277
8278 Optional<NSAPI::NSArrayMethodKind> MKOpt =
8279 S.NSAPIObj->getNSArrayMethodKind(Sel);
8280 if (!MKOpt) {
8281 return None;
8282 }
8283
8284 NSAPI::NSArrayMethodKind MK = *MKOpt;
8285
8286 switch (MK) {
8287 case NSAPI::NSMutableArr_addObject:
8288 case NSAPI::NSMutableArr_insertObjectAtIndex:
8289 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
8290 return 0;
8291 case NSAPI::NSMutableArr_replaceObjectAtIndex:
8292 return 1;
8293
8294 default:
8295 return None;
8296 }
8297
8298 return None;
8299}
8300
8301static
8302Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
8303 ObjCMessageExpr *Message) {
8304
8305 if (S.NSMutableDictionaryPointer.isNull()) {
8306 IdentifierInfo *NSMutableDictionaryId =
8307 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableDictionary);
8308 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableDictionaryId,
8309 Message->getLocStart(),
8310 Sema::LookupOrdinaryName);
8311 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8312 if (!InterfaceDecl) {
8313 return None;
8314 }
8315 QualType NSMutableDictionaryObject =
8316 S.Context.getObjCInterfaceType(InterfaceDecl);
8317 S.NSMutableDictionaryPointer =
8318 S.Context.getObjCObjectPointerType(NSMutableDictionaryObject);
8319 }
8320
8321 if (S.NSMutableDictionaryPointer != Message->getReceiverType()) {
8322 return None;
8323 }
8324
8325 Selector Sel = Message->getSelector();
8326
8327 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
8328 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
8329 if (!MKOpt) {
8330 return None;
8331 }
8332
8333 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
8334
8335 switch (MK) {
8336 case NSAPI::NSMutableDict_setObjectForKey:
8337 case NSAPI::NSMutableDict_setValueForKey:
8338 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
8339 return 0;
8340
8341 default:
8342 return None;
8343 }
8344
8345 return None;
8346}
8347
8348static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
8349
8350 ObjCInterfaceDecl *InterfaceDecl;
8351 if (S.NSMutableSetPointer.isNull()) {
8352 IdentifierInfo *NSMutableSetId =
8353 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableSet);
8354 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableSetId,
8355 Message->getLocStart(),
8356 Sema::LookupOrdinaryName);
8357 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8358 if (InterfaceDecl) {
8359 QualType NSMutableSetObject =
8360 S.Context.getObjCInterfaceType(InterfaceDecl);
8361 S.NSMutableSetPointer =
8362 S.Context.getObjCObjectPointerType(NSMutableSetObject);
8363 }
8364 }
8365
8366 if (S.NSCountedSetPointer.isNull()) {
8367 IdentifierInfo *NSCountedSetId =
8368 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSCountedSet);
8369 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSCountedSetId,
8370 Message->getLocStart(),
8371 Sema::LookupOrdinaryName);
8372 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8373 if (InterfaceDecl) {
8374 QualType NSCountedSetObject =
8375 S.Context.getObjCInterfaceType(InterfaceDecl);
8376 S.NSCountedSetPointer =
8377 S.Context.getObjCObjectPointerType(NSCountedSetObject);
8378 }
8379 }
8380
8381 if (S.NSMutableOrderedSetPointer.isNull()) {
8382 IdentifierInfo *NSOrderedSetId =
8383 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableOrderedSet);
8384 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSOrderedSetId,
8385 Message->getLocStart(),
8386 Sema::LookupOrdinaryName);
8387 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8388 if (InterfaceDecl) {
8389 QualType NSOrderedSetObject =
8390 S.Context.getObjCInterfaceType(InterfaceDecl);
8391 S.NSMutableOrderedSetPointer =
8392 S.Context.getObjCObjectPointerType(NSOrderedSetObject);
8393 }
8394 }
8395
8396 QualType ReceiverType = Message->getReceiverType();
8397
8398 bool IsMutableSet = !S.NSMutableSetPointer.isNull() &&
8399 ReceiverType == S.NSMutableSetPointer;
8400 bool IsMutableOrderedSet = !S.NSMutableOrderedSetPointer.isNull() &&
8401 ReceiverType == S.NSMutableOrderedSetPointer;
8402 bool IsCountedSet = !S.NSCountedSetPointer.isNull() &&
8403 ReceiverType == S.NSCountedSetPointer;
8404
8405 if (!IsMutableSet && !IsMutableOrderedSet && !IsCountedSet) {
8406 return None;
8407 }
8408
8409 Selector Sel = Message->getSelector();
8410
8411 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
8412 if (!MKOpt) {
8413 return None;
8414 }
8415
8416 NSAPI::NSSetMethodKind MK = *MKOpt;
8417
8418 switch (MK) {
8419 case NSAPI::NSMutableSet_addObject:
8420 case NSAPI::NSOrderedSet_setObjectAtIndex:
8421 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
8422 case NSAPI::NSOrderedSet_insertObjectAtIndex:
8423 return 0;
8424 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
8425 return 1;
8426 }
8427
8428 return None;
8429}
8430
8431void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
8432 if (!Message->isInstanceMessage()) {
8433 return;
8434 }
8435
8436 Optional<int> ArgOpt;
8437
8438 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
8439 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
8440 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
8441 return;
8442 }
8443
8444 int ArgIndex = *ArgOpt;
8445
8446 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
8447 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
8448 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
8449 }
8450
8451 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
8452 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
8453 Arg = OE->getSourceExpr()->IgnoreImpCasts();
8454 }
8455
8456 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
8457 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
8458 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
8459 ValueDecl *Decl = ReceiverRE->getDecl();
8460 Diag(Message->getSourceRange().getBegin(),
8461 diag::warn_objc_circular_container)
8462 << Decl->getName();
8463 Diag(Decl->getLocation(),
8464 diag::note_objc_circular_container_declared_here)
8465 << Decl->getName();
8466 }
8467 }
8468 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
8469 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
8470 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
8471 ObjCIvarDecl *Decl = IvarRE->getDecl();
8472 Diag(Message->getSourceRange().getBegin(),
8473 diag::warn_objc_circular_container)
8474 << Decl->getName();
8475 Diag(Decl->getLocation(),
8476 diag::note_objc_circular_container_declared_here)
8477 << Decl->getName();
8478 }
8479 }
8480 }
8481
8482}
8483
John McCall31168b02011-06-15 23:02:42 +00008484/// Check a message send to see if it's likely to cause a retain cycle.
8485void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8486 // Only check instance methods whose selector looks like a setter.
8487 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8488 return;
8489
8490 // Try to find a variable that the receiver is strongly owned by.
8491 RetainCycleOwner owner;
8492 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008493 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00008494 return;
8495 } else {
8496 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8497 owner.Variable = getCurMethodDecl()->getSelfDecl();
8498 owner.Loc = msg->getSuperLoc();
8499 owner.Range = msg->getSuperLoc();
8500 }
8501
8502 // Check whether the receiver is captured by any of the arguments.
8503 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
8504 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
8505 return diagnoseRetainCycle(*this, capturer, owner);
8506}
8507
8508/// Check a property assign to see if it's likely to cause a retain cycle.
8509void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
8510 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008511 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00008512 return;
8513
8514 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
8515 diagnoseRetainCycle(*this, capturer, owner);
8516}
8517
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008518void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
8519 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00008520 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008521 return;
8522
8523 // Because we don't have an expression for the variable, we have to set the
8524 // location explicitly here.
8525 Owner.Loc = Var->getLocation();
8526 Owner.Range = Var->getSourceRange();
8527
8528 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8529 diagnoseRetainCycle(*this, Capturer, Owner);
8530}
8531
Ted Kremenek9304da92012-12-21 08:04:28 +00008532static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8533 Expr *RHS, bool isProperty) {
8534 // Check if RHS is an Objective-C object literal, which also can get
8535 // immediately zapped in a weak reference. Note that we explicitly
8536 // allow ObjCStringLiterals, since those are designed to never really die.
8537 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008538
Ted Kremenek64873352012-12-21 22:46:35 +00008539 // This enum needs to match with the 'select' in
8540 // warn_objc_arc_literal_assign (off-by-1).
8541 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8542 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8543 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008544
8545 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00008546 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00008547 << (isProperty ? 0 : 1)
8548 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008549
8550 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00008551}
8552
Ted Kremenekc1f014a2012-12-21 19:45:30 +00008553static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8554 Qualifiers::ObjCLifetime LT,
8555 Expr *RHS, bool isProperty) {
8556 // Strip off any implicit cast added to get to the one ARC-specific.
8557 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8558 if (cast->getCastKind() == CK_ARCConsumeObject) {
8559 S.Diag(Loc, diag::warn_arc_retained_assign)
8560 << (LT == Qualifiers::OCL_ExplicitNone)
8561 << (isProperty ? 0 : 1)
8562 << RHS->getSourceRange();
8563 return true;
8564 }
8565 RHS = cast->getSubExpr();
8566 }
8567
8568 if (LT == Qualifiers::OCL_Weak &&
8569 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8570 return true;
8571
8572 return false;
8573}
8574
Ted Kremenekb36234d2012-12-21 08:04:20 +00008575bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8576 QualType LHS, Expr *RHS) {
8577 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8578
8579 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8580 return false;
8581
8582 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8583 return true;
8584
8585 return false;
8586}
8587
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008588void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8589 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008590 QualType LHSType;
8591 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00008592 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008593 ObjCPropertyRefExpr *PRE
8594 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8595 if (PRE && !PRE->isImplicitProperty()) {
8596 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8597 if (PD)
8598 LHSType = PD->getType();
8599 }
8600
8601 if (LHSType.isNull())
8602 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00008603
8604 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8605
8606 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008607 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00008608 getCurFunction()->markSafeWeakUse(LHS);
8609 }
8610
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008611 if (checkUnsafeAssigns(Loc, LHSType, RHS))
8612 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00008613
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008614 // FIXME. Check for other life times.
8615 if (LT != Qualifiers::OCL_None)
8616 return;
8617
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008618 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008619 if (PRE->isImplicitProperty())
8620 return;
8621 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8622 if (!PD)
8623 return;
8624
Bill Wendling44426052012-12-20 19:22:21 +00008625 unsigned Attributes = PD->getPropertyAttributes();
8626 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008627 // when 'assign' attribute was not explicitly specified
8628 // by user, ignore it and rely on property type itself
8629 // for lifetime info.
8630 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
8631 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
8632 LHSType->isObjCRetainableType())
8633 return;
8634
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008635 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00008636 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008637 Diag(Loc, diag::warn_arc_retained_property_assign)
8638 << RHS->getSourceRange();
8639 return;
8640 }
8641 RHS = cast->getSubExpr();
8642 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008643 }
Bill Wendling44426052012-12-20 19:22:21 +00008644 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00008645 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
8646 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00008647 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008648 }
8649}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008650
8651//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8652
8653namespace {
8654bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8655 SourceLocation StmtLoc,
8656 const NullStmt *Body) {
8657 // Do not warn if the body is a macro that expands to nothing, e.g:
8658 //
8659 // #define CALL(x)
8660 // if (condition)
8661 // CALL(0);
8662 //
8663 if (Body->hasLeadingEmptyMacro())
8664 return false;
8665
8666 // Get line numbers of statement and body.
8667 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +00008668 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008669 &StmtLineInvalid);
8670 if (StmtLineInvalid)
8671 return false;
8672
8673 bool BodyLineInvalid;
8674 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8675 &BodyLineInvalid);
8676 if (BodyLineInvalid)
8677 return false;
8678
8679 // Warn if null statement and body are on the same line.
8680 if (StmtLine != BodyLine)
8681 return false;
8682
8683 return true;
8684}
8685} // Unnamed namespace
8686
8687void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8688 const Stmt *Body,
8689 unsigned DiagID) {
8690 // Since this is a syntactic check, don't emit diagnostic for template
8691 // instantiations, this just adds noise.
8692 if (CurrentInstantiationScope)
8693 return;
8694
8695 // The body should be a null statement.
8696 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8697 if (!NBody)
8698 return;
8699
8700 // Do the usual checks.
8701 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8702 return;
8703
8704 Diag(NBody->getSemiLoc(), DiagID);
8705 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8706}
8707
8708void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8709 const Stmt *PossibleBody) {
8710 assert(!CurrentInstantiationScope); // Ensured by caller
8711
8712 SourceLocation StmtLoc;
8713 const Stmt *Body;
8714 unsigned DiagID;
8715 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8716 StmtLoc = FS->getRParenLoc();
8717 Body = FS->getBody();
8718 DiagID = diag::warn_empty_for_body;
8719 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8720 StmtLoc = WS->getCond()->getSourceRange().getEnd();
8721 Body = WS->getBody();
8722 DiagID = diag::warn_empty_while_body;
8723 } else
8724 return; // Neither `for' nor `while'.
8725
8726 // The body should be a null statement.
8727 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8728 if (!NBody)
8729 return;
8730
8731 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008732 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008733 return;
8734
8735 // Do the usual checks.
8736 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8737 return;
8738
8739 // `for(...);' and `while(...);' are popular idioms, so in order to keep
8740 // noise level low, emit diagnostics only if for/while is followed by a
8741 // CompoundStmt, e.g.:
8742 // for (int i = 0; i < n; i++);
8743 // {
8744 // a(i);
8745 // }
8746 // or if for/while is followed by a statement with more indentation
8747 // than for/while itself:
8748 // for (int i = 0; i < n; i++);
8749 // a(i);
8750 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8751 if (!ProbableTypo) {
8752 bool BodyColInvalid;
8753 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8754 PossibleBody->getLocStart(),
8755 &BodyColInvalid);
8756 if (BodyColInvalid)
8757 return;
8758
8759 bool StmtColInvalid;
8760 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8761 S->getLocStart(),
8762 &StmtColInvalid);
8763 if (StmtColInvalid)
8764 return;
8765
8766 if (BodyCol > StmtCol)
8767 ProbableTypo = true;
8768 }
8769
8770 if (ProbableTypo) {
8771 Diag(NBody->getSemiLoc(), DiagID);
8772 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8773 }
8774}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008775
Richard Trieu36d0b2b2015-01-13 02:32:02 +00008776//===--- CHECK: Warn on self move with std::move. -------------------------===//
8777
8778/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
8779void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
8780 SourceLocation OpLoc) {
8781
8782 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
8783 return;
8784
8785 if (!ActiveTemplateInstantiations.empty())
8786 return;
8787
8788 // Strip parens and casts away.
8789 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8790 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8791
8792 // Check for a call expression
8793 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
8794 if (!CE || CE->getNumArgs() != 1)
8795 return;
8796
8797 // Check for a call to std::move
8798 const FunctionDecl *FD = CE->getDirectCallee();
8799 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
8800 !FD->getIdentifier()->isStr("move"))
8801 return;
8802
8803 // Get argument from std::move
8804 RHSExpr = CE->getArg(0);
8805
8806 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8807 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8808
8809 // Two DeclRefExpr's, check that the decls are the same.
8810 if (LHSDeclRef && RHSDeclRef) {
8811 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8812 return;
8813 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8814 RHSDeclRef->getDecl()->getCanonicalDecl())
8815 return;
8816
8817 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8818 << LHSExpr->getSourceRange()
8819 << RHSExpr->getSourceRange();
8820 return;
8821 }
8822
8823 // Member variables require a different approach to check for self moves.
8824 // MemberExpr's are the same if every nested MemberExpr refers to the same
8825 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
8826 // the base Expr's are CXXThisExpr's.
8827 const Expr *LHSBase = LHSExpr;
8828 const Expr *RHSBase = RHSExpr;
8829 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
8830 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
8831 if (!LHSME || !RHSME)
8832 return;
8833
8834 while (LHSME && RHSME) {
8835 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
8836 RHSME->getMemberDecl()->getCanonicalDecl())
8837 return;
8838
8839 LHSBase = LHSME->getBase();
8840 RHSBase = RHSME->getBase();
8841 LHSME = dyn_cast<MemberExpr>(LHSBase);
8842 RHSME = dyn_cast<MemberExpr>(RHSBase);
8843 }
8844
8845 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
8846 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
8847 if (LHSDeclRef && RHSDeclRef) {
8848 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8849 return;
8850 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8851 RHSDeclRef->getDecl()->getCanonicalDecl())
8852 return;
8853
8854 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8855 << LHSExpr->getSourceRange()
8856 << RHSExpr->getSourceRange();
8857 return;
8858 }
8859
8860 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
8861 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8862 << LHSExpr->getSourceRange()
8863 << RHSExpr->getSourceRange();
8864}
8865
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008866//===--- Layout compatibility ----------------------------------------------//
8867
8868namespace {
8869
8870bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8871
8872/// \brief Check if two enumeration types are layout-compatible.
8873bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8874 // C++11 [dcl.enum] p8:
8875 // Two enumeration types are layout-compatible if they have the same
8876 // underlying type.
8877 return ED1->isComplete() && ED2->isComplete() &&
8878 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8879}
8880
8881/// \brief Check if two fields are layout-compatible.
8882bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8883 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8884 return false;
8885
8886 if (Field1->isBitField() != Field2->isBitField())
8887 return false;
8888
8889 if (Field1->isBitField()) {
8890 // Make sure that the bit-fields are the same length.
8891 unsigned Bits1 = Field1->getBitWidthValue(C);
8892 unsigned Bits2 = Field2->getBitWidthValue(C);
8893
8894 if (Bits1 != Bits2)
8895 return false;
8896 }
8897
8898 return true;
8899}
8900
8901/// \brief Check if two standard-layout structs are layout-compatible.
8902/// (C++11 [class.mem] p17)
8903bool isLayoutCompatibleStruct(ASTContext &C,
8904 RecordDecl *RD1,
8905 RecordDecl *RD2) {
8906 // If both records are C++ classes, check that base classes match.
8907 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
8908 // If one of records is a CXXRecordDecl we are in C++ mode,
8909 // thus the other one is a CXXRecordDecl, too.
8910 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
8911 // Check number of base classes.
8912 if (D1CXX->getNumBases() != D2CXX->getNumBases())
8913 return false;
8914
8915 // Check the base classes.
8916 for (CXXRecordDecl::base_class_const_iterator
8917 Base1 = D1CXX->bases_begin(),
8918 BaseEnd1 = D1CXX->bases_end(),
8919 Base2 = D2CXX->bases_begin();
8920 Base1 != BaseEnd1;
8921 ++Base1, ++Base2) {
8922 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
8923 return false;
8924 }
8925 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
8926 // If only RD2 is a C++ class, it should have zero base classes.
8927 if (D2CXX->getNumBases() > 0)
8928 return false;
8929 }
8930
8931 // Check the fields.
8932 RecordDecl::field_iterator Field2 = RD2->field_begin(),
8933 Field2End = RD2->field_end(),
8934 Field1 = RD1->field_begin(),
8935 Field1End = RD1->field_end();
8936 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
8937 if (!isLayoutCompatible(C, *Field1, *Field2))
8938 return false;
8939 }
8940 if (Field1 != Field1End || Field2 != Field2End)
8941 return false;
8942
8943 return true;
8944}
8945
8946/// \brief Check if two standard-layout unions are layout-compatible.
8947/// (C++11 [class.mem] p18)
8948bool isLayoutCompatibleUnion(ASTContext &C,
8949 RecordDecl *RD1,
8950 RecordDecl *RD2) {
8951 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008952 for (auto *Field2 : RD2->fields())
8953 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008954
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008955 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008956 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
8957 I = UnmatchedFields.begin(),
8958 E = UnmatchedFields.end();
8959
8960 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008961 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008962 bool Result = UnmatchedFields.erase(*I);
8963 (void) Result;
8964 assert(Result);
8965 break;
8966 }
8967 }
8968 if (I == E)
8969 return false;
8970 }
8971
8972 return UnmatchedFields.empty();
8973}
8974
8975bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
8976 if (RD1->isUnion() != RD2->isUnion())
8977 return false;
8978
8979 if (RD1->isUnion())
8980 return isLayoutCompatibleUnion(C, RD1, RD2);
8981 else
8982 return isLayoutCompatibleStruct(C, RD1, RD2);
8983}
8984
8985/// \brief Check if two types are layout-compatible in C++11 sense.
8986bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
8987 if (T1.isNull() || T2.isNull())
8988 return false;
8989
8990 // C++11 [basic.types] p11:
8991 // If two types T1 and T2 are the same type, then T1 and T2 are
8992 // layout-compatible types.
8993 if (C.hasSameType(T1, T2))
8994 return true;
8995
8996 T1 = T1.getCanonicalType().getUnqualifiedType();
8997 T2 = T2.getCanonicalType().getUnqualifiedType();
8998
8999 const Type::TypeClass TC1 = T1->getTypeClass();
9000 const Type::TypeClass TC2 = T2->getTypeClass();
9001
9002 if (TC1 != TC2)
9003 return false;
9004
9005 if (TC1 == Type::Enum) {
9006 return isLayoutCompatible(C,
9007 cast<EnumType>(T1)->getDecl(),
9008 cast<EnumType>(T2)->getDecl());
9009 } else if (TC1 == Type::Record) {
9010 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
9011 return false;
9012
9013 return isLayoutCompatible(C,
9014 cast<RecordType>(T1)->getDecl(),
9015 cast<RecordType>(T2)->getDecl());
9016 }
9017
9018 return false;
9019}
9020}
9021
9022//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
9023
9024namespace {
9025/// \brief Given a type tag expression find the type tag itself.
9026///
9027/// \param TypeExpr Type tag expression, as it appears in user's code.
9028///
9029/// \param VD Declaration of an identifier that appears in a type tag.
9030///
9031/// \param MagicValue Type tag magic value.
9032bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
9033 const ValueDecl **VD, uint64_t *MagicValue) {
9034 while(true) {
9035 if (!TypeExpr)
9036 return false;
9037
9038 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
9039
9040 switch (TypeExpr->getStmtClass()) {
9041 case Stmt::UnaryOperatorClass: {
9042 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
9043 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
9044 TypeExpr = UO->getSubExpr();
9045 continue;
9046 }
9047 return false;
9048 }
9049
9050 case Stmt::DeclRefExprClass: {
9051 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
9052 *VD = DRE->getDecl();
9053 return true;
9054 }
9055
9056 case Stmt::IntegerLiteralClass: {
9057 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
9058 llvm::APInt MagicValueAPInt = IL->getValue();
9059 if (MagicValueAPInt.getActiveBits() <= 64) {
9060 *MagicValue = MagicValueAPInt.getZExtValue();
9061 return true;
9062 } else
9063 return false;
9064 }
9065
9066 case Stmt::BinaryConditionalOperatorClass:
9067 case Stmt::ConditionalOperatorClass: {
9068 const AbstractConditionalOperator *ACO =
9069 cast<AbstractConditionalOperator>(TypeExpr);
9070 bool Result;
9071 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
9072 if (Result)
9073 TypeExpr = ACO->getTrueExpr();
9074 else
9075 TypeExpr = ACO->getFalseExpr();
9076 continue;
9077 }
9078 return false;
9079 }
9080
9081 case Stmt::BinaryOperatorClass: {
9082 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
9083 if (BO->getOpcode() == BO_Comma) {
9084 TypeExpr = BO->getRHS();
9085 continue;
9086 }
9087 return false;
9088 }
9089
9090 default:
9091 return false;
9092 }
9093 }
9094}
9095
9096/// \brief Retrieve the C type corresponding to type tag TypeExpr.
9097///
9098/// \param TypeExpr Expression that specifies a type tag.
9099///
9100/// \param MagicValues Registered magic values.
9101///
9102/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
9103/// kind.
9104///
9105/// \param TypeInfo Information about the corresponding C type.
9106///
9107/// \returns true if the corresponding C type was found.
9108bool GetMatchingCType(
9109 const IdentifierInfo *ArgumentKind,
9110 const Expr *TypeExpr, const ASTContext &Ctx,
9111 const llvm::DenseMap<Sema::TypeTagMagicValue,
9112 Sema::TypeTagData> *MagicValues,
9113 bool &FoundWrongKind,
9114 Sema::TypeTagData &TypeInfo) {
9115 FoundWrongKind = false;
9116
9117 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00009118 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009119
9120 uint64_t MagicValue;
9121
9122 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
9123 return false;
9124
9125 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00009126 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009127 if (I->getArgumentKind() != ArgumentKind) {
9128 FoundWrongKind = true;
9129 return false;
9130 }
9131 TypeInfo.Type = I->getMatchingCType();
9132 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
9133 TypeInfo.MustBeNull = I->getMustBeNull();
9134 return true;
9135 }
9136 return false;
9137 }
9138
9139 if (!MagicValues)
9140 return false;
9141
9142 llvm::DenseMap<Sema::TypeTagMagicValue,
9143 Sema::TypeTagData>::const_iterator I =
9144 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
9145 if (I == MagicValues->end())
9146 return false;
9147
9148 TypeInfo = I->second;
9149 return true;
9150}
9151} // unnamed namespace
9152
9153void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9154 uint64_t MagicValue, QualType Type,
9155 bool LayoutCompatible,
9156 bool MustBeNull) {
9157 if (!TypeTagForDatatypeMagicValues)
9158 TypeTagForDatatypeMagicValues.reset(
9159 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
9160
9161 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
9162 (*TypeTagForDatatypeMagicValues)[Magic] =
9163 TypeTagData(Type, LayoutCompatible, MustBeNull);
9164}
9165
9166namespace {
9167bool IsSameCharType(QualType T1, QualType T2) {
9168 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
9169 if (!BT1)
9170 return false;
9171
9172 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
9173 if (!BT2)
9174 return false;
9175
9176 BuiltinType::Kind T1Kind = BT1->getKind();
9177 BuiltinType::Kind T2Kind = BT2->getKind();
9178
9179 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
9180 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
9181 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
9182 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
9183}
9184} // unnamed namespace
9185
9186void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9187 const Expr * const *ExprArgs) {
9188 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
9189 bool IsPointerAttr = Attr->getIsPointer();
9190
9191 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
9192 bool FoundWrongKind;
9193 TypeTagData TypeInfo;
9194 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
9195 TypeTagForDatatypeMagicValues.get(),
9196 FoundWrongKind, TypeInfo)) {
9197 if (FoundWrongKind)
9198 Diag(TypeTagExpr->getExprLoc(),
9199 diag::warn_type_tag_for_datatype_wrong_kind)
9200 << TypeTagExpr->getSourceRange();
9201 return;
9202 }
9203
9204 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
9205 if (IsPointerAttr) {
9206 // Skip implicit cast of pointer to `void *' (as a function argument).
9207 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00009208 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00009209 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009210 ArgumentExpr = ICE->getSubExpr();
9211 }
9212 QualType ArgumentType = ArgumentExpr->getType();
9213
9214 // Passing a `void*' pointer shouldn't trigger a warning.
9215 if (IsPointerAttr && ArgumentType->isVoidPointerType())
9216 return;
9217
9218 if (TypeInfo.MustBeNull) {
9219 // Type tag with matching void type requires a null pointer.
9220 if (!ArgumentExpr->isNullPointerConstant(Context,
9221 Expr::NPC_ValueDependentIsNotNull)) {
9222 Diag(ArgumentExpr->getExprLoc(),
9223 diag::warn_type_safety_null_pointer_required)
9224 << ArgumentKind->getName()
9225 << ArgumentExpr->getSourceRange()
9226 << TypeTagExpr->getSourceRange();
9227 }
9228 return;
9229 }
9230
9231 QualType RequiredType = TypeInfo.Type;
9232 if (IsPointerAttr)
9233 RequiredType = Context.getPointerType(RequiredType);
9234
9235 bool mismatch = false;
9236 if (!TypeInfo.LayoutCompatible) {
9237 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
9238
9239 // C++11 [basic.fundamental] p1:
9240 // Plain char, signed char, and unsigned char are three distinct types.
9241 //
9242 // But we treat plain `char' as equivalent to `signed char' or `unsigned
9243 // char' depending on the current char signedness mode.
9244 if (mismatch)
9245 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
9246 RequiredType->getPointeeType())) ||
9247 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
9248 mismatch = false;
9249 } else
9250 if (IsPointerAttr)
9251 mismatch = !isLayoutCompatible(Context,
9252 ArgumentType->getPointeeType(),
9253 RequiredType->getPointeeType());
9254 else
9255 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
9256
9257 if (mismatch)
9258 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00009259 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009260 << TypeInfo.LayoutCompatible << RequiredType
9261 << ArgumentExpr->getSourceRange()
9262 << TypeTagExpr->getSourceRange();
9263}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009264