blob: d73d33d19e9dada288c21bc267d79377d8004e53 [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;
Nate Begeman4904e322010-06-08 02:47:44 +0000554 default:
555 break;
556 }
557 }
558
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000559 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000560}
561
Nate Begeman91e1fea2010-06-14 05:21:25 +0000562// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000563static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000564 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000565 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000566 switch (Type.getEltType()) {
567 case NeonTypeFlags::Int8:
568 case NeonTypeFlags::Poly8:
569 return shift ? 7 : (8 << IsQuad) - 1;
570 case NeonTypeFlags::Int16:
571 case NeonTypeFlags::Poly16:
572 return shift ? 15 : (4 << IsQuad) - 1;
573 case NeonTypeFlags::Int32:
574 return shift ? 31 : (2 << IsQuad) - 1;
575 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000576 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000577 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000578 case NeonTypeFlags::Poly128:
579 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000580 case NeonTypeFlags::Float16:
581 assert(!shift && "cannot shift float types!");
582 return (4 << IsQuad) - 1;
583 case NeonTypeFlags::Float32:
584 assert(!shift && "cannot shift float types!");
585 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000586 case NeonTypeFlags::Float64:
587 assert(!shift && "cannot shift float types!");
588 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000589 }
David Blaikie8a40f702012-01-17 06:56:22 +0000590 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000591}
592
Bob Wilsone4d77232011-11-08 05:04:11 +0000593/// getNeonEltType - Return the QualType corresponding to the elements of
594/// the vector type specified by the NeonTypeFlags. This is used to check
595/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000596static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000597 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000598 switch (Flags.getEltType()) {
599 case NeonTypeFlags::Int8:
600 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
601 case NeonTypeFlags::Int16:
602 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
603 case NeonTypeFlags::Int32:
604 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
605 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000606 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000607 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
608 else
609 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
610 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000611 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000612 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000613 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000614 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000615 case NeonTypeFlags::Poly64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000616 return Context.UnsignedLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000617 case NeonTypeFlags::Poly128:
618 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000619 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000620 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000621 case NeonTypeFlags::Float32:
622 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000623 case NeonTypeFlags::Float64:
624 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000625 }
David Blaikie8a40f702012-01-17 06:56:22 +0000626 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000627}
628
Tim Northover12670412014-02-19 10:37:05 +0000629bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000630 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000631 uint64_t mask = 0;
632 unsigned TV = 0;
633 int PtrArgNum = -1;
634 bool HasConstPtr = false;
635 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000636#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000637#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000638#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000639 }
640
641 // For NEON intrinsics which are overloaded on vector element type, validate
642 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000643 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000644 if (mask) {
645 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
646 return true;
647
648 TV = Result.getLimitedValue(64);
649 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
650 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000651 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000652 }
653
654 if (PtrArgNum >= 0) {
655 // Check that pointer arguments have the specified type.
656 Expr *Arg = TheCall->getArg(PtrArgNum);
657 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
658 Arg = ICE->getSubExpr();
659 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
660 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000661
Tim Northovera2ee4332014-03-29 15:09:45 +0000662 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000663 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000664 bool IsInt64Long =
665 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
666 QualType EltTy =
667 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000668 if (HasConstPtr)
669 EltTy = EltTy.withConst();
670 QualType LHSTy = Context.getPointerType(EltTy);
671 AssignConvertType ConvTy;
672 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
673 if (RHS.isInvalid())
674 return true;
675 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
676 RHS.get(), AA_Assigning))
677 return true;
678 }
679
680 // For NEON intrinsics which take an immediate value as part of the
681 // instruction, range check them here.
682 unsigned i = 0, l = 0, u = 0;
683 switch (BuiltinID) {
684 default:
685 return false;
Tim Northover12670412014-02-19 10:37:05 +0000686#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000687#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000688#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000689 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000690
Richard Sandiford28940af2014-04-16 08:47:51 +0000691 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000692}
693
Tim Northovera2ee4332014-03-29 15:09:45 +0000694bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
695 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000696 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000697 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000698 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000699 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000700 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000701 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
702 BuiltinID == AArch64::BI__builtin_arm_strex ||
703 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000704 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000705 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000706 BuiltinID == ARM::BI__builtin_arm_ldaex ||
707 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
708 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000709
710 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
711
712 // Ensure that we have the proper number of arguments.
713 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
714 return true;
715
716 // Inspect the pointer argument of the atomic builtin. This should always be
717 // a pointer type, whose element is an integral scalar or pointer type.
718 // Because it is a pointer type, we don't have to worry about any implicit
719 // casts here.
720 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
721 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
722 if (PointerArgRes.isInvalid())
723 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000724 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000725
726 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
727 if (!pointerType) {
728 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
729 << PointerArg->getType() << PointerArg->getSourceRange();
730 return true;
731 }
732
733 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
734 // task is to insert the appropriate casts into the AST. First work out just
735 // what the appropriate type is.
736 QualType ValType = pointerType->getPointeeType();
737 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
738 if (IsLdrex)
739 AddrType.addConst();
740
741 // Issue a warning if the cast is dodgy.
742 CastKind CastNeeded = CK_NoOp;
743 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
744 CastNeeded = CK_BitCast;
745 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
746 << PointerArg->getType()
747 << Context.getPointerType(AddrType)
748 << AA_Passing << PointerArg->getSourceRange();
749 }
750
751 // Finally, do the cast and replace the argument with the corrected version.
752 AddrType = Context.getPointerType(AddrType);
753 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
754 if (PointerArgRes.isInvalid())
755 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000756 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000757
758 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
759
760 // In general, we allow ints, floats and pointers to be loaded and stored.
761 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
762 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
763 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
764 << PointerArg->getType() << PointerArg->getSourceRange();
765 return true;
766 }
767
768 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000769 if (Context.getTypeSize(ValType) > MaxWidth) {
770 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000771 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
772 << PointerArg->getType() << PointerArg->getSourceRange();
773 return true;
774 }
775
776 switch (ValType.getObjCLifetime()) {
777 case Qualifiers::OCL_None:
778 case Qualifiers::OCL_ExplicitNone:
779 // okay
780 break;
781
782 case Qualifiers::OCL_Weak:
783 case Qualifiers::OCL_Strong:
784 case Qualifiers::OCL_Autoreleasing:
785 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
786 << ValType << PointerArg->getSourceRange();
787 return true;
788 }
789
790
791 if (IsLdrex) {
792 TheCall->setType(ValType);
793 return false;
794 }
795
796 // Initialize the argument to be stored.
797 ExprResult ValArg = TheCall->getArg(0);
798 InitializedEntity Entity = InitializedEntity::InitializeParameter(
799 Context, ValType, /*consume*/ false);
800 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
801 if (ValArg.isInvalid())
802 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000803 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000804
805 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
806 // but the custom checker bypasses all default analysis.
807 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000808 return false;
809}
810
Nate Begeman4904e322010-06-08 02:47:44 +0000811bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000812 llvm::APSInt Result;
813
Tim Northover6aacd492013-07-16 09:47:53 +0000814 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000815 BuiltinID == ARM::BI__builtin_arm_ldaex ||
816 BuiltinID == ARM::BI__builtin_arm_strex ||
817 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000818 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000819 }
820
Yi Kong26d104a2014-08-13 19:18:14 +0000821 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
822 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
823 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
824 }
825
Tim Northover12670412014-02-19 10:37:05 +0000826 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
827 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000828
Yi Kong4efadfb2014-07-03 16:01:25 +0000829 // For intrinsics which take an immediate value as part of the instruction,
830 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000831 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000832 switch (BuiltinID) {
833 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000834 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
835 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000836 case ARM::BI__builtin_arm_vcvtr_f:
837 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000838 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +0000839 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +0000840 case ARM::BI__builtin_arm_isb:
841 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000842 }
Nate Begemand773fe62010-06-13 04:47:52 +0000843
Nate Begemanf568b072010-08-03 21:32:34 +0000844 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000845 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000846}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000847
Tim Northover573cbee2014-05-24 12:52:07 +0000848bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000849 CallExpr *TheCall) {
850 llvm::APSInt Result;
851
Tim Northover573cbee2014-05-24 12:52:07 +0000852 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000853 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
854 BuiltinID == AArch64::BI__builtin_arm_strex ||
855 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000856 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
857 }
858
Yi Konga5548432014-08-13 19:18:20 +0000859 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
860 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
861 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
862 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
863 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
864 }
865
Tim Northovera2ee4332014-03-29 15:09:45 +0000866 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
867 return true;
868
Yi Kong19a29ac2014-07-17 10:52:06 +0000869 // For intrinsics which take an immediate value as part of the instruction,
870 // range check them here.
871 unsigned i = 0, l = 0, u = 0;
872 switch (BuiltinID) {
873 default: return false;
874 case AArch64::BI__builtin_arm_dmb:
875 case AArch64::BI__builtin_arm_dsb:
876 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
877 }
878
Yi Kong19a29ac2014-07-17 10:52:06 +0000879 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +0000880}
881
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000882bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
883 unsigned i = 0, l = 0, u = 0;
884 switch (BuiltinID) {
885 default: return false;
886 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
887 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000888 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
889 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
890 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
891 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
892 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000893 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000894
Richard Sandiford28940af2014-04-16 08:47:51 +0000895 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000896}
897
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000898bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topperdd84ec52014-12-27 07:00:08 +0000899 unsigned i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000900 switch (BuiltinID) {
Craig Topperdd84ec52014-12-27 07:00:08 +0000901 default: return false;
902 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
Craig Topper16015252015-01-31 06:31:23 +0000903 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
Craig Topper1a8b0472015-01-31 08:57:52 +0000904 case X86::BI__builtin_ia32_vpermil2pd:
905 case X86::BI__builtin_ia32_vpermil2pd256:
906 case X86::BI__builtin_ia32_vpermil2ps:
907 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
Craig Topper95b0d732015-01-25 23:30:05 +0000908 case X86::BI__builtin_ia32_cmpb128_mask:
909 case X86::BI__builtin_ia32_cmpw128_mask:
910 case X86::BI__builtin_ia32_cmpd128_mask:
911 case X86::BI__builtin_ia32_cmpq128_mask:
912 case X86::BI__builtin_ia32_cmpb256_mask:
913 case X86::BI__builtin_ia32_cmpw256_mask:
914 case X86::BI__builtin_ia32_cmpd256_mask:
915 case X86::BI__builtin_ia32_cmpq256_mask:
916 case X86::BI__builtin_ia32_cmpb512_mask:
917 case X86::BI__builtin_ia32_cmpw512_mask:
918 case X86::BI__builtin_ia32_cmpd512_mask:
919 case X86::BI__builtin_ia32_cmpq512_mask:
920 case X86::BI__builtin_ia32_ucmpb128_mask:
921 case X86::BI__builtin_ia32_ucmpw128_mask:
922 case X86::BI__builtin_ia32_ucmpd128_mask:
923 case X86::BI__builtin_ia32_ucmpq128_mask:
924 case X86::BI__builtin_ia32_ucmpb256_mask:
925 case X86::BI__builtin_ia32_ucmpw256_mask:
926 case X86::BI__builtin_ia32_ucmpd256_mask:
927 case X86::BI__builtin_ia32_ucmpq256_mask:
928 case X86::BI__builtin_ia32_ucmpb512_mask:
929 case X86::BI__builtin_ia32_ucmpw512_mask:
930 case X86::BI__builtin_ia32_ucmpd512_mask:
931 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
Craig Topper16015252015-01-31 06:31:23 +0000932 case X86::BI__builtin_ia32_roundps:
933 case X86::BI__builtin_ia32_roundpd:
934 case X86::BI__builtin_ia32_roundps256:
935 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
936 case X86::BI__builtin_ia32_roundss:
937 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
938 case X86::BI__builtin_ia32_cmpps:
939 case X86::BI__builtin_ia32_cmpss:
940 case X86::BI__builtin_ia32_cmppd:
941 case X86::BI__builtin_ia32_cmpsd:
942 case X86::BI__builtin_ia32_cmpps256:
943 case X86::BI__builtin_ia32_cmppd256:
944 case X86::BI__builtin_ia32_cmpps512_mask:
945 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +0000946 case X86::BI__builtin_ia32_vpcomub:
947 case X86::BI__builtin_ia32_vpcomuw:
948 case X86::BI__builtin_ia32_vpcomud:
949 case X86::BI__builtin_ia32_vpcomuq:
950 case X86::BI__builtin_ia32_vpcomb:
951 case X86::BI__builtin_ia32_vpcomw:
952 case X86::BI__builtin_ia32_vpcomd:
953 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000954 }
Craig Topperdd84ec52014-12-27 07:00:08 +0000955 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000956}
957
Richard Smith55ce3522012-06-25 20:30:08 +0000958/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
959/// parameter with the FormatAttr's correct format_idx and firstDataArg.
960/// Returns true when the format fits the function and the FormatStringInfo has
961/// been populated.
962bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
963 FormatStringInfo *FSI) {
964 FSI->HasVAListArg = Format->getFirstArg() == 0;
965 FSI->FormatIdx = Format->getFormatIdx() - 1;
966 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000967
Richard Smith55ce3522012-06-25 20:30:08 +0000968 // The way the format attribute works in GCC, the implicit this argument
969 // of member functions is counted. However, it doesn't appear in our own
970 // lists, so decrement format_idx in that case.
971 if (IsCXXMember) {
972 if(FSI->FormatIdx == 0)
973 return false;
974 --FSI->FormatIdx;
975 if (FSI->FirstDataArg != 0)
976 --FSI->FirstDataArg;
977 }
978 return true;
979}
Mike Stump11289f42009-09-09 15:08:12 +0000980
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000981/// Checks if a the given expression evaluates to null.
982///
983/// \brief Returns true if the value evaluates to null.
984static bool CheckNonNullExpr(Sema &S,
985 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000986 // As a special case, transparent unions initialized with zero are
987 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000988 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000989 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
990 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000991 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000992 if (const InitListExpr *ILE =
993 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000994 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000995 }
996
997 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000998 return (!Expr->isValueDependent() &&
999 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1000 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001001}
1002
1003static void CheckNonNullArgument(Sema &S,
1004 const Expr *ArgExpr,
1005 SourceLocation CallSiteLoc) {
1006 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001007 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
1008}
1009
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001010bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1011 FormatStringInfo FSI;
1012 if ((GetFormatStringType(Format) == FST_NSString) &&
1013 getFormatStringInfo(Format, false, &FSI)) {
1014 Idx = FSI.FormatIdx;
1015 return true;
1016 }
1017 return false;
1018}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001019/// \brief Diagnose use of %s directive in an NSString which is being passed
1020/// as formatting string to formatting method.
1021static void
1022DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1023 const NamedDecl *FDecl,
1024 Expr **Args,
1025 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001026 unsigned Idx = 0;
1027 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001028 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1029 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001030 Idx = 2;
1031 Format = true;
1032 }
1033 else
1034 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1035 if (S.GetFormatNSStringIdx(I, Idx)) {
1036 Format = true;
1037 break;
1038 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001039 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001040 if (!Format || NumArgs <= Idx)
1041 return;
1042 const Expr *FormatExpr = Args[Idx];
1043 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1044 FormatExpr = CSCE->getSubExpr();
1045 const StringLiteral *FormatString;
1046 if (const ObjCStringLiteral *OSL =
1047 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1048 FormatString = OSL->getString();
1049 else
1050 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1051 if (!FormatString)
1052 return;
1053 if (S.FormatStringHasSArg(FormatString)) {
1054 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1055 << "%s" << 1 << 1;
1056 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1057 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001058 }
1059}
1060
Ted Kremenek2bc73332014-01-17 06:24:43 +00001061static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001062 const NamedDecl *FDecl,
Richard Smith588bd9b2014-08-27 04:59:42 +00001063 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001064 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +00001065 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001066 llvm::SmallBitVector NonNullArgs;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001067 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001068 if (!NonNull->args_size()) {
1069 // Easy case: all pointer arguments are nonnull.
1070 for (const auto *Arg : Args)
Hal Finkelee90a222014-09-26 05:04:30 +00001071 if (S.isValidPointerAttrType(Arg->getType()))
Richard Smith588bd9b2014-08-27 04:59:42 +00001072 CheckNonNullArgument(S, Arg, CallSiteLoc);
1073 return;
1074 }
1075
1076 for (unsigned Val : NonNull->args()) {
1077 if (Val >= Args.size())
1078 continue;
1079 if (NonNullArgs.empty())
1080 NonNullArgs.resize(Args.size());
1081 NonNullArgs.set(Val);
1082 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001083 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001084
1085 // Check the attributes on the parameters.
1086 ArrayRef<ParmVarDecl*> parms;
1087 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1088 parms = FD->parameters();
1089 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
1090 parms = MD->parameters();
1091
Richard Smith588bd9b2014-08-27 04:59:42 +00001092 unsigned ArgIndex = 0;
Ted Kremenek9aedc152014-01-17 06:24:56 +00001093 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
Richard Smith588bd9b2014-08-27 04:59:42 +00001094 I != E; ++I, ++ArgIndex) {
Ted Kremenek9aedc152014-01-17 06:24:56 +00001095 const ParmVarDecl *PVD = *I;
Richard Smith588bd9b2014-08-27 04:59:42 +00001096 if (PVD->hasAttr<NonNullAttr>() ||
1097 (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
1098 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek9aedc152014-01-17 06:24:56 +00001099 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001100
1101 // In case this is a variadic call, check any remaining arguments.
1102 for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
1103 if (NonNullArgs[ArgIndex])
1104 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +00001105}
1106
Richard Smith55ce3522012-06-25 20:30:08 +00001107/// Handles the checks for format strings, non-POD arguments to vararg
1108/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00001109void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
1110 unsigned NumParams, bool IsMemberFunction,
1111 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001112 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001113 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001114 if (CurContext->isDependentContext())
1115 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001116
Ted Kremenekb8176da2010-09-09 04:33:05 +00001117 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001118 llvm::SmallBitVector CheckedVarArgs;
1119 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001120 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001121 // Only create vector if there are format attributes.
1122 CheckedVarArgs.resize(Args.size());
1123
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001124 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001125 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001126 }
Richard Smithd7293d72013-08-05 18:49:43 +00001127 }
Richard Smith55ce3522012-06-25 20:30:08 +00001128
1129 // Refuse POD arguments that weren't caught by the format string
1130 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001131 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001132 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001133 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001134 if (const Expr *Arg = Args[ArgIdx]) {
1135 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1136 checkVariadicArgument(Arg, CallType);
1137 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001138 }
Richard Smithd7293d72013-08-05 18:49:43 +00001139 }
Mike Stump11289f42009-09-09 15:08:12 +00001140
Richard Trieu41bc0992013-06-22 00:20:41 +00001141 if (FDecl) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001142 CheckNonNullArguments(*this, FDecl, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001143
Richard Trieu41bc0992013-06-22 00:20:41 +00001144 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001145 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1146 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001147 }
Richard Smith55ce3522012-06-25 20:30:08 +00001148}
1149
1150/// CheckConstructorCall - Check a constructor call for correctness and safety
1151/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001152void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1153 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001154 const FunctionProtoType *Proto,
1155 SourceLocation Loc) {
1156 VariadicCallType CallType =
1157 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +00001158 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +00001159 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
1160}
1161
1162/// CheckFunctionCall - Check a direct function call for various correctness
1163/// and safety properties not strictly enforced by the C type system.
1164bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1165 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001166 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1167 isa<CXXMethodDecl>(FDecl);
1168 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1169 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001170 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1171 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001172 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +00001173 Expr** Args = TheCall->getArgs();
1174 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001175 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001176 // If this is a call to a member operator, hide the first argument
1177 // from checkCall.
1178 // FIXME: Our choice of AST representation here is less than ideal.
1179 ++Args;
1180 --NumArgs;
1181 }
Craig Topper8c2a2a02014-08-30 16:55:39 +00001182 checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +00001183 IsMemberFunction, TheCall->getRParenLoc(),
1184 TheCall->getCallee()->getSourceRange(), CallType);
1185
1186 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1187 // None of the checks below are needed for functions that don't have
1188 // simple names (e.g., C++ conversion functions).
1189 if (!FnInfo)
1190 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001191
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001192 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001193 if (getLangOpts().ObjC1)
1194 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001195
Anna Zaks22122702012-01-17 00:37:07 +00001196 unsigned CMId = FDecl->getMemoryFunctionKind();
1197 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001198 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001199
Anna Zaks201d4892012-01-13 21:52:01 +00001200 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001201 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001202 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001203 else if (CMId == Builtin::BIstrncat)
1204 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001205 else
Anna Zaks22122702012-01-17 00:37:07 +00001206 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001207
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001208 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001209}
1210
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001211bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001212 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001213 VariadicCallType CallType =
1214 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001215
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001216 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +00001217 /*IsMemberFunction=*/false,
1218 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001219
1220 return false;
1221}
1222
Richard Trieu664c4c62013-06-20 21:03:13 +00001223bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1224 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001225 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
1226 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001227 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001228
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001229 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +00001230 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001231 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001232
Richard Trieu664c4c62013-06-20 21:03:13 +00001233 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001234 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001235 CallType = VariadicDoesNotApply;
1236 } else if (Ty->isBlockPointerType()) {
1237 CallType = VariadicBlock;
1238 } else { // Ty->isFunctionPointerType()
1239 CallType = VariadicFunction;
1240 }
Alp Toker9cacbab2014-01-20 20:26:09 +00001241 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001242
Craig Topper8c2a2a02014-08-30 16:55:39 +00001243 checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
1244 TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001245 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001246 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001247
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001248 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001249}
1250
Richard Trieu41bc0992013-06-22 00:20:41 +00001251/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1252/// such as function pointers returned from functions.
1253bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001254 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001255 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001256 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +00001257
Craig Topperc3ec1492014-05-26 06:22:03 +00001258 checkCall(/*FDecl=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001259 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001260 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001261 TheCall->getCallee()->getSourceRange(), CallType);
1262
1263 return false;
1264}
1265
Tim Northovere94a34c2014-03-11 10:49:14 +00001266static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1267 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1268 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1269 return false;
1270
1271 switch (Op) {
1272 case AtomicExpr::AO__c11_atomic_init:
1273 llvm_unreachable("There is no ordering argument for an init");
1274
1275 case AtomicExpr::AO__c11_atomic_load:
1276 case AtomicExpr::AO__atomic_load_n:
1277 case AtomicExpr::AO__atomic_load:
1278 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1279 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1280
1281 case AtomicExpr::AO__c11_atomic_store:
1282 case AtomicExpr::AO__atomic_store:
1283 case AtomicExpr::AO__atomic_store_n:
1284 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1285 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1286 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1287
1288 default:
1289 return true;
1290 }
1291}
1292
Richard Smithfeea8832012-04-12 05:08:17 +00001293ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1294 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001295 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1296 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001297
Richard Smithfeea8832012-04-12 05:08:17 +00001298 // All these operations take one of the following forms:
1299 enum {
1300 // C __c11_atomic_init(A *, C)
1301 Init,
1302 // C __c11_atomic_load(A *, int)
1303 Load,
1304 // void __atomic_load(A *, CP, int)
1305 Copy,
1306 // C __c11_atomic_add(A *, M, int)
1307 Arithmetic,
1308 // C __atomic_exchange_n(A *, CP, int)
1309 Xchg,
1310 // void __atomic_exchange(A *, C *, CP, int)
1311 GNUXchg,
1312 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1313 C11CmpXchg,
1314 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1315 GNUCmpXchg
1316 } Form = Init;
1317 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1318 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1319 // where:
1320 // C is an appropriate type,
1321 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1322 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1323 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1324 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001325
Gabor Horvath98bd0982015-03-16 09:59:54 +00001326 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1327 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1328 AtomicExpr::AO__atomic_load,
1329 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00001330 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1331 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1332 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1333 Op == AtomicExpr::AO__atomic_store_n ||
1334 Op == AtomicExpr::AO__atomic_exchange_n ||
1335 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1336 bool IsAddSub = false;
1337
1338 switch (Op) {
1339 case AtomicExpr::AO__c11_atomic_init:
1340 Form = Init;
1341 break;
1342
1343 case AtomicExpr::AO__c11_atomic_load:
1344 case AtomicExpr::AO__atomic_load_n:
1345 Form = Load;
1346 break;
1347
1348 case AtomicExpr::AO__c11_atomic_store:
1349 case AtomicExpr::AO__atomic_load:
1350 case AtomicExpr::AO__atomic_store:
1351 case AtomicExpr::AO__atomic_store_n:
1352 Form = Copy;
1353 break;
1354
1355 case AtomicExpr::AO__c11_atomic_fetch_add:
1356 case AtomicExpr::AO__c11_atomic_fetch_sub:
1357 case AtomicExpr::AO__atomic_fetch_add:
1358 case AtomicExpr::AO__atomic_fetch_sub:
1359 case AtomicExpr::AO__atomic_add_fetch:
1360 case AtomicExpr::AO__atomic_sub_fetch:
1361 IsAddSub = true;
1362 // Fall through.
1363 case AtomicExpr::AO__c11_atomic_fetch_and:
1364 case AtomicExpr::AO__c11_atomic_fetch_or:
1365 case AtomicExpr::AO__c11_atomic_fetch_xor:
1366 case AtomicExpr::AO__atomic_fetch_and:
1367 case AtomicExpr::AO__atomic_fetch_or:
1368 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001369 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001370 case AtomicExpr::AO__atomic_and_fetch:
1371 case AtomicExpr::AO__atomic_or_fetch:
1372 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001373 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001374 Form = Arithmetic;
1375 break;
1376
1377 case AtomicExpr::AO__c11_atomic_exchange:
1378 case AtomicExpr::AO__atomic_exchange_n:
1379 Form = Xchg;
1380 break;
1381
1382 case AtomicExpr::AO__atomic_exchange:
1383 Form = GNUXchg;
1384 break;
1385
1386 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1387 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1388 Form = C11CmpXchg;
1389 break;
1390
1391 case AtomicExpr::AO__atomic_compare_exchange:
1392 case AtomicExpr::AO__atomic_compare_exchange_n:
1393 Form = GNUCmpXchg;
1394 break;
1395 }
1396
1397 // Check we have the right number of arguments.
1398 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001399 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001400 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001401 << TheCall->getCallee()->getSourceRange();
1402 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001403 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1404 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001405 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001406 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001407 << TheCall->getCallee()->getSourceRange();
1408 return ExprError();
1409 }
1410
Richard Smithfeea8832012-04-12 05:08:17 +00001411 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001412 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001413 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1414 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1415 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001416 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001417 << Ptr->getType() << Ptr->getSourceRange();
1418 return ExprError();
1419 }
1420
Richard Smithfeea8832012-04-12 05:08:17 +00001421 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1422 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1423 QualType ValType = AtomTy; // 'C'
1424 if (IsC11) {
1425 if (!AtomTy->isAtomicType()) {
1426 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1427 << Ptr->getType() << Ptr->getSourceRange();
1428 return ExprError();
1429 }
Richard Smithe00921a2012-09-15 06:09:58 +00001430 if (AtomTy.isConstQualified()) {
1431 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1432 << Ptr->getType() << Ptr->getSourceRange();
1433 return ExprError();
1434 }
Richard Smithfeea8832012-04-12 05:08:17 +00001435 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001436 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001437
Richard Smithfeea8832012-04-12 05:08:17 +00001438 // For an arithmetic operation, the implied arithmetic must be well-formed.
1439 if (Form == Arithmetic) {
1440 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1441 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1442 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1443 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1444 return ExprError();
1445 }
1446 if (!IsAddSub && !ValType->isIntegerType()) {
1447 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1448 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1449 return ExprError();
1450 }
David Majnemere85cff82015-01-28 05:48:06 +00001451 if (IsC11 && ValType->isPointerType() &&
1452 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1453 diag::err_incomplete_type)) {
1454 return ExprError();
1455 }
Richard Smithfeea8832012-04-12 05:08:17 +00001456 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1457 // For __atomic_*_n operations, the value type must be a scalar integral or
1458 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001459 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001460 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1461 return ExprError();
1462 }
1463
Eli Friedmanaa769812013-09-11 03:49:34 +00001464 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1465 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001466 // For GNU atomics, require a trivially-copyable type. This is not part of
1467 // the GNU atomics specification, but we enforce it for sanity.
1468 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001469 << Ptr->getType() << Ptr->getSourceRange();
1470 return ExprError();
1471 }
1472
Richard Smithfeea8832012-04-12 05:08:17 +00001473 // FIXME: For any builtin other than a load, the ValType must not be
1474 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001475
1476 switch (ValType.getObjCLifetime()) {
1477 case Qualifiers::OCL_None:
1478 case Qualifiers::OCL_ExplicitNone:
1479 // okay
1480 break;
1481
1482 case Qualifiers::OCL_Weak:
1483 case Qualifiers::OCL_Strong:
1484 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001485 // FIXME: Can this happen? By this point, ValType should be known
1486 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001487 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1488 << ValType << Ptr->getSourceRange();
1489 return ExprError();
1490 }
1491
1492 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001493 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001494 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001495 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001496 ResultType = Context.BoolTy;
1497
Richard Smithfeea8832012-04-12 05:08:17 +00001498 // The type of a parameter passed 'by value'. In the GNU atomics, such
1499 // arguments are actually passed as pointers.
1500 QualType ByValType = ValType; // 'CP'
1501 if (!IsC11 && !IsN)
1502 ByValType = Ptr->getType();
1503
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001504 // The first argument --- the pointer --- has a fixed type; we
1505 // deduce the types of the rest of the arguments accordingly. Walk
1506 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001507 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001508 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001509 if (i < NumVals[Form] + 1) {
1510 switch (i) {
1511 case 1:
1512 // The second argument is the non-atomic operand. For arithmetic, this
1513 // is always passed by value, and for a compare_exchange it is always
1514 // passed by address. For the rest, GNU uses by-address and C11 uses
1515 // by-value.
1516 assert(Form != Load);
1517 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1518 Ty = ValType;
1519 else if (Form == Copy || Form == Xchg)
1520 Ty = ByValType;
1521 else if (Form == Arithmetic)
1522 Ty = Context.getPointerDiffType();
1523 else
1524 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1525 break;
1526 case 2:
1527 // The third argument to compare_exchange / GNU exchange is a
1528 // (pointer to a) desired value.
1529 Ty = ByValType;
1530 break;
1531 case 3:
1532 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1533 Ty = Context.BoolTy;
1534 break;
1535 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001536 } else {
1537 // The order(s) are always converted to int.
1538 Ty = Context.IntTy;
1539 }
Richard Smithfeea8832012-04-12 05:08:17 +00001540
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001541 InitializedEntity Entity =
1542 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001543 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001544 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1545 if (Arg.isInvalid())
1546 return true;
1547 TheCall->setArg(i, Arg.get());
1548 }
1549
Richard Smithfeea8832012-04-12 05:08:17 +00001550 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001551 SmallVector<Expr*, 5> SubExprs;
1552 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001553 switch (Form) {
1554 case Init:
1555 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001556 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001557 break;
1558 case Load:
1559 SubExprs.push_back(TheCall->getArg(1)); // Order
1560 break;
1561 case Copy:
1562 case Arithmetic:
1563 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001564 SubExprs.push_back(TheCall->getArg(2)); // Order
1565 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001566 break;
1567 case GNUXchg:
1568 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1569 SubExprs.push_back(TheCall->getArg(3)); // Order
1570 SubExprs.push_back(TheCall->getArg(1)); // Val1
1571 SubExprs.push_back(TheCall->getArg(2)); // Val2
1572 break;
1573 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001574 SubExprs.push_back(TheCall->getArg(3)); // Order
1575 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001576 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001577 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001578 break;
1579 case GNUCmpXchg:
1580 SubExprs.push_back(TheCall->getArg(4)); // Order
1581 SubExprs.push_back(TheCall->getArg(1)); // Val1
1582 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1583 SubExprs.push_back(TheCall->getArg(2)); // Val2
1584 SubExprs.push_back(TheCall->getArg(3)); // Weak
1585 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001586 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001587
1588 if (SubExprs.size() >= 2 && Form != Init) {
1589 llvm::APSInt Result(32);
1590 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1591 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001592 Diag(SubExprs[1]->getLocStart(),
1593 diag::warn_atomic_op_has_invalid_memory_order)
1594 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001595 }
1596
Fariborz Jahanian615de762013-05-28 17:37:39 +00001597 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1598 SubExprs, ResultType, Op,
1599 TheCall->getRParenLoc());
1600
1601 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1602 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1603 Context.AtomicUsesUnsupportedLibcall(AE))
1604 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1605 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001606
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001607 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001608}
1609
1610
John McCall29ad95b2011-08-27 01:09:30 +00001611/// checkBuiltinArgument - Given a call to a builtin function, perform
1612/// normal type-checking on the given argument, updating the call in
1613/// place. This is useful when a builtin function requires custom
1614/// type-checking for some of its arguments but not necessarily all of
1615/// them.
1616///
1617/// Returns true on error.
1618static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1619 FunctionDecl *Fn = E->getDirectCallee();
1620 assert(Fn && "builtin call without direct callee!");
1621
1622 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1623 InitializedEntity Entity =
1624 InitializedEntity::InitializeParameter(S.Context, Param);
1625
1626 ExprResult Arg = E->getArg(0);
1627 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1628 if (Arg.isInvalid())
1629 return true;
1630
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001631 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001632 return false;
1633}
1634
Chris Lattnerdc046542009-05-08 06:58:22 +00001635/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1636/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1637/// type of its first argument. The main ActOnCallExpr routines have already
1638/// promoted the types of arguments because all of these calls are prototyped as
1639/// void(...).
1640///
1641/// This function goes through and does final semantic checking for these
1642/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001643ExprResult
1644Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001645 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001646 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1647 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1648
1649 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001650 if (TheCall->getNumArgs() < 1) {
1651 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1652 << 0 << 1 << TheCall->getNumArgs()
1653 << TheCall->getCallee()->getSourceRange();
1654 return ExprError();
1655 }
Mike Stump11289f42009-09-09 15:08:12 +00001656
Chris Lattnerdc046542009-05-08 06:58:22 +00001657 // Inspect the first argument of the atomic builtin. This should always be
1658 // a pointer type, whose element is an integral scalar or pointer type.
1659 // Because it is a pointer type, we don't have to worry about any implicit
1660 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001661 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001662 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001663 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1664 if (FirstArgResult.isInvalid())
1665 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001666 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001667 TheCall->setArg(0, FirstArg);
1668
John McCall31168b02011-06-15 23:02:42 +00001669 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1670 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001671 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1672 << FirstArg->getType() << FirstArg->getSourceRange();
1673 return ExprError();
1674 }
Mike Stump11289f42009-09-09 15:08:12 +00001675
John McCall31168b02011-06-15 23:02:42 +00001676 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001677 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001678 !ValType->isBlockPointerType()) {
1679 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1680 << FirstArg->getType() << FirstArg->getSourceRange();
1681 return ExprError();
1682 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001683
John McCall31168b02011-06-15 23:02:42 +00001684 switch (ValType.getObjCLifetime()) {
1685 case Qualifiers::OCL_None:
1686 case Qualifiers::OCL_ExplicitNone:
1687 // okay
1688 break;
1689
1690 case Qualifiers::OCL_Weak:
1691 case Qualifiers::OCL_Strong:
1692 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001693 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001694 << ValType << FirstArg->getSourceRange();
1695 return ExprError();
1696 }
1697
John McCallb50451a2011-10-05 07:41:44 +00001698 // Strip any qualifiers off ValType.
1699 ValType = ValType.getUnqualifiedType();
1700
Chandler Carruth3973af72010-07-18 20:54:12 +00001701 // The majority of builtins return a value, but a few have special return
1702 // types, so allow them to override appropriately below.
1703 QualType ResultType = ValType;
1704
Chris Lattnerdc046542009-05-08 06:58:22 +00001705 // We need to figure out which concrete builtin this maps onto. For example,
1706 // __sync_fetch_and_add with a 2 byte object turns into
1707 // __sync_fetch_and_add_2.
1708#define BUILTIN_ROW(x) \
1709 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1710 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001711
Chris Lattnerdc046542009-05-08 06:58:22 +00001712 static const unsigned BuiltinIndices[][5] = {
1713 BUILTIN_ROW(__sync_fetch_and_add),
1714 BUILTIN_ROW(__sync_fetch_and_sub),
1715 BUILTIN_ROW(__sync_fetch_and_or),
1716 BUILTIN_ROW(__sync_fetch_and_and),
1717 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00001718 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00001719
Chris Lattnerdc046542009-05-08 06:58:22 +00001720 BUILTIN_ROW(__sync_add_and_fetch),
1721 BUILTIN_ROW(__sync_sub_and_fetch),
1722 BUILTIN_ROW(__sync_and_and_fetch),
1723 BUILTIN_ROW(__sync_or_and_fetch),
1724 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00001725 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001726
Chris Lattnerdc046542009-05-08 06:58:22 +00001727 BUILTIN_ROW(__sync_val_compare_and_swap),
1728 BUILTIN_ROW(__sync_bool_compare_and_swap),
1729 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001730 BUILTIN_ROW(__sync_lock_release),
1731 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001732 };
Mike Stump11289f42009-09-09 15:08:12 +00001733#undef BUILTIN_ROW
1734
Chris Lattnerdc046542009-05-08 06:58:22 +00001735 // Determine the index of the size.
1736 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001737 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001738 case 1: SizeIndex = 0; break;
1739 case 2: SizeIndex = 1; break;
1740 case 4: SizeIndex = 2; break;
1741 case 8: SizeIndex = 3; break;
1742 case 16: SizeIndex = 4; break;
1743 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001744 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1745 << FirstArg->getType() << FirstArg->getSourceRange();
1746 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001747 }
Mike Stump11289f42009-09-09 15:08:12 +00001748
Chris Lattnerdc046542009-05-08 06:58:22 +00001749 // Each of these builtins has one pointer argument, followed by some number of
1750 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1751 // that we ignore. Find out which row of BuiltinIndices to read from as well
1752 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001753 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001754 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00001755 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00001756 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001757 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001758 case Builtin::BI__sync_fetch_and_add:
1759 case Builtin::BI__sync_fetch_and_add_1:
1760 case Builtin::BI__sync_fetch_and_add_2:
1761 case Builtin::BI__sync_fetch_and_add_4:
1762 case Builtin::BI__sync_fetch_and_add_8:
1763 case Builtin::BI__sync_fetch_and_add_16:
1764 BuiltinIndex = 0;
1765 break;
1766
1767 case Builtin::BI__sync_fetch_and_sub:
1768 case Builtin::BI__sync_fetch_and_sub_1:
1769 case Builtin::BI__sync_fetch_and_sub_2:
1770 case Builtin::BI__sync_fetch_and_sub_4:
1771 case Builtin::BI__sync_fetch_and_sub_8:
1772 case Builtin::BI__sync_fetch_and_sub_16:
1773 BuiltinIndex = 1;
1774 break;
1775
1776 case Builtin::BI__sync_fetch_and_or:
1777 case Builtin::BI__sync_fetch_and_or_1:
1778 case Builtin::BI__sync_fetch_and_or_2:
1779 case Builtin::BI__sync_fetch_and_or_4:
1780 case Builtin::BI__sync_fetch_and_or_8:
1781 case Builtin::BI__sync_fetch_and_or_16:
1782 BuiltinIndex = 2;
1783 break;
1784
1785 case Builtin::BI__sync_fetch_and_and:
1786 case Builtin::BI__sync_fetch_and_and_1:
1787 case Builtin::BI__sync_fetch_and_and_2:
1788 case Builtin::BI__sync_fetch_and_and_4:
1789 case Builtin::BI__sync_fetch_and_and_8:
1790 case Builtin::BI__sync_fetch_and_and_16:
1791 BuiltinIndex = 3;
1792 break;
Mike Stump11289f42009-09-09 15:08:12 +00001793
Douglas Gregor73722482011-11-28 16:30:08 +00001794 case Builtin::BI__sync_fetch_and_xor:
1795 case Builtin::BI__sync_fetch_and_xor_1:
1796 case Builtin::BI__sync_fetch_and_xor_2:
1797 case Builtin::BI__sync_fetch_and_xor_4:
1798 case Builtin::BI__sync_fetch_and_xor_8:
1799 case Builtin::BI__sync_fetch_and_xor_16:
1800 BuiltinIndex = 4;
1801 break;
1802
Hal Finkeld2208b52014-10-02 20:53:50 +00001803 case Builtin::BI__sync_fetch_and_nand:
1804 case Builtin::BI__sync_fetch_and_nand_1:
1805 case Builtin::BI__sync_fetch_and_nand_2:
1806 case Builtin::BI__sync_fetch_and_nand_4:
1807 case Builtin::BI__sync_fetch_and_nand_8:
1808 case Builtin::BI__sync_fetch_and_nand_16:
1809 BuiltinIndex = 5;
1810 WarnAboutSemanticsChange = true;
1811 break;
1812
Douglas Gregor73722482011-11-28 16:30:08 +00001813 case Builtin::BI__sync_add_and_fetch:
1814 case Builtin::BI__sync_add_and_fetch_1:
1815 case Builtin::BI__sync_add_and_fetch_2:
1816 case Builtin::BI__sync_add_and_fetch_4:
1817 case Builtin::BI__sync_add_and_fetch_8:
1818 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001819 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00001820 break;
1821
1822 case Builtin::BI__sync_sub_and_fetch:
1823 case Builtin::BI__sync_sub_and_fetch_1:
1824 case Builtin::BI__sync_sub_and_fetch_2:
1825 case Builtin::BI__sync_sub_and_fetch_4:
1826 case Builtin::BI__sync_sub_and_fetch_8:
1827 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001828 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00001829 break;
1830
1831 case Builtin::BI__sync_and_and_fetch:
1832 case Builtin::BI__sync_and_and_fetch_1:
1833 case Builtin::BI__sync_and_and_fetch_2:
1834 case Builtin::BI__sync_and_and_fetch_4:
1835 case Builtin::BI__sync_and_and_fetch_8:
1836 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001837 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00001838 break;
1839
1840 case Builtin::BI__sync_or_and_fetch:
1841 case Builtin::BI__sync_or_and_fetch_1:
1842 case Builtin::BI__sync_or_and_fetch_2:
1843 case Builtin::BI__sync_or_and_fetch_4:
1844 case Builtin::BI__sync_or_and_fetch_8:
1845 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001846 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00001847 break;
1848
1849 case Builtin::BI__sync_xor_and_fetch:
1850 case Builtin::BI__sync_xor_and_fetch_1:
1851 case Builtin::BI__sync_xor_and_fetch_2:
1852 case Builtin::BI__sync_xor_and_fetch_4:
1853 case Builtin::BI__sync_xor_and_fetch_8:
1854 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001855 BuiltinIndex = 10;
1856 break;
1857
1858 case Builtin::BI__sync_nand_and_fetch:
1859 case Builtin::BI__sync_nand_and_fetch_1:
1860 case Builtin::BI__sync_nand_and_fetch_2:
1861 case Builtin::BI__sync_nand_and_fetch_4:
1862 case Builtin::BI__sync_nand_and_fetch_8:
1863 case Builtin::BI__sync_nand_and_fetch_16:
1864 BuiltinIndex = 11;
1865 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00001866 break;
Mike Stump11289f42009-09-09 15:08:12 +00001867
Chris Lattnerdc046542009-05-08 06:58:22 +00001868 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001869 case Builtin::BI__sync_val_compare_and_swap_1:
1870 case Builtin::BI__sync_val_compare_and_swap_2:
1871 case Builtin::BI__sync_val_compare_and_swap_4:
1872 case Builtin::BI__sync_val_compare_and_swap_8:
1873 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001874 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00001875 NumFixed = 2;
1876 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001877
Chris Lattnerdc046542009-05-08 06:58:22 +00001878 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001879 case Builtin::BI__sync_bool_compare_and_swap_1:
1880 case Builtin::BI__sync_bool_compare_and_swap_2:
1881 case Builtin::BI__sync_bool_compare_and_swap_4:
1882 case Builtin::BI__sync_bool_compare_and_swap_8:
1883 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001884 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001885 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001886 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001887 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001888
1889 case Builtin::BI__sync_lock_test_and_set:
1890 case Builtin::BI__sync_lock_test_and_set_1:
1891 case Builtin::BI__sync_lock_test_and_set_2:
1892 case Builtin::BI__sync_lock_test_and_set_4:
1893 case Builtin::BI__sync_lock_test_and_set_8:
1894 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001895 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00001896 break;
1897
Chris Lattnerdc046542009-05-08 06:58:22 +00001898 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001899 case Builtin::BI__sync_lock_release_1:
1900 case Builtin::BI__sync_lock_release_2:
1901 case Builtin::BI__sync_lock_release_4:
1902 case Builtin::BI__sync_lock_release_8:
1903 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001904 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00001905 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001906 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001907 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001908
1909 case Builtin::BI__sync_swap:
1910 case Builtin::BI__sync_swap_1:
1911 case Builtin::BI__sync_swap_2:
1912 case Builtin::BI__sync_swap_4:
1913 case Builtin::BI__sync_swap_8:
1914 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001915 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00001916 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001917 }
Mike Stump11289f42009-09-09 15:08:12 +00001918
Chris Lattnerdc046542009-05-08 06:58:22 +00001919 // Now that we know how many fixed arguments we expect, first check that we
1920 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001921 if (TheCall->getNumArgs() < 1+NumFixed) {
1922 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1923 << 0 << 1+NumFixed << TheCall->getNumArgs()
1924 << TheCall->getCallee()->getSourceRange();
1925 return ExprError();
1926 }
Mike Stump11289f42009-09-09 15:08:12 +00001927
Hal Finkeld2208b52014-10-02 20:53:50 +00001928 if (WarnAboutSemanticsChange) {
1929 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
1930 << TheCall->getCallee()->getSourceRange();
1931 }
1932
Chris Lattner5b9241b2009-05-08 15:36:58 +00001933 // Get the decl for the concrete builtin from this, we can tell what the
1934 // concrete integer type we should convert to is.
1935 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1936 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001937 FunctionDecl *NewBuiltinDecl;
1938 if (NewBuiltinID == BuiltinID)
1939 NewBuiltinDecl = FDecl;
1940 else {
1941 // Perform builtin lookup to avoid redeclaring it.
1942 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1943 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1944 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1945 assert(Res.getFoundDecl());
1946 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00001947 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001948 return ExprError();
1949 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001950
John McCallcf142162010-08-07 06:22:56 +00001951 // The first argument --- the pointer --- has a fixed type; we
1952 // deduce the types of the rest of the arguments accordingly. Walk
1953 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001954 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001955 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001956
Chris Lattnerdc046542009-05-08 06:58:22 +00001957 // GCC does an implicit conversion to the pointer or integer ValType. This
1958 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001959 // Initialize the argument.
1960 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1961 ValType, /*consume*/ false);
1962 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001963 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001964 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001965
Chris Lattnerdc046542009-05-08 06:58:22 +00001966 // Okay, we have something that *can* be converted to the right type. Check
1967 // to see if there is a potentially weird extension going on here. This can
1968 // happen when you do an atomic operation on something like an char* and
1969 // pass in 42. The 42 gets converted to char. This is even more strange
1970 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001971 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001972 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00001973 }
Mike Stump11289f42009-09-09 15:08:12 +00001974
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001975 ASTContext& Context = this->getASTContext();
1976
1977 // Create a new DeclRefExpr to refer to the new decl.
1978 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1979 Context,
1980 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001981 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001982 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001983 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001984 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001985 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001986 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001987
Chris Lattnerdc046542009-05-08 06:58:22 +00001988 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001989 // FIXME: This loses syntactic information.
1990 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1991 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1992 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001993 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00001994
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001995 // Change the result type of the call to match the original value type. This
1996 // is arbitrary, but the codegen for these builtins ins design to handle it
1997 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001998 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001999
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002000 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002001}
2002
Chris Lattner6436fb62009-02-18 06:01:06 +00002003/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002004/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002005/// Note: It might also make sense to do the UTF-16 conversion here (would
2006/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002007bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002008 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002009 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2010
Douglas Gregorfb65e592011-07-27 05:40:30 +00002011 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002012 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2013 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002014 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002015 }
Mike Stump11289f42009-09-09 15:08:12 +00002016
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002017 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002018 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002019 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002020 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002021 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002022 UTF16 *ToPtr = &ToBuf[0];
2023
2024 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2025 &ToPtr, ToPtr + NumBytes,
2026 strictConversion);
2027 // Check for conversion failure.
2028 if (Result != conversionOK)
2029 Diag(Arg->getLocStart(),
2030 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2031 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002032 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002033}
2034
Chris Lattnere202e6a2007-12-20 00:05:45 +00002035/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
2036/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00002037bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2038 Expr *Fn = TheCall->getCallee();
2039 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002040 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002041 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002042 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2043 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002044 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002045 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002046 return true;
2047 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002048
2049 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002050 return Diag(TheCall->getLocEnd(),
2051 diag::err_typecheck_call_too_few_args_at_least)
2052 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002053 }
2054
John McCall29ad95b2011-08-27 01:09:30 +00002055 // Type-check the first argument normally.
2056 if (checkBuiltinArgument(*this, TheCall, 0))
2057 return true;
2058
Chris Lattnere202e6a2007-12-20 00:05:45 +00002059 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002060 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002061 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002062 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002063 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002064 else if (FunctionDecl *FD = getCurFunctionDecl())
2065 isVariadic = FD->isVariadic();
2066 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002067 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002068
Chris Lattnere202e6a2007-12-20 00:05:45 +00002069 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002070 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2071 return true;
2072 }
Mike Stump11289f42009-09-09 15:08:12 +00002073
Chris Lattner43be2e62007-12-19 23:59:04 +00002074 // Verify that the second argument to the builtin is the last argument of the
2075 // current function or method.
2076 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002077 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002078
Nico Weber9eea7642013-05-24 23:31:57 +00002079 // These are valid if SecondArgIsLastNamedArgument is false after the next
2080 // block.
2081 QualType Type;
2082 SourceLocation ParamLoc;
2083
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002084 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2085 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002086 // FIXME: This isn't correct for methods (results in bogus warning).
2087 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002088 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002089 if (CurBlock)
2090 LastArg = *(CurBlock->TheDecl->param_end()-1);
2091 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002092 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002093 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002094 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002095 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002096
2097 Type = PV->getType();
2098 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002099 }
2100 }
Mike Stump11289f42009-09-09 15:08:12 +00002101
Chris Lattner43be2e62007-12-19 23:59:04 +00002102 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002103 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002104 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002105 else if (Type->isReferenceType()) {
2106 Diag(Arg->getLocStart(),
2107 diag::warn_va_start_of_reference_type_is_undefined);
2108 Diag(ParamLoc, diag::note_parameter_type) << Type;
2109 }
2110
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002111 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002112 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002113}
Chris Lattner43be2e62007-12-19 23:59:04 +00002114
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002115bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2116 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2117 // const char *named_addr);
2118
2119 Expr *Func = Call->getCallee();
2120
2121 if (Call->getNumArgs() < 3)
2122 return Diag(Call->getLocEnd(),
2123 diag::err_typecheck_call_too_few_args_at_least)
2124 << 0 /*function call*/ << 3 << Call->getNumArgs();
2125
2126 // Determine whether the current function is variadic or not.
2127 bool IsVariadic;
2128 if (BlockScopeInfo *CurBlock = getCurBlock())
2129 IsVariadic = CurBlock->TheDecl->isVariadic();
2130 else if (FunctionDecl *FD = getCurFunctionDecl())
2131 IsVariadic = FD->isVariadic();
2132 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2133 IsVariadic = MD->isVariadic();
2134 else
2135 llvm_unreachable("unexpected statement type");
2136
2137 if (!IsVariadic) {
2138 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2139 return true;
2140 }
2141
2142 // Type-check the first argument normally.
2143 if (checkBuiltinArgument(*this, Call, 0))
2144 return true;
2145
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002146 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002147 unsigned ArgNo;
2148 QualType Type;
2149 } ArgumentTypes[] = {
2150 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2151 { 2, Context.getSizeType() },
2152 };
2153
2154 for (const auto &AT : ArgumentTypes) {
2155 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2156 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2157 continue;
2158 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2159 << Arg->getType() << AT.Type << 1 /* different class */
2160 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2161 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2162 }
2163
2164 return false;
2165}
2166
Chris Lattner2da14fb2007-12-20 00:26:33 +00002167/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2168/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002169bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2170 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002171 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002172 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002173 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002174 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002175 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002176 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002177 << SourceRange(TheCall->getArg(2)->getLocStart(),
2178 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002179
John Wiegley01296292011-04-08 18:41:53 +00002180 ExprResult OrigArg0 = TheCall->getArg(0);
2181 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002182
Chris Lattner2da14fb2007-12-20 00:26:33 +00002183 // Do standard promotions between the two arguments, returning their common
2184 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002185 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002186 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2187 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002188
2189 // Make sure any conversions are pushed back into the call; this is
2190 // type safe since unordered compare builtins are declared as "_Bool
2191 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002192 TheCall->setArg(0, OrigArg0.get());
2193 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002194
John Wiegley01296292011-04-08 18:41:53 +00002195 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002196 return false;
2197
Chris Lattner2da14fb2007-12-20 00:26:33 +00002198 // If the common type isn't a real floating type, then the arguments were
2199 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002200 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002201 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002202 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002203 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2204 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002205
Chris Lattner2da14fb2007-12-20 00:26:33 +00002206 return false;
2207}
2208
Benjamin Kramer634fc102010-02-15 22:42:31 +00002209/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2210/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002211/// to check everything. We expect the last argument to be a floating point
2212/// value.
2213bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2214 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002215 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002216 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002217 if (TheCall->getNumArgs() > NumArgs)
2218 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002219 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002220 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002221 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002222 (*(TheCall->arg_end()-1))->getLocEnd());
2223
Benjamin Kramer64aae502010-02-16 10:07:31 +00002224 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002225
Eli Friedman7e4faac2009-08-31 20:06:00 +00002226 if (OrigArg->isTypeDependent())
2227 return false;
2228
Chris Lattner68784ef2010-05-06 05:50:07 +00002229 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002230 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002231 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002232 diag::err_typecheck_call_invalid_unary_fp)
2233 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002234
Chris Lattner68784ef2010-05-06 05:50:07 +00002235 // If this is an implicit conversion from float -> double, remove it.
2236 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2237 Expr *CastArg = Cast->getSubExpr();
2238 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2239 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2240 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002241 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002242 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002243 }
2244 }
2245
Eli Friedman7e4faac2009-08-31 20:06:00 +00002246 return false;
2247}
2248
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002249/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2250// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002251ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002252 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002253 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002254 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002255 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2256 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002257
Nate Begemana0110022010-06-08 00:16:34 +00002258 // Determine which of the following types of shufflevector we're checking:
2259 // 1) unary, vector mask: (lhs, mask)
2260 // 2) binary, vector mask: (lhs, rhs, mask)
2261 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2262 QualType resType = TheCall->getArg(0)->getType();
2263 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002264
Douglas Gregorc25f7662009-05-19 22:10:17 +00002265 if (!TheCall->getArg(0)->isTypeDependent() &&
2266 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002267 QualType LHSType = TheCall->getArg(0)->getType();
2268 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002269
Craig Topperbaca3892013-07-29 06:47:04 +00002270 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2271 return ExprError(Diag(TheCall->getLocStart(),
2272 diag::err_shufflevector_non_vector)
2273 << SourceRange(TheCall->getArg(0)->getLocStart(),
2274 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002275
Nate Begemana0110022010-06-08 00:16:34 +00002276 numElements = LHSType->getAs<VectorType>()->getNumElements();
2277 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002278
Nate Begemana0110022010-06-08 00:16:34 +00002279 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2280 // with mask. If so, verify that RHS is an integer vector type with the
2281 // same number of elts as lhs.
2282 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002283 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002284 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002285 return ExprError(Diag(TheCall->getLocStart(),
2286 diag::err_shufflevector_incompatible_vector)
2287 << SourceRange(TheCall->getArg(1)->getLocStart(),
2288 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002289 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002290 return ExprError(Diag(TheCall->getLocStart(),
2291 diag::err_shufflevector_incompatible_vector)
2292 << SourceRange(TheCall->getArg(0)->getLocStart(),
2293 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002294 } else if (numElements != numResElements) {
2295 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002296 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002297 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002298 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002299 }
2300
2301 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002302 if (TheCall->getArg(i)->isTypeDependent() ||
2303 TheCall->getArg(i)->isValueDependent())
2304 continue;
2305
Nate Begemana0110022010-06-08 00:16:34 +00002306 llvm::APSInt Result(32);
2307 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2308 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002309 diag::err_shufflevector_nonconstant_argument)
2310 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002311
Craig Topper50ad5b72013-08-03 17:40:38 +00002312 // Allow -1 which will be translated to undef in the IR.
2313 if (Result.isSigned() && Result.isAllOnesValue())
2314 continue;
2315
Chris Lattner7ab824e2008-08-10 02:05:13 +00002316 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002317 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002318 diag::err_shufflevector_argument_too_large)
2319 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002320 }
2321
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002322 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002323
Chris Lattner7ab824e2008-08-10 02:05:13 +00002324 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002325 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002326 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002327 }
2328
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002329 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2330 TheCall->getCallee()->getLocStart(),
2331 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002332}
Chris Lattner43be2e62007-12-19 23:59:04 +00002333
Hal Finkelc4d7c822013-09-18 03:29:45 +00002334/// SemaConvertVectorExpr - Handle __builtin_convertvector
2335ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2336 SourceLocation BuiltinLoc,
2337 SourceLocation RParenLoc) {
2338 ExprValueKind VK = VK_RValue;
2339 ExprObjectKind OK = OK_Ordinary;
2340 QualType DstTy = TInfo->getType();
2341 QualType SrcTy = E->getType();
2342
2343 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2344 return ExprError(Diag(BuiltinLoc,
2345 diag::err_convertvector_non_vector)
2346 << E->getSourceRange());
2347 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2348 return ExprError(Diag(BuiltinLoc,
2349 diag::err_convertvector_non_vector_type));
2350
2351 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2352 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2353 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2354 if (SrcElts != DstElts)
2355 return ExprError(Diag(BuiltinLoc,
2356 diag::err_convertvector_incompatible_vector)
2357 << E->getSourceRange());
2358 }
2359
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002360 return new (Context)
2361 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002362}
2363
Daniel Dunbarb7257262008-07-21 22:59:13 +00002364/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2365// This is declared to take (const void*, ...) and can take two
2366// optional constant int args.
2367bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002368 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002369
Chris Lattner3b054132008-11-19 05:08:23 +00002370 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002371 return Diag(TheCall->getLocEnd(),
2372 diag::err_typecheck_call_too_many_args_at_most)
2373 << 0 /*function call*/ << 3 << NumArgs
2374 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002375
2376 // Argument 0 is checked for us and the remaining arguments must be
2377 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002378 for (unsigned i = 1; i != NumArgs; ++i)
2379 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002380 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002381
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002382 return false;
2383}
2384
Hal Finkelf0417332014-07-17 14:25:55 +00002385/// SemaBuiltinAssume - Handle __assume (MS Extension).
2386// __assume does not evaluate its arguments, and should warn if its argument
2387// has side effects.
2388bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2389 Expr *Arg = TheCall->getArg(0);
2390 if (Arg->isInstantiationDependent()) return false;
2391
2392 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00002393 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002394 << Arg->getSourceRange()
2395 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2396
2397 return false;
2398}
2399
2400/// Handle __builtin_assume_aligned. This is declared
2401/// as (const void*, size_t, ...) and can take one optional constant int arg.
2402bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2403 unsigned NumArgs = TheCall->getNumArgs();
2404
2405 if (NumArgs > 3)
2406 return Diag(TheCall->getLocEnd(),
2407 diag::err_typecheck_call_too_many_args_at_most)
2408 << 0 /*function call*/ << 3 << NumArgs
2409 << TheCall->getSourceRange();
2410
2411 // The alignment must be a constant integer.
2412 Expr *Arg = TheCall->getArg(1);
2413
2414 // We can't check the value of a dependent argument.
2415 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2416 llvm::APSInt Result;
2417 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2418 return true;
2419
2420 if (!Result.isPowerOf2())
2421 return Diag(TheCall->getLocStart(),
2422 diag::err_alignment_not_power_of_two)
2423 << Arg->getSourceRange();
2424 }
2425
2426 if (NumArgs > 2) {
2427 ExprResult Arg(TheCall->getArg(2));
2428 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2429 Context.getSizeType(), false);
2430 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2431 if (Arg.isInvalid()) return true;
2432 TheCall->setArg(2, Arg.get());
2433 }
Hal Finkelf0417332014-07-17 14:25:55 +00002434
2435 return false;
2436}
2437
Eric Christopher8d0c6212010-04-17 02:26:23 +00002438/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2439/// TheCall is a constant expression.
2440bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2441 llvm::APSInt &Result) {
2442 Expr *Arg = TheCall->getArg(ArgNum);
2443 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2444 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2445
2446 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2447
2448 if (!Arg->isIntegerConstantExpr(Result, Context))
2449 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002450 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002451
Chris Lattnerd545ad12009-09-23 06:06:36 +00002452 return false;
2453}
2454
Richard Sandiford28940af2014-04-16 08:47:51 +00002455/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2456/// TheCall is a constant expression in the range [Low, High].
2457bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2458 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002459 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002460
2461 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002462 Expr *Arg = TheCall->getArg(ArgNum);
2463 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002464 return false;
2465
Eric Christopher8d0c6212010-04-17 02:26:23 +00002466 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002467 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002468 return true;
2469
Richard Sandiford28940af2014-04-16 08:47:51 +00002470 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002471 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002472 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002473
2474 return false;
2475}
2476
Eli Friedmanc97d0142009-05-03 06:04:26 +00002477/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002478/// This checks that the target supports __builtin_longjmp and
2479/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002480bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002481 if (!Context.getTargetInfo().hasSjLjLowering())
2482 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
2483 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2484
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002485 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002486 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002487
Eric Christopher8d0c6212010-04-17 02:26:23 +00002488 // TODO: This is less than ideal. Overload this to take a value.
2489 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2490 return true;
2491
2492 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002493 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2494 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2495
2496 return false;
2497}
2498
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002499
2500/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
2501/// This checks that the target supports __builtin_setjmp.
2502bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
2503 if (!Context.getTargetInfo().hasSjLjLowering())
2504 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
2505 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2506 return false;
2507}
2508
Richard Smithd7293d72013-08-05 18:49:43 +00002509namespace {
2510enum StringLiteralCheckType {
2511 SLCT_NotALiteral,
2512 SLCT_UncheckedLiteral,
2513 SLCT_CheckedLiteral
2514};
2515}
2516
Richard Smith55ce3522012-06-25 20:30:08 +00002517// Determine if an expression is a string literal or constant string.
2518// If this function returns false on the arguments to a function expecting a
2519// format string, we will usually need to emit a warning.
2520// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002521static StringLiteralCheckType
2522checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2523 bool HasVAListArg, unsigned format_idx,
2524 unsigned firstDataArg, Sema::FormatStringType Type,
2525 Sema::VariadicCallType CallType, bool InFunctionCall,
2526 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002527 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002528 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002529 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002530
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002531 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002532
Richard Smithd7293d72013-08-05 18:49:43 +00002533 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002534 // Technically -Wformat-nonliteral does not warn about this case.
2535 // The behavior of printf and friends in this case is implementation
2536 // dependent. Ideally if the format string cannot be null then
2537 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002538 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002539
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002540 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002541 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002542 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002543 // The expression is a literal if both sub-expressions were, and it was
2544 // completely checked only if both sub-expressions were checked.
2545 const AbstractConditionalOperator *C =
2546 cast<AbstractConditionalOperator>(E);
2547 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002548 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002549 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002550 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002551 if (Left == SLCT_NotALiteral)
2552 return SLCT_NotALiteral;
2553 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002554 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002555 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002556 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002557 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002558 }
2559
2560 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002561 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2562 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002563 }
2564
John McCallc07a0c72011-02-17 10:25:35 +00002565 case Stmt::OpaqueValueExprClass:
2566 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2567 E = src;
2568 goto tryAgain;
2569 }
Richard Smith55ce3522012-06-25 20:30:08 +00002570 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002571
Ted Kremeneka8890832011-02-24 23:03:04 +00002572 case Stmt::PredefinedExprClass:
2573 // While __func__, etc., are technically not string literals, they
2574 // cannot contain format specifiers and thus are not a security
2575 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002576 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002577
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002578 case Stmt::DeclRefExprClass: {
2579 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002580
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002581 // As an exception, do not flag errors for variables binding to
2582 // const string literals.
2583 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2584 bool isConstant = false;
2585 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002586
Richard Smithd7293d72013-08-05 18:49:43 +00002587 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2588 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002589 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002590 isConstant = T.isConstant(S.Context) &&
2591 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002592 } else if (T->isObjCObjectPointerType()) {
2593 // In ObjC, there is usually no "const ObjectPointer" type,
2594 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002595 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002596 }
Mike Stump11289f42009-09-09 15:08:12 +00002597
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002598 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002599 if (const Expr *Init = VD->getAnyInitializer()) {
2600 // Look through initializers like const char c[] = { "foo" }
2601 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2602 if (InitList->isStringLiteralInit())
2603 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2604 }
Richard Smithd7293d72013-08-05 18:49:43 +00002605 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002606 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002607 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002608 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002609 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002610 }
Mike Stump11289f42009-09-09 15:08:12 +00002611
Anders Carlssonb012ca92009-06-28 19:55:58 +00002612 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2613 // special check to see if the format string is a function parameter
2614 // of the function calling the printf function. If the function
2615 // has an attribute indicating it is a printf-like function, then we
2616 // should suppress warnings concerning non-literals being used in a call
2617 // to a vprintf function. For example:
2618 //
2619 // void
2620 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2621 // va_list ap;
2622 // va_start(ap, fmt);
2623 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2624 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002625 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002626 if (HasVAListArg) {
2627 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2628 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2629 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002630 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002631 // adjust for implicit parameter
2632 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2633 if (MD->isInstance())
2634 ++PVIndex;
2635 // We also check if the formats are compatible.
2636 // We can't pass a 'scanf' string to a 'printf' function.
2637 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002638 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002639 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002640 }
2641 }
2642 }
2643 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002644 }
Mike Stump11289f42009-09-09 15:08:12 +00002645
Richard Smith55ce3522012-06-25 20:30:08 +00002646 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002647 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002648
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002649 case Stmt::CallExprClass:
2650 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002651 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002652 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2653 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2654 unsigned ArgIndex = FA->getFormatIdx();
2655 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2656 if (MD->isInstance())
2657 --ArgIndex;
2658 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002659
Richard Smithd7293d72013-08-05 18:49:43 +00002660 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002661 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002662 Type, CallType, InFunctionCall,
2663 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002664 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2665 unsigned BuiltinID = FD->getBuiltinID();
2666 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2667 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2668 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002669 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002670 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002671 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002672 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002673 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002674 }
2675 }
Mike Stump11289f42009-09-09 15:08:12 +00002676
Richard Smith55ce3522012-06-25 20:30:08 +00002677 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002678 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002679 case Stmt::ObjCStringLiteralClass:
2680 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002681 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002682
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002683 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002684 StrE = ObjCFExpr->getString();
2685 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002686 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002687
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002688 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002689 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2690 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002691 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002692 }
Mike Stump11289f42009-09-09 15:08:12 +00002693
Richard Smith55ce3522012-06-25 20:30:08 +00002694 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002695 }
Mike Stump11289f42009-09-09 15:08:12 +00002696
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002697 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002698 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002699 }
2700}
2701
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002702Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002703 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002704 .Case("scanf", FST_Scanf)
2705 .Cases("printf", "printf0", FST_Printf)
2706 .Cases("NSString", "CFString", FST_NSString)
2707 .Case("strftime", FST_Strftime)
2708 .Case("strfmon", FST_Strfmon)
2709 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00002710 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00002711 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002712 .Default(FST_Unknown);
2713}
2714
Jordan Rose3e0ec582012-07-19 18:10:23 +00002715/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002716/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002717/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002718bool Sema::CheckFormatArguments(const FormatAttr *Format,
2719 ArrayRef<const Expr *> Args,
2720 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002721 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002722 SourceLocation Loc, SourceRange Range,
2723 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002724 FormatStringInfo FSI;
2725 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002726 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002727 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002728 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002729 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002730}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002731
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002732bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002733 bool HasVAListArg, unsigned format_idx,
2734 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002735 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002736 SourceLocation Loc, SourceRange Range,
2737 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002738 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002739 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002740 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002741 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002742 }
Mike Stump11289f42009-09-09 15:08:12 +00002743
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002744 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002745
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002746 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002747 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002748 // Dynamically generated format strings are difficult to
2749 // automatically vet at compile time. Requiring that format strings
2750 // are string literals: (1) permits the checking of format strings by
2751 // the compiler and thereby (2) can practically remove the source of
2752 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002753
Mike Stump11289f42009-09-09 15:08:12 +00002754 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002755 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002756 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002757 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002758 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002759 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2760 format_idx, firstDataArg, Type, CallType,
2761 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002762 if (CT != SLCT_NotALiteral)
2763 // Literal format string found, check done!
2764 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002765
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002766 // Strftime is particular as it always uses a single 'time' argument,
2767 // so it is safe to pass a non-literal string.
2768 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002769 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002770
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002771 // Do not emit diag when the string param is a macro expansion and the
2772 // format is either NSString or CFString. This is a hack to prevent
2773 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2774 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002775 if (Type == FST_NSString &&
2776 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002777 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002778
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002779 // If there are no arguments specified, warn with -Wformat-security, otherwise
2780 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002781 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002782 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002783 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002784 << OrigFormatExpr->getSourceRange();
2785 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002786 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002787 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002788 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002789 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002790}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002791
Ted Kremenekab278de2010-01-28 23:39:18 +00002792namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002793class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2794protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002795 Sema &S;
2796 const StringLiteral *FExpr;
2797 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002798 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002799 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002800 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002801 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002802 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002803 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002804 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002805 bool usesPositionalArgs;
2806 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002807 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002808 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002809 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002810public:
Ted Kremenek02087932010-07-16 02:11:22 +00002811 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002812 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002813 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002814 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002815 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002816 Sema::VariadicCallType callType,
2817 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002818 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002819 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2820 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002821 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002822 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002823 inFunctionCall(inFunctionCall), CallType(callType),
2824 CheckedVarArgs(CheckedVarArgs) {
2825 CoveredArgs.resize(numDataArgs);
2826 CoveredArgs.reset();
2827 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002828
Ted Kremenek019d2242010-01-29 01:50:07 +00002829 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002830
Ted Kremenek02087932010-07-16 02:11:22 +00002831 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002832 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002833
Jordan Rose92303592012-09-08 04:00:03 +00002834 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002835 const analyze_format_string::FormatSpecifier &FS,
2836 const analyze_format_string::ConversionSpecifier &CS,
2837 const char *startSpecifier, unsigned specifierLen,
2838 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002839
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002840 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002841 const analyze_format_string::FormatSpecifier &FS,
2842 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002843
2844 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002845 const analyze_format_string::ConversionSpecifier &CS,
2846 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002847
Craig Toppere14c0f82014-03-12 04:55:44 +00002848 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002849
Craig Toppere14c0f82014-03-12 04:55:44 +00002850 void HandleInvalidPosition(const char *startSpecifier,
2851 unsigned specifierLen,
2852 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002853
Craig Toppere14c0f82014-03-12 04:55:44 +00002854 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002855
Craig Toppere14c0f82014-03-12 04:55:44 +00002856 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002857
Richard Trieu03cf7b72011-10-28 00:41:25 +00002858 template <typename Range>
2859 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2860 const Expr *ArgumentExpr,
2861 PartialDiagnostic PDiag,
2862 SourceLocation StringLoc,
2863 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002864 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002865
Ted Kremenek02087932010-07-16 02:11:22 +00002866protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002867 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2868 const char *startSpec,
2869 unsigned specifierLen,
2870 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002871
2872 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2873 const char *startSpec,
2874 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002875
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002876 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002877 CharSourceRange getSpecifierRange(const char *startSpecifier,
2878 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002879 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002880
Ted Kremenek5739de72010-01-29 01:06:55 +00002881 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002882
2883 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2884 const analyze_format_string::ConversionSpecifier &CS,
2885 const char *startSpecifier, unsigned specifierLen,
2886 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002887
2888 template <typename Range>
2889 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2890 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002891 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002892};
2893}
2894
Ted Kremenek02087932010-07-16 02:11:22 +00002895SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002896 return OrigFormatExpr->getSourceRange();
2897}
2898
Ted Kremenek02087932010-07-16 02:11:22 +00002899CharSourceRange CheckFormatHandler::
2900getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002901 SourceLocation Start = getLocationOfByte(startSpecifier);
2902 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2903
2904 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002905 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002906
2907 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002908}
2909
Ted Kremenek02087932010-07-16 02:11:22 +00002910SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002911 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002912}
2913
Ted Kremenek02087932010-07-16 02:11:22 +00002914void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2915 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002916 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2917 getLocationOfByte(startSpecifier),
2918 /*IsStringLocation*/true,
2919 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002920}
2921
Jordan Rose92303592012-09-08 04:00:03 +00002922void CheckFormatHandler::HandleInvalidLengthModifier(
2923 const analyze_format_string::FormatSpecifier &FS,
2924 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002925 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002926 using namespace analyze_format_string;
2927
2928 const LengthModifier &LM = FS.getLengthModifier();
2929 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2930
2931 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002932 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002933 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002934 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002935 getLocationOfByte(LM.getStart()),
2936 /*IsStringLocation*/true,
2937 getSpecifierRange(startSpecifier, specifierLen));
2938
2939 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2940 << FixedLM->toString()
2941 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2942
2943 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002944 FixItHint Hint;
2945 if (DiagID == diag::warn_format_nonsensical_length)
2946 Hint = FixItHint::CreateRemoval(LMRange);
2947
2948 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002949 getLocationOfByte(LM.getStart()),
2950 /*IsStringLocation*/true,
2951 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002952 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002953 }
2954}
2955
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002956void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002957 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002958 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002959 using namespace analyze_format_string;
2960
2961 const LengthModifier &LM = FS.getLengthModifier();
2962 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2963
2964 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002965 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002966 if (FixedLM) {
2967 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2968 << LM.toString() << 0,
2969 getLocationOfByte(LM.getStart()),
2970 /*IsStringLocation*/true,
2971 getSpecifierRange(startSpecifier, specifierLen));
2972
2973 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2974 << FixedLM->toString()
2975 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2976
2977 } else {
2978 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2979 << LM.toString() << 0,
2980 getLocationOfByte(LM.getStart()),
2981 /*IsStringLocation*/true,
2982 getSpecifierRange(startSpecifier, specifierLen));
2983 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002984}
2985
2986void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2987 const analyze_format_string::ConversionSpecifier &CS,
2988 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002989 using namespace analyze_format_string;
2990
2991 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002992 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002993 if (FixedCS) {
2994 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2995 << CS.toString() << /*conversion specifier*/1,
2996 getLocationOfByte(CS.getStart()),
2997 /*IsStringLocation*/true,
2998 getSpecifierRange(startSpecifier, specifierLen));
2999
3000 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3001 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3002 << FixedCS->toString()
3003 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3004 } else {
3005 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3006 << CS.toString() << /*conversion specifier*/1,
3007 getLocationOfByte(CS.getStart()),
3008 /*IsStringLocation*/true,
3009 getSpecifierRange(startSpecifier, specifierLen));
3010 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003011}
3012
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003013void CheckFormatHandler::HandlePosition(const char *startPos,
3014 unsigned posLen) {
3015 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3016 getLocationOfByte(startPos),
3017 /*IsStringLocation*/true,
3018 getSpecifierRange(startPos, posLen));
3019}
3020
Ted Kremenekd1668192010-02-27 01:41:03 +00003021void
Ted Kremenek02087932010-07-16 02:11:22 +00003022CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3023 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003024 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3025 << (unsigned) p,
3026 getLocationOfByte(startPos), /*IsStringLocation*/true,
3027 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003028}
3029
Ted Kremenek02087932010-07-16 02:11:22 +00003030void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003031 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003032 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3033 getLocationOfByte(startPos),
3034 /*IsStringLocation*/true,
3035 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003036}
3037
Ted Kremenek02087932010-07-16 02:11:22 +00003038void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003039 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003040 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003041 EmitFormatDiagnostic(
3042 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3043 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3044 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003045 }
Ted Kremenek02087932010-07-16 02:11:22 +00003046}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003047
Jordan Rose58bbe422012-07-19 18:10:08 +00003048// Note that this may return NULL if there was an error parsing or building
3049// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003050const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003051 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003052}
3053
3054void CheckFormatHandler::DoneProcessing() {
3055 // Does the number of data arguments exceed the number of
3056 // format conversions in the format string?
3057 if (!HasVAListArg) {
3058 // Find any arguments that weren't covered.
3059 CoveredArgs.flip();
3060 signed notCoveredArg = CoveredArgs.find_first();
3061 if (notCoveredArg >= 0) {
3062 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00003063 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3064 SourceLocation Loc = E->getLocStart();
3065 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3066 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3067 Loc, /*IsStringLocation*/false,
3068 getFormatStringRange());
3069 }
Bob Wilson23cd4342012-05-03 19:47:19 +00003070 }
Ted Kremenek02087932010-07-16 02:11:22 +00003071 }
3072 }
3073}
3074
Ted Kremenekce815422010-07-19 21:25:57 +00003075bool
3076CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3077 SourceLocation Loc,
3078 const char *startSpec,
3079 unsigned specifierLen,
3080 const char *csStart,
3081 unsigned csLen) {
3082
3083 bool keepGoing = true;
3084 if (argIndex < NumDataArgs) {
3085 // Consider the argument coverered, even though the specifier doesn't
3086 // make sense.
3087 CoveredArgs.set(argIndex);
3088 }
3089 else {
3090 // If argIndex exceeds the number of data arguments we
3091 // don't issue a warning because that is just a cascade of warnings (and
3092 // they may have intended '%%' anyway). We don't want to continue processing
3093 // the format string after this point, however, as we will like just get
3094 // gibberish when trying to match arguments.
3095 keepGoing = false;
3096 }
3097
Richard Trieu03cf7b72011-10-28 00:41:25 +00003098 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3099 << StringRef(csStart, csLen),
3100 Loc, /*IsStringLocation*/true,
3101 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003102
3103 return keepGoing;
3104}
3105
Richard Trieu03cf7b72011-10-28 00:41:25 +00003106void
3107CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3108 const char *startSpec,
3109 unsigned specifierLen) {
3110 EmitFormatDiagnostic(
3111 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3112 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3113}
3114
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003115bool
3116CheckFormatHandler::CheckNumArgs(
3117 const analyze_format_string::FormatSpecifier &FS,
3118 const analyze_format_string::ConversionSpecifier &CS,
3119 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3120
3121 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003122 PartialDiagnostic PDiag = FS.usesPositionalArg()
3123 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3124 << (argIndex+1) << NumDataArgs)
3125 : S.PDiag(diag::warn_printf_insufficient_data_args);
3126 EmitFormatDiagnostic(
3127 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3128 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003129 return false;
3130 }
3131 return true;
3132}
3133
Richard Trieu03cf7b72011-10-28 00:41:25 +00003134template<typename Range>
3135void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3136 SourceLocation Loc,
3137 bool IsStringLocation,
3138 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003139 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003140 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003141 Loc, IsStringLocation, StringRange, FixIt);
3142}
3143
3144/// \brief If the format string is not within the funcion call, emit a note
3145/// so that the function call and string are in diagnostic messages.
3146///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003147/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003148/// call and only one diagnostic message will be produced. Otherwise, an
3149/// extra note will be emitted pointing to location of the format string.
3150///
3151/// \param ArgumentExpr the expression that is passed as the format string
3152/// argument in the function call. Used for getting locations when two
3153/// diagnostics are emitted.
3154///
3155/// \param PDiag the callee should already have provided any strings for the
3156/// diagnostic message. This function only adds locations and fixits
3157/// to diagnostics.
3158///
3159/// \param Loc primary location for diagnostic. If two diagnostics are
3160/// required, one will be at Loc and a new SourceLocation will be created for
3161/// the other one.
3162///
3163/// \param IsStringLocation if true, Loc points to the format string should be
3164/// used for the note. Otherwise, Loc points to the argument list and will
3165/// be used with PDiag.
3166///
3167/// \param StringRange some or all of the string to highlight. This is
3168/// templated so it can accept either a CharSourceRange or a SourceRange.
3169///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003170/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003171template<typename Range>
3172void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3173 const Expr *ArgumentExpr,
3174 PartialDiagnostic PDiag,
3175 SourceLocation Loc,
3176 bool IsStringLocation,
3177 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003178 ArrayRef<FixItHint> FixIt) {
3179 if (InFunctionCall) {
3180 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3181 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003182 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00003183 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003184 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3185 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003186
3187 const Sema::SemaDiagnosticBuilder &Note =
3188 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3189 diag::note_format_string_defined);
3190
3191 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003192 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003193 }
3194}
3195
Ted Kremenek02087932010-07-16 02:11:22 +00003196//===--- CHECK: Printf format string checking ------------------------------===//
3197
3198namespace {
3199class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003200 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00003201public:
3202 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3203 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003204 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003205 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003206 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003207 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003208 Sema::VariadicCallType CallType,
3209 llvm::SmallBitVector &CheckedVarArgs)
3210 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3211 numDataArgs, beg, hasVAListArg, Args,
3212 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3213 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003214 {}
3215
Craig Toppere14c0f82014-03-12 04:55:44 +00003216
Ted Kremenek02087932010-07-16 02:11:22 +00003217 bool HandleInvalidPrintfConversionSpecifier(
3218 const analyze_printf::PrintfSpecifier &FS,
3219 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003220 unsigned specifierLen) override;
3221
Ted Kremenek02087932010-07-16 02:11:22 +00003222 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3223 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003224 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003225 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3226 const char *StartSpecifier,
3227 unsigned SpecifierLen,
3228 const Expr *E);
3229
Ted Kremenek02087932010-07-16 02:11:22 +00003230 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3231 const char *startSpecifier, unsigned specifierLen);
3232 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3233 const analyze_printf::OptionalAmount &Amt,
3234 unsigned type,
3235 const char *startSpecifier, unsigned specifierLen);
3236 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3237 const analyze_printf::OptionalFlag &flag,
3238 const char *startSpecifier, unsigned specifierLen);
3239 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3240 const analyze_printf::OptionalFlag &ignoredFlag,
3241 const analyze_printf::OptionalFlag &flag,
3242 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003243 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003244 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00003245
Ted Kremenek02087932010-07-16 02:11:22 +00003246};
3247}
3248
3249bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3250 const analyze_printf::PrintfSpecifier &FS,
3251 const char *startSpecifier,
3252 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003253 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003254 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003255
Ted Kremenekce815422010-07-19 21:25:57 +00003256 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3257 getLocationOfByte(CS.getStart()),
3258 startSpecifier, specifierLen,
3259 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003260}
3261
Ted Kremenek02087932010-07-16 02:11:22 +00003262bool CheckPrintfHandler::HandleAmount(
3263 const analyze_format_string::OptionalAmount &Amt,
3264 unsigned k, const char *startSpecifier,
3265 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003266
3267 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003268 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003269 unsigned argIndex = Amt.getArgIndex();
3270 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003271 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3272 << k,
3273 getLocationOfByte(Amt.getStart()),
3274 /*IsStringLocation*/true,
3275 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003276 // Don't do any more checking. We will just emit
3277 // spurious errors.
3278 return false;
3279 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003280
Ted Kremenek5739de72010-01-29 01:06:55 +00003281 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00003282 // Although not in conformance with C99, we also allow the argument to be
3283 // an 'unsigned int' as that is a reasonably safe case. GCC also
3284 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003285 CoveredArgs.set(argIndex);
3286 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003287 if (!Arg)
3288 return false;
3289
Ted Kremenek5739de72010-01-29 01:06:55 +00003290 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003291
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003292 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3293 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003294
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003295 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003296 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003297 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003298 << T << Arg->getSourceRange(),
3299 getLocationOfByte(Amt.getStart()),
3300 /*IsStringLocation*/true,
3301 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003302 // Don't do any more checking. We will just emit
3303 // spurious errors.
3304 return false;
3305 }
3306 }
3307 }
3308 return true;
3309}
Ted Kremenek5739de72010-01-29 01:06:55 +00003310
Tom Careb49ec692010-06-17 19:00:27 +00003311void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003312 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003313 const analyze_printf::OptionalAmount &Amt,
3314 unsigned type,
3315 const char *startSpecifier,
3316 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003317 const analyze_printf::PrintfConversionSpecifier &CS =
3318 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003319
Richard Trieu03cf7b72011-10-28 00:41:25 +00003320 FixItHint fixit =
3321 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3322 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3323 Amt.getConstantLength()))
3324 : FixItHint();
3325
3326 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3327 << type << CS.toString(),
3328 getLocationOfByte(Amt.getStart()),
3329 /*IsStringLocation*/true,
3330 getSpecifierRange(startSpecifier, specifierLen),
3331 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003332}
3333
Ted Kremenek02087932010-07-16 02:11:22 +00003334void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003335 const analyze_printf::OptionalFlag &flag,
3336 const char *startSpecifier,
3337 unsigned specifierLen) {
3338 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003339 const analyze_printf::PrintfConversionSpecifier &CS =
3340 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003341 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3342 << flag.toString() << CS.toString(),
3343 getLocationOfByte(flag.getPosition()),
3344 /*IsStringLocation*/true,
3345 getSpecifierRange(startSpecifier, specifierLen),
3346 FixItHint::CreateRemoval(
3347 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003348}
3349
3350void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003351 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003352 const analyze_printf::OptionalFlag &ignoredFlag,
3353 const analyze_printf::OptionalFlag &flag,
3354 const char *startSpecifier,
3355 unsigned specifierLen) {
3356 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003357 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3358 << ignoredFlag.toString() << flag.toString(),
3359 getLocationOfByte(ignoredFlag.getPosition()),
3360 /*IsStringLocation*/true,
3361 getSpecifierRange(startSpecifier, specifierLen),
3362 FixItHint::CreateRemoval(
3363 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003364}
3365
Richard Smith55ce3522012-06-25 20:30:08 +00003366// Determines if the specified is a C++ class or struct containing
3367// a member with the specified name and kind (e.g. a CXXMethodDecl named
3368// "c_str()").
3369template<typename MemberKind>
3370static llvm::SmallPtrSet<MemberKind*, 1>
3371CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3372 const RecordType *RT = Ty->getAs<RecordType>();
3373 llvm::SmallPtrSet<MemberKind*, 1> Results;
3374
3375 if (!RT)
3376 return Results;
3377 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003378 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003379 return Results;
3380
Alp Tokerb6cc5922014-05-03 03:45:55 +00003381 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003382 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003383 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003384
3385 // We just need to include all members of the right kind turned up by the
3386 // filter, at this point.
3387 if (S.LookupQualifiedName(R, RT->getDecl()))
3388 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3389 NamedDecl *decl = (*I)->getUnderlyingDecl();
3390 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3391 Results.insert(FK);
3392 }
3393 return Results;
3394}
3395
Richard Smith2868a732014-02-28 01:36:39 +00003396/// Check if we could call '.c_str()' on an object.
3397///
3398/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3399/// allow the call, or if it would be ambiguous).
3400bool Sema::hasCStrMethod(const Expr *E) {
3401 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3402 MethodSet Results =
3403 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3404 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3405 MI != ME; ++MI)
3406 if ((*MI)->getMinRequiredArguments() == 0)
3407 return true;
3408 return false;
3409}
3410
Richard Smith55ce3522012-06-25 20:30:08 +00003411// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003412// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003413// Returns true when a c_str() conversion method is found.
3414bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003415 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003416 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3417
3418 MethodSet Results =
3419 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3420
3421 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3422 MI != ME; ++MI) {
3423 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003424 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003425 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003426 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003427 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003428 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3429 << "c_str()"
3430 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3431 return true;
3432 }
3433 }
3434
3435 return false;
3436}
3437
Ted Kremenekab278de2010-01-28 23:39:18 +00003438bool
Ted Kremenek02087932010-07-16 02:11:22 +00003439CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003440 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003441 const char *startSpecifier,
3442 unsigned specifierLen) {
3443
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003444 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003445 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003446 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003447
Ted Kremenek6cd69422010-07-19 22:01:06 +00003448 if (FS.consumesDataArgument()) {
3449 if (atFirstArg) {
3450 atFirstArg = false;
3451 usesPositionalArgs = FS.usesPositionalArg();
3452 }
3453 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003454 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3455 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003456 return false;
3457 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003458 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003459
Ted Kremenekd1668192010-02-27 01:41:03 +00003460 // First check if the field width, precision, and conversion specifier
3461 // have matching data arguments.
3462 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3463 startSpecifier, specifierLen)) {
3464 return false;
3465 }
3466
3467 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3468 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003469 return false;
3470 }
3471
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003472 if (!CS.consumesDataArgument()) {
3473 // FIXME: Technically specifying a precision or field width here
3474 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003475 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003476 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003477
Ted Kremenek4a49d982010-02-26 19:18:41 +00003478 // Consume the argument.
3479 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003480 if (argIndex < NumDataArgs) {
3481 // The check to see if the argIndex is valid will come later.
3482 // We set the bit here because we may exit early from this
3483 // function if we encounter some other error.
3484 CoveredArgs.set(argIndex);
3485 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003486
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003487 // FreeBSD kernel extensions.
3488 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
3489 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
3490 // We need at least two arguments.
3491 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
3492 return false;
3493
3494 // Claim the second argument.
3495 CoveredArgs.set(argIndex + 1);
3496
3497 // Type check the first argument (int for %b, pointer for %D)
3498 const Expr *Ex = getDataArg(argIndex);
3499 const analyze_printf::ArgType &AT =
3500 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
3501 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
3502 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
3503 EmitFormatDiagnostic(
3504 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3505 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3506 << false << Ex->getSourceRange(),
3507 Ex->getLocStart(), /*IsStringLocation*/false,
3508 getSpecifierRange(startSpecifier, specifierLen));
3509
3510 // Type check the second argument (char * for both %b and %D)
3511 Ex = getDataArg(argIndex + 1);
3512 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
3513 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
3514 EmitFormatDiagnostic(
3515 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3516 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
3517 << false << Ex->getSourceRange(),
3518 Ex->getLocStart(), /*IsStringLocation*/false,
3519 getSpecifierRange(startSpecifier, specifierLen));
3520
3521 return true;
3522 }
3523
Ted Kremenek4a49d982010-02-26 19:18:41 +00003524 // Check for using an Objective-C specific conversion specifier
3525 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003526 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003527 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3528 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003529 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003530
Tom Careb49ec692010-06-17 19:00:27 +00003531 // Check for invalid use of field width
3532 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003533 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003534 startSpecifier, specifierLen);
3535 }
3536
3537 // Check for invalid use of precision
3538 if (!FS.hasValidPrecision()) {
3539 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3540 startSpecifier, specifierLen);
3541 }
3542
3543 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003544 if (!FS.hasValidThousandsGroupingPrefix())
3545 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003546 if (!FS.hasValidLeadingZeros())
3547 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3548 if (!FS.hasValidPlusPrefix())
3549 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003550 if (!FS.hasValidSpacePrefix())
3551 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003552 if (!FS.hasValidAlternativeForm())
3553 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3554 if (!FS.hasValidLeftJustified())
3555 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3556
3557 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003558 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3559 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3560 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003561 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3562 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3563 startSpecifier, specifierLen);
3564
3565 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003566 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003567 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3568 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003569 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003570 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003571 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003572 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3573 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003574
Jordan Rose92303592012-09-08 04:00:03 +00003575 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3576 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3577
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003578 // The remaining checks depend on the data arguments.
3579 if (HasVAListArg)
3580 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003581
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003582 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003583 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003584
Jordan Rose58bbe422012-07-19 18:10:08 +00003585 const Expr *Arg = getDataArg(argIndex);
3586 if (!Arg)
3587 return true;
3588
3589 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003590}
3591
Jordan Roseaee34382012-09-05 22:56:26 +00003592static bool requiresParensToAddCast(const Expr *E) {
3593 // FIXME: We should have a general way to reason about operator
3594 // precedence and whether parens are actually needed here.
3595 // Take care of a few common cases where they aren't.
3596 const Expr *Inside = E->IgnoreImpCasts();
3597 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3598 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3599
3600 switch (Inside->getStmtClass()) {
3601 case Stmt::ArraySubscriptExprClass:
3602 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003603 case Stmt::CharacterLiteralClass:
3604 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003605 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003606 case Stmt::FloatingLiteralClass:
3607 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003608 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003609 case Stmt::ObjCArrayLiteralClass:
3610 case Stmt::ObjCBoolLiteralExprClass:
3611 case Stmt::ObjCBoxedExprClass:
3612 case Stmt::ObjCDictionaryLiteralClass:
3613 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003614 case Stmt::ObjCIvarRefExprClass:
3615 case Stmt::ObjCMessageExprClass:
3616 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003617 case Stmt::ObjCStringLiteralClass:
3618 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003619 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003620 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003621 case Stmt::UnaryOperatorClass:
3622 return false;
3623 default:
3624 return true;
3625 }
3626}
3627
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003628static std::pair<QualType, StringRef>
3629shouldNotPrintDirectly(const ASTContext &Context,
3630 QualType IntendedTy,
3631 const Expr *E) {
3632 // Use a 'while' to peel off layers of typedefs.
3633 QualType TyTy = IntendedTy;
3634 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3635 StringRef Name = UserTy->getDecl()->getName();
3636 QualType CastTy = llvm::StringSwitch<QualType>(Name)
3637 .Case("NSInteger", Context.LongTy)
3638 .Case("NSUInteger", Context.UnsignedLongTy)
3639 .Case("SInt32", Context.IntTy)
3640 .Case("UInt32", Context.UnsignedIntTy)
3641 .Default(QualType());
3642
3643 if (!CastTy.isNull())
3644 return std::make_pair(CastTy, Name);
3645
3646 TyTy = UserTy->desugar();
3647 }
3648
3649 // Strip parens if necessary.
3650 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
3651 return shouldNotPrintDirectly(Context,
3652 PE->getSubExpr()->getType(),
3653 PE->getSubExpr());
3654
3655 // If this is a conditional expression, then its result type is constructed
3656 // via usual arithmetic conversions and thus there might be no necessary
3657 // typedef sugar there. Recurse to operands to check for NSInteger &
3658 // Co. usage condition.
3659 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3660 QualType TrueTy, FalseTy;
3661 StringRef TrueName, FalseName;
3662
3663 std::tie(TrueTy, TrueName) =
3664 shouldNotPrintDirectly(Context,
3665 CO->getTrueExpr()->getType(),
3666 CO->getTrueExpr());
3667 std::tie(FalseTy, FalseName) =
3668 shouldNotPrintDirectly(Context,
3669 CO->getFalseExpr()->getType(),
3670 CO->getFalseExpr());
3671
3672 if (TrueTy == FalseTy)
3673 return std::make_pair(TrueTy, TrueName);
3674 else if (TrueTy.isNull())
3675 return std::make_pair(FalseTy, FalseName);
3676 else if (FalseTy.isNull())
3677 return std::make_pair(TrueTy, TrueName);
3678 }
3679
3680 return std::make_pair(QualType(), StringRef());
3681}
3682
Richard Smith55ce3522012-06-25 20:30:08 +00003683bool
3684CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3685 const char *StartSpecifier,
3686 unsigned SpecifierLen,
3687 const Expr *E) {
3688 using namespace analyze_format_string;
3689 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003690 // Now type check the data expression that matches the
3691 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003692 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3693 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003694 if (!AT.isValid())
3695 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003696
Jordan Rose598ec092012-12-05 18:44:40 +00003697 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003698 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3699 ExprTy = TET->getUnderlyingExpr()->getType();
3700 }
3701
Seth Cantrellb4802962015-03-04 03:12:10 +00003702 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
3703
3704 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00003705 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00003706 }
Jordan Rose98709982012-06-04 22:48:57 +00003707
Jordan Rose22b74712012-09-05 22:56:19 +00003708 // Look through argument promotions for our error message's reported type.
3709 // This includes the integral and floating promotions, but excludes array
3710 // and function pointer decay; seeing that an argument intended to be a
3711 // string has type 'char [6]' is probably more confusing than 'char *'.
3712 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3713 if (ICE->getCastKind() == CK_IntegralCast ||
3714 ICE->getCastKind() == CK_FloatingCast) {
3715 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003716 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003717
3718 // Check if we didn't match because of an implicit cast from a 'char'
3719 // or 'short' to an 'int'. This is done because printf is a varargs
3720 // function.
3721 if (ICE->getType() == S.Context.IntTy ||
3722 ICE->getType() == S.Context.UnsignedIntTy) {
3723 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003724 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003725 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003726 }
Jordan Rose98709982012-06-04 22:48:57 +00003727 }
Jordan Rose598ec092012-12-05 18:44:40 +00003728 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3729 // Special case for 'a', which has type 'int' in C.
3730 // Note, however, that we do /not/ want to treat multibyte constants like
3731 // 'MooV' as characters! This form is deprecated but still exists.
3732 if (ExprTy == S.Context.IntTy)
3733 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3734 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003735 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003736
Jordan Rosebc53ed12014-05-31 04:12:14 +00003737 // Look through enums to their underlying type.
3738 bool IsEnum = false;
3739 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3740 ExprTy = EnumTy->getDecl()->getIntegerType();
3741 IsEnum = true;
3742 }
3743
Jordan Rose0e5badd2012-12-05 18:44:49 +00003744 // %C in an Objective-C context prints a unichar, not a wchar_t.
3745 // If the argument is an integer of some kind, believe the %C and suggest
3746 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003747 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003748 if (ObjCContext &&
3749 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3750 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3751 !ExprTy->isCharType()) {
3752 // 'unichar' is defined as a typedef of unsigned short, but we should
3753 // prefer using the typedef if it is visible.
3754 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003755
3756 // While we are here, check if the value is an IntegerLiteral that happens
3757 // to be within the valid range.
3758 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3759 const llvm::APInt &V = IL->getValue();
3760 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3761 return true;
3762 }
3763
Jordan Rose0e5badd2012-12-05 18:44:49 +00003764 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3765 Sema::LookupOrdinaryName);
3766 if (S.LookupName(Result, S.getCurScope())) {
3767 NamedDecl *ND = Result.getFoundDecl();
3768 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3769 if (TD->getUnderlyingType() == IntendedTy)
3770 IntendedTy = S.Context.getTypedefType(TD);
3771 }
3772 }
3773 }
3774
3775 // Special-case some of Darwin's platform-independence types by suggesting
3776 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003777 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00003778 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003779 QualType CastTy;
3780 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
3781 if (!CastTy.isNull()) {
3782 IntendedTy = CastTy;
3783 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00003784 }
3785 }
3786
Jordan Rose22b74712012-09-05 22:56:19 +00003787 // We may be able to offer a FixItHint if it is a supported type.
3788 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003789 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003790 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003791
Jordan Rose22b74712012-09-05 22:56:19 +00003792 if (success) {
3793 // Get the fix string from the fixed format specifier
3794 SmallString<16> buf;
3795 llvm::raw_svector_ostream os(buf);
3796 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003797
Jordan Roseaee34382012-09-05 22:56:26 +00003798 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3799
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003800 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00003801 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
3802 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
3803 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
3804 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00003805 // In this case, the specifier is wrong and should be changed to match
3806 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00003807 EmitFormatDiagnostic(S.PDiag(diag)
3808 << AT.getRepresentativeTypeName(S.Context)
3809 << IntendedTy << IsEnum << E->getSourceRange(),
3810 E->getLocStart(),
3811 /*IsStringLocation*/ false, SpecRange,
3812 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00003813
3814 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003815 // The canonical type for formatting this value is different from the
3816 // actual type of the expression. (This occurs, for example, with Darwin's
3817 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3818 // should be printed as 'long' for 64-bit compatibility.)
3819 // Rather than emitting a normal format/argument mismatch, we want to
3820 // add a cast to the recommended type (and correct the format string
3821 // if necessary).
3822 SmallString<16> CastBuf;
3823 llvm::raw_svector_ostream CastFix(CastBuf);
3824 CastFix << "(";
3825 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3826 CastFix << ")";
3827
3828 SmallVector<FixItHint,4> Hints;
3829 if (!AT.matchesType(S.Context, IntendedTy))
3830 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3831
3832 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3833 // If there's already a cast present, just replace it.
3834 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3835 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3836
3837 } else if (!requiresParensToAddCast(E)) {
3838 // If the expression has high enough precedence,
3839 // just write the C-style cast.
3840 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3841 CastFix.str()));
3842 } else {
3843 // Otherwise, add parens around the expression as well as the cast.
3844 CastFix << "(";
3845 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3846 CastFix.str()));
3847
Alp Tokerb6cc5922014-05-03 03:45:55 +00003848 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003849 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3850 }
3851
Jordan Rose0e5badd2012-12-05 18:44:49 +00003852 if (ShouldNotPrintDirectly) {
3853 // The expression has a type that should not be printed directly.
3854 // We extract the name from the typedef because we don't want to show
3855 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003856 StringRef Name;
3857 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
3858 Name = TypedefTy->getDecl()->getName();
3859 else
3860 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003861 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00003862 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003863 << E->getSourceRange(),
3864 E->getLocStart(), /*IsStringLocation=*/false,
3865 SpecRange, Hints);
3866 } else {
3867 // In this case, the expression could be printed using a different
3868 // specifier, but we've decided that the specifier is probably correct
3869 // and we should cast instead. Just use the normal warning message.
3870 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003871 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3872 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003873 << E->getSourceRange(),
3874 E->getLocStart(), /*IsStringLocation*/false,
3875 SpecRange, Hints);
3876 }
Jordan Roseaee34382012-09-05 22:56:26 +00003877 }
Jordan Rose22b74712012-09-05 22:56:19 +00003878 } else {
3879 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3880 SpecifierLen);
3881 // Since the warning for passing non-POD types to variadic functions
3882 // was deferred until now, we emit a warning for non-POD
3883 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003884 switch (S.isValidVarArgType(ExprTy)) {
3885 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00003886 case Sema::VAK_ValidInCXX11: {
3887 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
3888 if (match == analyze_printf::ArgType::NoMatchPedantic) {
3889 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
3890 }
Richard Smithd7293d72013-08-05 18:49:43 +00003891
Seth Cantrellb4802962015-03-04 03:12:10 +00003892 EmitFormatDiagnostic(
3893 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
3894 << IsEnum << CSR << E->getSourceRange(),
3895 E->getLocStart(), /*IsStringLocation*/ false, CSR);
3896 break;
3897 }
Richard Smithd7293d72013-08-05 18:49:43 +00003898 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00003899 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00003900 EmitFormatDiagnostic(
3901 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003902 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003903 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003904 << CallType
3905 << AT.getRepresentativeTypeName(S.Context)
3906 << CSR
3907 << E->getSourceRange(),
3908 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003909 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003910 break;
3911
3912 case Sema::VAK_Invalid:
3913 if (ExprTy->isObjCObjectType())
3914 EmitFormatDiagnostic(
3915 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3916 << S.getLangOpts().CPlusPlus11
3917 << ExprTy
3918 << CallType
3919 << AT.getRepresentativeTypeName(S.Context)
3920 << CSR
3921 << E->getSourceRange(),
3922 E->getLocStart(), /*IsStringLocation*/false, CSR);
3923 else
3924 // FIXME: If this is an initializer list, suggest removing the braces
3925 // or inserting a cast to the target type.
3926 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3927 << isa<InitListExpr>(E) << ExprTy << CallType
3928 << AT.getRepresentativeTypeName(S.Context)
3929 << E->getSourceRange();
3930 break;
3931 }
3932
3933 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3934 "format string specifier index out of range");
3935 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003936 }
3937
Ted Kremenekab278de2010-01-28 23:39:18 +00003938 return true;
3939}
3940
Ted Kremenek02087932010-07-16 02:11:22 +00003941//===--- CHECK: Scanf format string checking ------------------------------===//
3942
3943namespace {
3944class CheckScanfHandler : public CheckFormatHandler {
3945public:
3946 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3947 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003948 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003949 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003950 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003951 Sema::VariadicCallType CallType,
3952 llvm::SmallBitVector &CheckedVarArgs)
3953 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3954 numDataArgs, beg, hasVAListArg,
3955 Args, formatIdx, inFunctionCall, CallType,
3956 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003957 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003958
3959 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3960 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003961 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003962
3963 bool HandleInvalidScanfConversionSpecifier(
3964 const analyze_scanf::ScanfSpecifier &FS,
3965 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003966 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003967
Craig Toppere14c0f82014-03-12 04:55:44 +00003968 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003969};
Ted Kremenek019d2242010-01-29 01:50:07 +00003970}
Ted Kremenekab278de2010-01-28 23:39:18 +00003971
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003972void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3973 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003974 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3975 getLocationOfByte(end), /*IsStringLocation*/true,
3976 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003977}
3978
Ted Kremenekce815422010-07-19 21:25:57 +00003979bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3980 const analyze_scanf::ScanfSpecifier &FS,
3981 const char *startSpecifier,
3982 unsigned specifierLen) {
3983
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003984 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003985 FS.getConversionSpecifier();
3986
3987 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3988 getLocationOfByte(CS.getStart()),
3989 startSpecifier, specifierLen,
3990 CS.getStart(), CS.getLength());
3991}
3992
Ted Kremenek02087932010-07-16 02:11:22 +00003993bool CheckScanfHandler::HandleScanfSpecifier(
3994 const analyze_scanf::ScanfSpecifier &FS,
3995 const char *startSpecifier,
3996 unsigned specifierLen) {
3997
3998 using namespace analyze_scanf;
3999 using namespace analyze_format_string;
4000
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004001 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004002
Ted Kremenek6cd69422010-07-19 22:01:06 +00004003 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4004 // be used to decide if we are using positional arguments consistently.
4005 if (FS.consumesDataArgument()) {
4006 if (atFirstArg) {
4007 atFirstArg = false;
4008 usesPositionalArgs = FS.usesPositionalArg();
4009 }
4010 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004011 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4012 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004013 return false;
4014 }
Ted Kremenek02087932010-07-16 02:11:22 +00004015 }
4016
4017 // Check if the field with is non-zero.
4018 const OptionalAmount &Amt = FS.getFieldWidth();
4019 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4020 if (Amt.getConstantAmount() == 0) {
4021 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4022 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00004023 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4024 getLocationOfByte(Amt.getStart()),
4025 /*IsStringLocation*/true, R,
4026 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00004027 }
4028 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004029
Ted Kremenek02087932010-07-16 02:11:22 +00004030 if (!FS.consumesDataArgument()) {
4031 // FIXME: Technically specifying a precision or field width here
4032 // makes no sense. Worth issuing a warning at some point.
4033 return true;
4034 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004035
Ted Kremenek02087932010-07-16 02:11:22 +00004036 // Consume the argument.
4037 unsigned argIndex = FS.getArgIndex();
4038 if (argIndex < NumDataArgs) {
4039 // The check to see if the argIndex is valid will come later.
4040 // We set the bit here because we may exit early from this
4041 // function if we encounter some other error.
4042 CoveredArgs.set(argIndex);
4043 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004044
Ted Kremenek4407ea42010-07-20 20:04:47 +00004045 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004046 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004047 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4048 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004049 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004050 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004051 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004052 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4053 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004054
Jordan Rose92303592012-09-08 04:00:03 +00004055 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4056 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4057
Ted Kremenek02087932010-07-16 02:11:22 +00004058 // The remaining checks depend on the data arguments.
4059 if (HasVAListArg)
4060 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004061
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004062 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004063 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00004064
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004065 // Check that the argument type matches the format specifier.
4066 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004067 if (!Ex)
4068 return true;
4069
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004070 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00004071
4072 if (!AT.isValid()) {
4073 return true;
4074 }
4075
Seth Cantrellb4802962015-03-04 03:12:10 +00004076 analyze_format_string::ArgType::MatchKind match =
4077 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00004078 if (match == analyze_format_string::ArgType::Match) {
4079 return true;
4080 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004081
Seth Cantrell79340072015-03-04 05:58:08 +00004082 ScanfSpecifier fixedFS = FS;
4083 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4084 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004085
Seth Cantrell79340072015-03-04 05:58:08 +00004086 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4087 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4088 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4089 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004090
Seth Cantrell79340072015-03-04 05:58:08 +00004091 if (success) {
4092 // Get the fix string from the fixed format specifier.
4093 SmallString<128> buf;
4094 llvm::raw_svector_ostream os(buf);
4095 fixedFS.toString(os);
4096
4097 EmitFormatDiagnostic(
4098 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4099 << Ex->getType() << false << Ex->getSourceRange(),
4100 Ex->getLocStart(),
4101 /*IsStringLocation*/ false,
4102 getSpecifierRange(startSpecifier, specifierLen),
4103 FixItHint::CreateReplacement(
4104 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4105 } else {
4106 EmitFormatDiagnostic(S.PDiag(diag)
4107 << AT.getRepresentativeTypeName(S.Context)
4108 << Ex->getType() << false << Ex->getSourceRange(),
4109 Ex->getLocStart(),
4110 /*IsStringLocation*/ false,
4111 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004112 }
4113
Ted Kremenek02087932010-07-16 02:11:22 +00004114 return true;
4115}
4116
4117void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00004118 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004119 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004120 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004121 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00004122 bool inFunctionCall, VariadicCallType CallType,
4123 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004124
Ted Kremenekab278de2010-01-28 23:39:18 +00004125 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004126 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004127 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004128 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004129 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4130 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004131 return;
4132 }
Ted Kremenek02087932010-07-16 02:11:22 +00004133
Ted Kremenekab278de2010-01-28 23:39:18 +00004134 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004135 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004136 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004137 // Account for cases where the string literal is truncated in a declaration.
4138 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4139 assert(T && "String literal not of constant array type!");
4140 size_t TypeSize = T->getSize().getZExtValue();
4141 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004142 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004143
4144 // Emit a warning if the string literal is truncated and does not contain an
4145 // embedded null character.
4146 if (TypeSize <= StrRef.size() &&
4147 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4148 CheckFormatHandler::EmitFormatDiagnostic(
4149 *this, inFunctionCall, Args[format_idx],
4150 PDiag(diag::warn_printf_format_string_not_null_terminated),
4151 FExpr->getLocStart(),
4152 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4153 return;
4154 }
4155
Ted Kremenekab278de2010-01-28 23:39:18 +00004156 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004157 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004158 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004159 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004160 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4161 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004162 return;
4163 }
Ted Kremenek02087932010-07-16 02:11:22 +00004164
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004165 if (Type == FST_Printf || Type == FST_NSString ||
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004166 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek02087932010-07-16 02:11:22 +00004167 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004168 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004169 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004170 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004171
Hans Wennborg23926bd2011-12-15 10:25:47 +00004172 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004173 getLangOpts(),
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004174 Context.getTargetInfo(),
4175 Type == FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00004176 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004177 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004178 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004179 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004180 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004181
Hans Wennborg23926bd2011-12-15 10:25:47 +00004182 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004183 getLangOpts(),
4184 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004185 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004186 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004187}
4188
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004189bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4190 // Str - The format string. NOTE: this is NOT null-terminated!
4191 StringRef StrRef = FExpr->getString();
4192 const char *Str = StrRef.data();
4193 // Account for cases where the string literal is truncated in a declaration.
4194 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4195 assert(T && "String literal not of constant array type!");
4196 size_t TypeSize = T->getSize().getZExtValue();
4197 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4198 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4199 getLangOpts(),
4200 Context.getTargetInfo());
4201}
4202
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004203//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4204
4205// Returns the related absolute value function that is larger, of 0 if one
4206// does not exist.
4207static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4208 switch (AbsFunction) {
4209 default:
4210 return 0;
4211
4212 case Builtin::BI__builtin_abs:
4213 return Builtin::BI__builtin_labs;
4214 case Builtin::BI__builtin_labs:
4215 return Builtin::BI__builtin_llabs;
4216 case Builtin::BI__builtin_llabs:
4217 return 0;
4218
4219 case Builtin::BI__builtin_fabsf:
4220 return Builtin::BI__builtin_fabs;
4221 case Builtin::BI__builtin_fabs:
4222 return Builtin::BI__builtin_fabsl;
4223 case Builtin::BI__builtin_fabsl:
4224 return 0;
4225
4226 case Builtin::BI__builtin_cabsf:
4227 return Builtin::BI__builtin_cabs;
4228 case Builtin::BI__builtin_cabs:
4229 return Builtin::BI__builtin_cabsl;
4230 case Builtin::BI__builtin_cabsl:
4231 return 0;
4232
4233 case Builtin::BIabs:
4234 return Builtin::BIlabs;
4235 case Builtin::BIlabs:
4236 return Builtin::BIllabs;
4237 case Builtin::BIllabs:
4238 return 0;
4239
4240 case Builtin::BIfabsf:
4241 return Builtin::BIfabs;
4242 case Builtin::BIfabs:
4243 return Builtin::BIfabsl;
4244 case Builtin::BIfabsl:
4245 return 0;
4246
4247 case Builtin::BIcabsf:
4248 return Builtin::BIcabs;
4249 case Builtin::BIcabs:
4250 return Builtin::BIcabsl;
4251 case Builtin::BIcabsl:
4252 return 0;
4253 }
4254}
4255
4256// Returns the argument type of the absolute value function.
4257static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4258 unsigned AbsType) {
4259 if (AbsType == 0)
4260 return QualType();
4261
4262 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4263 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4264 if (Error != ASTContext::GE_None)
4265 return QualType();
4266
4267 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4268 if (!FT)
4269 return QualType();
4270
4271 if (FT->getNumParams() != 1)
4272 return QualType();
4273
4274 return FT->getParamType(0);
4275}
4276
4277// Returns the best absolute value function, or zero, based on type and
4278// current absolute value function.
4279static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4280 unsigned AbsFunctionKind) {
4281 unsigned BestKind = 0;
4282 uint64_t ArgSize = Context.getTypeSize(ArgType);
4283 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4284 Kind = getLargerAbsoluteValueFunction(Kind)) {
4285 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4286 if (Context.getTypeSize(ParamType) >= ArgSize) {
4287 if (BestKind == 0)
4288 BestKind = Kind;
4289 else if (Context.hasSameType(ParamType, ArgType)) {
4290 BestKind = Kind;
4291 break;
4292 }
4293 }
4294 }
4295 return BestKind;
4296}
4297
4298enum AbsoluteValueKind {
4299 AVK_Integer,
4300 AVK_Floating,
4301 AVK_Complex
4302};
4303
4304static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4305 if (T->isIntegralOrEnumerationType())
4306 return AVK_Integer;
4307 if (T->isRealFloatingType())
4308 return AVK_Floating;
4309 if (T->isAnyComplexType())
4310 return AVK_Complex;
4311
4312 llvm_unreachable("Type not integer, floating, or complex");
4313}
4314
4315// Changes the absolute value function to a different type. Preserves whether
4316// the function is a builtin.
4317static unsigned changeAbsFunction(unsigned AbsKind,
4318 AbsoluteValueKind ValueKind) {
4319 switch (ValueKind) {
4320 case AVK_Integer:
4321 switch (AbsKind) {
4322 default:
4323 return 0;
4324 case Builtin::BI__builtin_fabsf:
4325 case Builtin::BI__builtin_fabs:
4326 case Builtin::BI__builtin_fabsl:
4327 case Builtin::BI__builtin_cabsf:
4328 case Builtin::BI__builtin_cabs:
4329 case Builtin::BI__builtin_cabsl:
4330 return Builtin::BI__builtin_abs;
4331 case Builtin::BIfabsf:
4332 case Builtin::BIfabs:
4333 case Builtin::BIfabsl:
4334 case Builtin::BIcabsf:
4335 case Builtin::BIcabs:
4336 case Builtin::BIcabsl:
4337 return Builtin::BIabs;
4338 }
4339 case AVK_Floating:
4340 switch (AbsKind) {
4341 default:
4342 return 0;
4343 case Builtin::BI__builtin_abs:
4344 case Builtin::BI__builtin_labs:
4345 case Builtin::BI__builtin_llabs:
4346 case Builtin::BI__builtin_cabsf:
4347 case Builtin::BI__builtin_cabs:
4348 case Builtin::BI__builtin_cabsl:
4349 return Builtin::BI__builtin_fabsf;
4350 case Builtin::BIabs:
4351 case Builtin::BIlabs:
4352 case Builtin::BIllabs:
4353 case Builtin::BIcabsf:
4354 case Builtin::BIcabs:
4355 case Builtin::BIcabsl:
4356 return Builtin::BIfabsf;
4357 }
4358 case AVK_Complex:
4359 switch (AbsKind) {
4360 default:
4361 return 0;
4362 case Builtin::BI__builtin_abs:
4363 case Builtin::BI__builtin_labs:
4364 case Builtin::BI__builtin_llabs:
4365 case Builtin::BI__builtin_fabsf:
4366 case Builtin::BI__builtin_fabs:
4367 case Builtin::BI__builtin_fabsl:
4368 return Builtin::BI__builtin_cabsf;
4369 case Builtin::BIabs:
4370 case Builtin::BIlabs:
4371 case Builtin::BIllabs:
4372 case Builtin::BIfabsf:
4373 case Builtin::BIfabs:
4374 case Builtin::BIfabsl:
4375 return Builtin::BIcabsf;
4376 }
4377 }
4378 llvm_unreachable("Unable to convert function");
4379}
4380
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004381static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004382 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4383 if (!FnInfo)
4384 return 0;
4385
4386 switch (FDecl->getBuiltinID()) {
4387 default:
4388 return 0;
4389 case Builtin::BI__builtin_abs:
4390 case Builtin::BI__builtin_fabs:
4391 case Builtin::BI__builtin_fabsf:
4392 case Builtin::BI__builtin_fabsl:
4393 case Builtin::BI__builtin_labs:
4394 case Builtin::BI__builtin_llabs:
4395 case Builtin::BI__builtin_cabs:
4396 case Builtin::BI__builtin_cabsf:
4397 case Builtin::BI__builtin_cabsl:
4398 case Builtin::BIabs:
4399 case Builtin::BIlabs:
4400 case Builtin::BIllabs:
4401 case Builtin::BIfabs:
4402 case Builtin::BIfabsf:
4403 case Builtin::BIfabsl:
4404 case Builtin::BIcabs:
4405 case Builtin::BIcabsf:
4406 case Builtin::BIcabsl:
4407 return FDecl->getBuiltinID();
4408 }
4409 llvm_unreachable("Unknown Builtin type");
4410}
4411
4412// If the replacement is valid, emit a note with replacement function.
4413// Additionally, suggest including the proper header if not already included.
4414static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004415 unsigned AbsKind, QualType ArgType) {
4416 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004417 const char *HeaderName = nullptr;
4418 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004419 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4420 FunctionName = "std::abs";
4421 if (ArgType->isIntegralOrEnumerationType()) {
4422 HeaderName = "cstdlib";
4423 } else if (ArgType->isRealFloatingType()) {
4424 HeaderName = "cmath";
4425 } else {
4426 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004427 }
Richard Trieubeffb832014-04-15 23:47:53 +00004428
4429 // Lookup all std::abs
4430 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004431 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004432 R.suppressDiagnostics();
4433 S.LookupQualifiedName(R, Std);
4434
4435 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004436 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004437 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4438 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4439 } else {
4440 FDecl = dyn_cast<FunctionDecl>(I);
4441 }
4442 if (!FDecl)
4443 continue;
4444
4445 // Found std::abs(), check that they are the right ones.
4446 if (FDecl->getNumParams() != 1)
4447 continue;
4448
4449 // Check that the parameter type can handle the argument.
4450 QualType ParamType = FDecl->getParamDecl(0)->getType();
4451 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4452 S.Context.getTypeSize(ArgType) <=
4453 S.Context.getTypeSize(ParamType)) {
4454 // Found a function, don't need the header hint.
4455 EmitHeaderHint = false;
4456 break;
4457 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004458 }
Richard Trieubeffb832014-04-15 23:47:53 +00004459 }
4460 } else {
4461 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4462 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4463
4464 if (HeaderName) {
4465 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4466 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4467 R.suppressDiagnostics();
4468 S.LookupName(R, S.getCurScope());
4469
4470 if (R.isSingleResult()) {
4471 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4472 if (FD && FD->getBuiltinID() == AbsKind) {
4473 EmitHeaderHint = false;
4474 } else {
4475 return;
4476 }
4477 } else if (!R.empty()) {
4478 return;
4479 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004480 }
4481 }
4482
4483 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00004484 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004485
Richard Trieubeffb832014-04-15 23:47:53 +00004486 if (!HeaderName)
4487 return;
4488
4489 if (!EmitHeaderHint)
4490 return;
4491
Alp Toker5d96e0a2014-07-11 20:53:51 +00004492 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4493 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00004494}
4495
4496static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4497 if (!FDecl)
4498 return false;
4499
4500 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4501 return false;
4502
4503 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4504
4505 while (ND && ND->isInlineNamespace()) {
4506 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004507 }
Richard Trieubeffb832014-04-15 23:47:53 +00004508
4509 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4510 return false;
4511
4512 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4513 return false;
4514
4515 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004516}
4517
4518// Warn when using the wrong abs() function.
4519void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4520 const FunctionDecl *FDecl,
4521 IdentifierInfo *FnInfo) {
4522 if (Call->getNumArgs() != 1)
4523 return;
4524
4525 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00004526 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4527 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004528 return;
4529
4530 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4531 QualType ParamType = Call->getArg(0)->getType();
4532
Alp Toker5d96e0a2014-07-11 20:53:51 +00004533 // Unsigned types cannot be negative. Suggest removing the absolute value
4534 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004535 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00004536 const char *FunctionName =
4537 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004538 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4539 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00004540 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004541 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4542 return;
4543 }
4544
Richard Trieubeffb832014-04-15 23:47:53 +00004545 // std::abs has overloads which prevent most of the absolute value problems
4546 // from occurring.
4547 if (IsStdAbs)
4548 return;
4549
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004550 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4551 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4552
4553 // The argument and parameter are the same kind. Check if they are the right
4554 // size.
4555 if (ArgValueKind == ParamValueKind) {
4556 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4557 return;
4558
4559 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4560 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4561 << FDecl << ArgType << ParamType;
4562
4563 if (NewAbsKind == 0)
4564 return;
4565
4566 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004567 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004568 return;
4569 }
4570
4571 // ArgValueKind != ParamValueKind
4572 // The wrong type of absolute value function was used. Attempt to find the
4573 // proper one.
4574 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4575 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4576 if (NewAbsKind == 0)
4577 return;
4578
4579 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4580 << FDecl << ParamValueKind << ArgValueKind;
4581
4582 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004583 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004584 return;
4585}
4586
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004587//===--- CHECK: Standard memory functions ---------------------------------===//
4588
Nico Weber0e6daef2013-12-26 23:38:39 +00004589/// \brief Takes the expression passed to the size_t parameter of functions
4590/// such as memcmp, strncat, etc and warns if it's a comparison.
4591///
4592/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4593static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4594 IdentifierInfo *FnName,
4595 SourceLocation FnLoc,
4596 SourceLocation RParenLoc) {
4597 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4598 if (!Size)
4599 return false;
4600
4601 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4602 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4603 return false;
4604
Nico Weber0e6daef2013-12-26 23:38:39 +00004605 SourceRange SizeRange = Size->getSourceRange();
4606 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4607 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00004608 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004609 << FnName << FixItHint::CreateInsertion(
4610 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00004611 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00004612 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00004613 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00004614 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4615 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00004616
4617 return true;
4618}
4619
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004620/// \brief Determine whether the given type is or contains a dynamic class type
4621/// (e.g., whether it has a vtable).
4622static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4623 bool &IsContained) {
4624 // Look through array types while ignoring qualifiers.
4625 const Type *Ty = T->getBaseElementTypeUnsafe();
4626 IsContained = false;
4627
4628 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4629 RD = RD ? RD->getDefinition() : nullptr;
4630 if (!RD)
4631 return nullptr;
4632
4633 if (RD->isDynamicClass())
4634 return RD;
4635
4636 // Check all the fields. If any bases were dynamic, the class is dynamic.
4637 // It's impossible for a class to transitively contain itself by value, so
4638 // infinite recursion is impossible.
4639 for (auto *FD : RD->fields()) {
4640 bool SubContained;
4641 if (const CXXRecordDecl *ContainedRD =
4642 getContainedDynamicClass(FD->getType(), SubContained)) {
4643 IsContained = true;
4644 return ContainedRD;
4645 }
4646 }
4647
4648 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004649}
4650
Chandler Carruth889ed862011-06-21 23:04:20 +00004651/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004652/// otherwise returns NULL.
4653static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004654 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004655 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4656 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4657 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004658
Craig Topperc3ec1492014-05-26 06:22:03 +00004659 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004660}
4661
Chandler Carruth889ed862011-06-21 23:04:20 +00004662/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004663static QualType getSizeOfArgType(const Expr* E) {
4664 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4665 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4666 if (SizeOf->getKind() == clang::UETT_SizeOf)
4667 return SizeOf->getTypeOfArgument();
4668
4669 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004670}
4671
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004672/// \brief Check for dangerous or invalid arguments to memset().
4673///
Chandler Carruthac687262011-06-03 06:23:57 +00004674/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004675/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4676/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004677///
4678/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004679void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004680 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004681 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004682 assert(BId != 0);
4683
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004684 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004685 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004686 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004687 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004688 return;
4689
Anna Zaks22122702012-01-17 00:37:07 +00004690 unsigned LastArg = (BId == Builtin::BImemset ||
4691 BId == Builtin::BIstrndup ? 1 : 2);
4692 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004693 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004694
Nico Weber0e6daef2013-12-26 23:38:39 +00004695 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4696 Call->getLocStart(), Call->getRParenLoc()))
4697 return;
4698
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004699 // We have special checking when the length is a sizeof expression.
4700 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4701 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4702 llvm::FoldingSetNodeID SizeOfArgID;
4703
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004704 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4705 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004706 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004707
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004708 QualType DestTy = Dest->getType();
4709 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4710 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004711
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004712 // Never warn about void type pointers. This can be used to suppress
4713 // false positives.
4714 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004715 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004716
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004717 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4718 // actually comparing the expressions for equality. Because computing the
4719 // expression IDs can be expensive, we only do this if the diagnostic is
4720 // enabled.
4721 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004722 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4723 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004724 // We only compute IDs for expressions if the warning is enabled, and
4725 // cache the sizeof arg's ID.
4726 if (SizeOfArgID == llvm::FoldingSetNodeID())
4727 SizeOfArg->Profile(SizeOfArgID, Context, true);
4728 llvm::FoldingSetNodeID DestID;
4729 Dest->Profile(DestID, Context, true);
4730 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004731 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4732 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004733 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004734 StringRef ReadableName = FnName->getName();
4735
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004736 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004737 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004738 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004739 if (!PointeeTy->isIncompleteType() &&
4740 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004741 ActionIdx = 2; // If the pointee's size is sizeof(char),
4742 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004743
4744 // If the function is defined as a builtin macro, do not show macro
4745 // expansion.
4746 SourceLocation SL = SizeOfArg->getExprLoc();
4747 SourceRange DSR = Dest->getSourceRange();
4748 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004749 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004750
4751 if (SM.isMacroArgExpansion(SL)) {
4752 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4753 SL = SM.getSpellingLoc(SL);
4754 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4755 SM.getSpellingLoc(DSR.getEnd()));
4756 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4757 SM.getSpellingLoc(SSR.getEnd()));
4758 }
4759
Anna Zaksd08d9152012-05-30 23:14:52 +00004760 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004761 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004762 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004763 << PointeeTy
4764 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004765 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004766 << SSR);
4767 DiagRuntimeBehavior(SL, SizeOfArg,
4768 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4769 << ActionIdx
4770 << SSR);
4771
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004772 break;
4773 }
4774 }
4775
4776 // Also check for cases where the sizeof argument is the exact same
4777 // type as the memory argument, and where it points to a user-defined
4778 // record type.
4779 if (SizeOfArgTy != QualType()) {
4780 if (PointeeTy->isRecordType() &&
4781 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4782 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4783 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4784 << FnName << SizeOfArgTy << ArgIdx
4785 << PointeeTy << Dest->getSourceRange()
4786 << LenExpr->getSourceRange());
4787 break;
4788 }
Nico Weberc5e73862011-06-14 16:14:58 +00004789 }
4790
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004791 // Always complain about dynamic classes.
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004792 bool IsContained;
4793 if (const CXXRecordDecl *ContainedRD =
4794 getContainedDynamicClass(PointeeTy, IsContained)) {
Anna Zaks22122702012-01-17 00:37:07 +00004795
4796 unsigned OperationType = 0;
4797 // "overwritten" if we're warning about the destination for any call
4798 // but memcmp; otherwise a verb appropriate to the call.
4799 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4800 if (BId == Builtin::BImemcpy)
4801 OperationType = 1;
4802 else if(BId == Builtin::BImemmove)
4803 OperationType = 2;
4804 else if (BId == Builtin::BImemcmp)
4805 OperationType = 3;
4806 }
4807
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004808 DiagRuntimeBehavior(
4809 Dest->getExprLoc(), Dest,
4810 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004811 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004812 << FnName << IsContained << ContainedRD << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004813 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004814 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4815 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004816 DiagRuntimeBehavior(
4817 Dest->getExprLoc(), Dest,
4818 PDiag(diag::warn_arc_object_memaccess)
4819 << ArgIdx << FnName << PointeeTy
4820 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004821 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004822 continue;
John McCall31168b02011-06-15 23:02:42 +00004823
4824 DiagRuntimeBehavior(
4825 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004826 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004827 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4828 break;
4829 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004830 }
4831}
4832
Ted Kremenek6865f772011-08-18 20:55:45 +00004833// A little helper routine: ignore addition and subtraction of integer literals.
4834// This intentionally does not ignore all integer constant expressions because
4835// we don't want to remove sizeof().
4836static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4837 Ex = Ex->IgnoreParenCasts();
4838
4839 for (;;) {
4840 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4841 if (!BO || !BO->isAdditiveOp())
4842 break;
4843
4844 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4845 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4846
4847 if (isa<IntegerLiteral>(RHS))
4848 Ex = LHS;
4849 else if (isa<IntegerLiteral>(LHS))
4850 Ex = RHS;
4851 else
4852 break;
4853 }
4854
4855 return Ex;
4856}
4857
Anna Zaks13b08572012-08-08 21:42:23 +00004858static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4859 ASTContext &Context) {
4860 // Only handle constant-sized or VLAs, but not flexible members.
4861 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4862 // Only issue the FIXIT for arrays of size > 1.
4863 if (CAT->getSize().getSExtValue() <= 1)
4864 return false;
4865 } else if (!Ty->isVariableArrayType()) {
4866 return false;
4867 }
4868 return true;
4869}
4870
Ted Kremenek6865f772011-08-18 20:55:45 +00004871// Warn if the user has made the 'size' argument to strlcpy or strlcat
4872// be the size of the source, instead of the destination.
4873void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4874 IdentifierInfo *FnName) {
4875
4876 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00004877 unsigned NumArgs = Call->getNumArgs();
4878 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00004879 return;
4880
4881 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4882 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004883 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00004884
4885 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4886 Call->getLocStart(), Call->getRParenLoc()))
4887 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004888
4889 // Look for 'strlcpy(dst, x, sizeof(x))'
4890 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4891 CompareWithSrc = Ex;
4892 else {
4893 // Look for 'strlcpy(dst, x, strlen(x))'
4894 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004895 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4896 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004897 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4898 }
4899 }
4900
4901 if (!CompareWithSrc)
4902 return;
4903
4904 // Determine if the argument to sizeof/strlen is equal to the source
4905 // argument. In principle there's all kinds of things you could do
4906 // here, for instance creating an == expression and evaluating it with
4907 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4908 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4909 if (!SrcArgDRE)
4910 return;
4911
4912 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4913 if (!CompareWithSrcDRE ||
4914 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4915 return;
4916
4917 const Expr *OriginalSizeArg = Call->getArg(2);
4918 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4919 << OriginalSizeArg->getSourceRange() << FnName;
4920
4921 // Output a FIXIT hint if the destination is an array (rather than a
4922 // pointer to an array). This could be enhanced to handle some
4923 // pointers if we know the actual size, like if DstArg is 'array+2'
4924 // we could say 'sizeof(array)-2'.
4925 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004926 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004927 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004928
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004929 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004930 llvm::raw_svector_ostream OS(sizeString);
4931 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004932 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004933 OS << ")";
4934
4935 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4936 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4937 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004938}
4939
Anna Zaks314cd092012-02-01 19:08:57 +00004940/// Check if two expressions refer to the same declaration.
4941static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4942 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4943 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4944 return D1->getDecl() == D2->getDecl();
4945 return false;
4946}
4947
4948static const Expr *getStrlenExprArg(const Expr *E) {
4949 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4950 const FunctionDecl *FD = CE->getDirectCallee();
4951 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00004952 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004953 return CE->getArg(0)->IgnoreParenCasts();
4954 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004955 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004956}
4957
4958// Warn on anti-patterns as the 'size' argument to strncat.
4959// The correct size argument should look like following:
4960// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4961void Sema::CheckStrncatArguments(const CallExpr *CE,
4962 IdentifierInfo *FnName) {
4963 // Don't crash if the user has the wrong number of arguments.
4964 if (CE->getNumArgs() < 3)
4965 return;
4966 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4967 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4968 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4969
Nico Weber0e6daef2013-12-26 23:38:39 +00004970 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4971 CE->getRParenLoc()))
4972 return;
4973
Anna Zaks314cd092012-02-01 19:08:57 +00004974 // Identify common expressions, which are wrongly used as the size argument
4975 // to strncat and may lead to buffer overflows.
4976 unsigned PatternType = 0;
4977 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4978 // - sizeof(dst)
4979 if (referToTheSameDecl(SizeOfArg, DstArg))
4980 PatternType = 1;
4981 // - sizeof(src)
4982 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4983 PatternType = 2;
4984 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4985 if (BE->getOpcode() == BO_Sub) {
4986 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4987 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4988 // - sizeof(dst) - strlen(dst)
4989 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4990 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4991 PatternType = 1;
4992 // - sizeof(src) - (anything)
4993 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4994 PatternType = 2;
4995 }
4996 }
4997
4998 if (PatternType == 0)
4999 return;
5000
Anna Zaks5069aa32012-02-03 01:27:37 +00005001 // Generate the diagnostic.
5002 SourceLocation SL = LenArg->getLocStart();
5003 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005004 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00005005
5006 // If the function is defined as a builtin macro, do not show macro expansion.
5007 if (SM.isMacroArgExpansion(SL)) {
5008 SL = SM.getSpellingLoc(SL);
5009 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5010 SM.getSpellingLoc(SR.getEnd()));
5011 }
5012
Anna Zaks13b08572012-08-08 21:42:23 +00005013 // Check if the destination is an array (rather than a pointer to an array).
5014 QualType DstTy = DstArg->getType();
5015 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5016 Context);
5017 if (!isKnownSizeArray) {
5018 if (PatternType == 1)
5019 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5020 else
5021 Diag(SL, diag::warn_strncat_src_size) << SR;
5022 return;
5023 }
5024
Anna Zaks314cd092012-02-01 19:08:57 +00005025 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00005026 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005027 else
Anna Zaks5069aa32012-02-03 01:27:37 +00005028 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005029
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005030 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00005031 llvm::raw_svector_ostream OS(sizeString);
5032 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005033 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005034 OS << ") - ";
5035 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005036 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005037 OS << ") - 1";
5038
Anna Zaks5069aa32012-02-03 01:27:37 +00005039 Diag(SL, diag::note_strncat_wrong_size)
5040 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005041}
5042
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005043//===--- CHECK: Return Address of Stack Variable --------------------------===//
5044
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005045static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5046 Decl *ParentDecl);
5047static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5048 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005049
5050/// CheckReturnStackAddr - Check if a return statement returns the address
5051/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005052static void
5053CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5054 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005055
Craig Topperc3ec1492014-05-26 06:22:03 +00005056 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005057 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005058
5059 // Perform checking for returned stack addresses, local blocks,
5060 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005061 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005062 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005063 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005064 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005065 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005066 }
5067
Craig Topperc3ec1492014-05-26 06:22:03 +00005068 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005069 return; // Nothing suspicious was found.
5070
5071 SourceLocation diagLoc;
5072 SourceRange diagRange;
5073 if (refVars.empty()) {
5074 diagLoc = stackE->getLocStart();
5075 diagRange = stackE->getSourceRange();
5076 } else {
5077 // We followed through a reference variable. 'stackE' contains the
5078 // problematic expression but we will warn at the return statement pointing
5079 // at the reference variable. We will later display the "trail" of
5080 // reference variables using notes.
5081 diagLoc = refVars[0]->getLocStart();
5082 diagRange = refVars[0]->getSourceRange();
5083 }
5084
5085 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005086 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005087 : diag::warn_ret_stack_addr)
5088 << DR->getDecl()->getDeclName() << diagRange;
5089 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005090 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005091 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005092 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005093 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005094 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
5095 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005096 << diagRange;
5097 }
5098
5099 // Display the "trail" of reference variables that we followed until we
5100 // found the problematic expression using notes.
5101 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5102 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5103 // If this var binds to another reference var, show the range of the next
5104 // var, otherwise the var binds to the problematic expression, in which case
5105 // show the range of the expression.
5106 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5107 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005108 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5109 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005110 }
5111}
5112
5113/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5114/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005115/// to a location on the stack, a local block, an address of a label, or a
5116/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005117/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005118/// encounter a subexpression that (1) clearly does not lead to one of the
5119/// above problematic expressions (2) is something we cannot determine leads to
5120/// a problematic expression based on such local checking.
5121///
5122/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5123/// the expression that they point to. Such variables are added to the
5124/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005125///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005126/// EvalAddr processes expressions that are pointers that are used as
5127/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005128/// At the base case of the recursion is a check for the above problematic
5129/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005130///
5131/// This implementation handles:
5132///
5133/// * pointer-to-pointer casts
5134/// * implicit conversions from array references to pointers
5135/// * taking the address of fields
5136/// * arbitrary interplay between "&" and "*" operators
5137/// * pointer arithmetic from an address of a stack variable
5138/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005139static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5140 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005141 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005142 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005143
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005144 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005145 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005146 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005147 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005148 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005149
Peter Collingbourne91147592011-04-15 00:35:48 +00005150 E = E->IgnoreParens();
5151
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005152 // Our "symbolic interpreter" is just a dispatch off the currently
5153 // viewed AST node. We then recursively traverse the AST by calling
5154 // EvalAddr and EvalVal appropriately.
5155 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005156 case Stmt::DeclRefExprClass: {
5157 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5158
Richard Smith40f08eb2014-01-30 22:05:38 +00005159 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005160 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005161 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005162
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005163 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5164 // If this is a reference variable, follow through to the expression that
5165 // it points to.
5166 if (V->hasLocalStorage() &&
5167 V->getType()->isReferenceType() && V->hasInit()) {
5168 // Add the reference variable to the "trail".
5169 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005170 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005171 }
5172
Craig Topperc3ec1492014-05-26 06:22:03 +00005173 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005174 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005175
Chris Lattner934edb22007-12-28 05:31:15 +00005176 case Stmt::UnaryOperatorClass: {
5177 // The only unary operator that make sense to handle here
5178 // is AddrOf. All others don't make sense as pointers.
5179 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005180
John McCalle3027922010-08-25 11:45:40 +00005181 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005182 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005183 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005184 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005185 }
Mike Stump11289f42009-09-09 15:08:12 +00005186
Chris Lattner934edb22007-12-28 05:31:15 +00005187 case Stmt::BinaryOperatorClass: {
5188 // Handle pointer arithmetic. All other binary operators are not valid
5189 // in this context.
5190 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005191 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005192
John McCalle3027922010-08-25 11:45:40 +00005193 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005194 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005195
Chris Lattner934edb22007-12-28 05:31:15 +00005196 Expr *Base = B->getLHS();
5197
5198 // Determine which argument is the real pointer base. It could be
5199 // the RHS argument instead of the LHS.
5200 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005201
Chris Lattner934edb22007-12-28 05:31:15 +00005202 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005203 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005204 }
Steve Naroff2752a172008-09-10 19:17:48 +00005205
Chris Lattner934edb22007-12-28 05:31:15 +00005206 // For conditional operators we need to see if either the LHS or RHS are
5207 // valid DeclRefExpr*s. If one of them is valid, we return it.
5208 case Stmt::ConditionalOperatorClass: {
5209 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005210
Chris Lattner934edb22007-12-28 05:31:15 +00005211 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005212 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5213 if (Expr *LHSExpr = C->getLHS()) {
5214 // In C++, we can have a throw-expression, which has 'void' type.
5215 if (!LHSExpr->getType()->isVoidType())
5216 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005217 return LHS;
5218 }
Chris Lattner934edb22007-12-28 05:31:15 +00005219
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005220 // In C++, we can have a throw-expression, which has 'void' type.
5221 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005222 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005223
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005224 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005225 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005226
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005227 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00005228 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005229 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00005230 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005231
5232 case Stmt::AddrLabelExprClass:
5233 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00005234
John McCall28fc7092011-11-10 05:35:25 +00005235 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005236 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5237 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005238
Ted Kremenekc3b4c522008-08-07 00:49:01 +00005239 // For casts, we need to handle conversions from arrays to
5240 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00005241 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00005242 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005243 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00005244 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00005245 case Stmt::CXXStaticCastExprClass:
5246 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00005247 case Stmt::CXXConstCastExprClass:
5248 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00005249 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5250 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00005251 case CK_LValueToRValue:
5252 case CK_NoOp:
5253 case CK_BaseToDerived:
5254 case CK_DerivedToBase:
5255 case CK_UncheckedDerivedToBase:
5256 case CK_Dynamic:
5257 case CK_CPointerToObjCPointerCast:
5258 case CK_BlockPointerToObjCPointerCast:
5259 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005260 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005261
5262 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005263 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005264
Richard Trieudadefde2014-07-02 04:39:38 +00005265 case CK_BitCast:
5266 if (SubExpr->getType()->isAnyPointerType() ||
5267 SubExpr->getType()->isBlockPointerType() ||
5268 SubExpr->getType()->isObjCQualifiedIdType())
5269 return EvalAddr(SubExpr, refVars, ParentDecl);
5270 else
5271 return nullptr;
5272
Eli Friedman8195ad72012-02-23 23:04:32 +00005273 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005274 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00005275 }
Chris Lattner934edb22007-12-28 05:31:15 +00005276 }
Mike Stump11289f42009-09-09 15:08:12 +00005277
Douglas Gregorfe314812011-06-21 17:03:29 +00005278 case Stmt::MaterializeTemporaryExprClass:
5279 if (Expr *Result = EvalAddr(
5280 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005281 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005282 return Result;
5283
5284 return E;
5285
Chris Lattner934edb22007-12-28 05:31:15 +00005286 // Everything else: we simply don't reason about them.
5287 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005288 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00005289 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005290}
Mike Stump11289f42009-09-09 15:08:12 +00005291
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005292
5293/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5294/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005295static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5296 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005297do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005298 // We should only be called for evaluating non-pointer expressions, or
5299 // expressions with a pointer type that are not used as references but instead
5300 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00005301
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005302 // Our "symbolic interpreter" is just a dispatch off the currently
5303 // viewed AST node. We then recursively traverse the AST by calling
5304 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00005305
5306 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005307 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005308 case Stmt::ImplicitCastExprClass: {
5309 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00005310 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005311 E = IE->getSubExpr();
5312 continue;
5313 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005314 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00005315 }
5316
John McCall28fc7092011-11-10 05:35:25 +00005317 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005318 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005319
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005320 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005321 // When we hit a DeclRefExpr we are looking at code that refers to a
5322 // variable's name. If it's not a reference variable we check if it has
5323 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005324 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005325
Richard Smith40f08eb2014-01-30 22:05:38 +00005326 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005327 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005328 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005329
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005330 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5331 // Check if it refers to itself, e.g. "int& i = i;".
5332 if (V == ParentDecl)
5333 return DR;
5334
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005335 if (V->hasLocalStorage()) {
5336 if (!V->getType()->isReferenceType())
5337 return DR;
5338
5339 // Reference variable, follow through to the expression that
5340 // it points to.
5341 if (V->hasInit()) {
5342 // Add the reference variable to the "trail".
5343 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005344 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005345 }
5346 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005347 }
Mike Stump11289f42009-09-09 15:08:12 +00005348
Craig Topperc3ec1492014-05-26 06:22:03 +00005349 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005350 }
Mike Stump11289f42009-09-09 15:08:12 +00005351
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005352 case Stmt::UnaryOperatorClass: {
5353 // The only unary operator that make sense to handle here
5354 // is Deref. All others don't resolve to a "name." This includes
5355 // handling all sorts of rvalues passed to a unary operator.
5356 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005357
John McCalle3027922010-08-25 11:45:40 +00005358 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005359 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005360
Craig Topperc3ec1492014-05-26 06:22:03 +00005361 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005362 }
Mike Stump11289f42009-09-09 15:08:12 +00005363
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005364 case Stmt::ArraySubscriptExprClass: {
5365 // Array subscripts are potential references to data on the stack. We
5366 // retrieve the DeclRefExpr* for the array variable if it indeed
5367 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005368 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005369 }
Mike Stump11289f42009-09-09 15:08:12 +00005370
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005371 case Stmt::ConditionalOperatorClass: {
5372 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005373 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005374 ConditionalOperator *C = cast<ConditionalOperator>(E);
5375
Anders Carlsson801c5c72007-11-30 19:04:31 +00005376 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005377 if (Expr *LHSExpr = C->getLHS()) {
5378 // In C++, we can have a throw-expression, which has 'void' type.
5379 if (!LHSExpr->getType()->isVoidType())
5380 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5381 return LHS;
5382 }
5383
5384 // In C++, we can have a throw-expression, which has 'void' type.
5385 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005386 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005387
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005388 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005389 }
Mike Stump11289f42009-09-09 15:08:12 +00005390
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005391 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005392 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005393 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005394
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005395 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005396 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005397 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005398
5399 // Check whether the member type is itself a reference, in which case
5400 // we're not going to refer to the member, but to what the member refers to.
5401 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005402 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005403
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005404 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005405 }
Mike Stump11289f42009-09-09 15:08:12 +00005406
Douglas Gregorfe314812011-06-21 17:03:29 +00005407 case Stmt::MaterializeTemporaryExprClass:
5408 if (Expr *Result = EvalVal(
5409 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005410 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005411 return Result;
5412
5413 return E;
5414
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005415 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005416 // Check that we don't return or take the address of a reference to a
5417 // temporary. This is only useful in C++.
5418 if (!E->isTypeDependent() && E->isRValue())
5419 return E;
5420
5421 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005422 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005423 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005424} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005425}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005426
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005427void
5428Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5429 SourceLocation ReturnLoc,
5430 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005431 const AttrVec *Attrs,
5432 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005433 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5434
5435 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00005436 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5437 CheckNonNullExpr(*this, RetValExp))
5438 Diag(ReturnLoc, diag::warn_null_ret)
5439 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00005440
5441 // C++11 [basic.stc.dynamic.allocation]p4:
5442 // If an allocation function declared with a non-throwing
5443 // exception-specification fails to allocate storage, it shall return
5444 // a null pointer. Any other allocation function that fails to allocate
5445 // storage shall indicate failure only by throwing an exception [...]
5446 if (FD) {
5447 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5448 if (Op == OO_New || Op == OO_Array_New) {
5449 const FunctionProtoType *Proto
5450 = FD->getType()->castAs<FunctionProtoType>();
5451 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5452 CheckNonNullExpr(*this, RetValExp))
5453 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5454 << FD << getLangOpts().CPlusPlus11;
5455 }
5456 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005457}
5458
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005459//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5460
5461/// Check for comparisons of floating point operands using != and ==.
5462/// Issue a warning if these are no self-comparisons, as they are not likely
5463/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00005464void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00005465 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5466 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005467
5468 // Special case: check for x == x (which is OK).
5469 // Do not emit warnings for such cases.
5470 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5471 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5472 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00005473 return;
Mike Stump11289f42009-09-09 15:08:12 +00005474
5475
Ted Kremenekeda40e22007-11-29 00:59:04 +00005476 // Special case: check for comparisons against literals that can be exactly
5477 // represented by APFloat. In such cases, do not emit a warning. This
5478 // is a heuristic: often comparison against such literals are used to
5479 // detect if a value in a variable has not changed. This clearly can
5480 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00005481 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5482 if (FLL->isExact())
5483 return;
5484 } else
5485 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5486 if (FLR->isExact())
5487 return;
Mike Stump11289f42009-09-09 15:08:12 +00005488
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005489 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00005490 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005491 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005492 return;
Mike Stump11289f42009-09-09 15:08:12 +00005493
David Blaikie1f4ff152012-07-16 20:47:22 +00005494 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005495 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005496 return;
Mike Stump11289f42009-09-09 15:08:12 +00005497
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005498 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00005499 Diag(Loc, diag::warn_floatingpoint_eq)
5500 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005501}
John McCallca01b222010-01-04 23:21:16 +00005502
John McCall70aa5392010-01-06 05:24:50 +00005503//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5504//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00005505
John McCall70aa5392010-01-06 05:24:50 +00005506namespace {
John McCallca01b222010-01-04 23:21:16 +00005507
John McCall70aa5392010-01-06 05:24:50 +00005508/// Structure recording the 'active' range of an integer-valued
5509/// expression.
5510struct IntRange {
5511 /// The number of bits active in the int.
5512 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00005513
John McCall70aa5392010-01-06 05:24:50 +00005514 /// True if the int is known not to have negative values.
5515 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00005516
John McCall70aa5392010-01-06 05:24:50 +00005517 IntRange(unsigned Width, bool NonNegative)
5518 : Width(Width), NonNegative(NonNegative)
5519 {}
John McCallca01b222010-01-04 23:21:16 +00005520
John McCall817d4af2010-11-10 23:38:19 +00005521 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00005522 static IntRange forBoolType() {
5523 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00005524 }
5525
John McCall817d4af2010-11-10 23:38:19 +00005526 /// Returns the range of an opaque value of the given integral type.
5527 static IntRange forValueOfType(ASTContext &C, QualType T) {
5528 return forValueOfCanonicalType(C,
5529 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00005530 }
5531
John McCall817d4af2010-11-10 23:38:19 +00005532 /// Returns the range of an opaque value of a canonical integral type.
5533 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00005534 assert(T->isCanonicalUnqualified());
5535
5536 if (const VectorType *VT = dyn_cast<VectorType>(T))
5537 T = VT->getElementType().getTypePtr();
5538 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5539 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005540 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5541 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00005542
David Majnemer6a426652013-06-07 22:07:20 +00005543 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00005544 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00005545 EnumDecl *Enum = ET->getDecl();
5546 if (!Enum->isCompleteDefinition())
5547 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00005548
David Majnemer6a426652013-06-07 22:07:20 +00005549 unsigned NumPositive = Enum->getNumPositiveBits();
5550 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00005551
David Majnemer6a426652013-06-07 22:07:20 +00005552 if (NumNegative == 0)
5553 return IntRange(NumPositive, true/*NonNegative*/);
5554 else
5555 return IntRange(std::max(NumPositive + 1, NumNegative),
5556 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00005557 }
John McCall70aa5392010-01-06 05:24:50 +00005558
5559 const BuiltinType *BT = cast<BuiltinType>(T);
5560 assert(BT->isInteger());
5561
5562 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5563 }
5564
John McCall817d4af2010-11-10 23:38:19 +00005565 /// Returns the "target" range of a canonical integral type, i.e.
5566 /// the range of values expressible in the type.
5567 ///
5568 /// This matches forValueOfCanonicalType except that enums have the
5569 /// full range of their type, not the range of their enumerators.
5570 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5571 assert(T->isCanonicalUnqualified());
5572
5573 if (const VectorType *VT = dyn_cast<VectorType>(T))
5574 T = VT->getElementType().getTypePtr();
5575 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5576 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005577 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5578 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005579 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00005580 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005581
5582 const BuiltinType *BT = cast<BuiltinType>(T);
5583 assert(BT->isInteger());
5584
5585 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5586 }
5587
5588 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00005589 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00005590 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00005591 L.NonNegative && R.NonNegative);
5592 }
5593
John McCall817d4af2010-11-10 23:38:19 +00005594 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00005595 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00005596 return IntRange(std::min(L.Width, R.Width),
5597 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00005598 }
5599};
5600
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005601static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5602 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005603 if (value.isSigned() && value.isNegative())
5604 return IntRange(value.getMinSignedBits(), false);
5605
5606 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005607 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005608
5609 // isNonNegative() just checks the sign bit without considering
5610 // signedness.
5611 return IntRange(value.getActiveBits(), true);
5612}
5613
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005614static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5615 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005616 if (result.isInt())
5617 return GetValueRange(C, result.getInt(), MaxWidth);
5618
5619 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00005620 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5621 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5622 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5623 R = IntRange::join(R, El);
5624 }
John McCall70aa5392010-01-06 05:24:50 +00005625 return R;
5626 }
5627
5628 if (result.isComplexInt()) {
5629 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5630 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5631 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00005632 }
5633
5634 // This can happen with lossless casts to intptr_t of "based" lvalues.
5635 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00005636 // FIXME: The only reason we need to pass the type in here is to get
5637 // the sign right on this one case. It would be nice if APValue
5638 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005639 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00005640 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005641}
John McCall70aa5392010-01-06 05:24:50 +00005642
Eli Friedmane6d33952013-07-08 20:20:06 +00005643static QualType GetExprType(Expr *E) {
5644 QualType Ty = E->getType();
5645 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5646 Ty = AtomicRHS->getValueType();
5647 return Ty;
5648}
5649
John McCall70aa5392010-01-06 05:24:50 +00005650/// Pseudo-evaluate the given integer expression, estimating the
5651/// range of values it might take.
5652///
5653/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005654static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005655 E = E->IgnoreParens();
5656
5657 // Try a full evaluation first.
5658 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005659 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005660 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005661
5662 // I think we only want to look through implicit casts here; if the
5663 // user has an explicit widening cast, we should treat the value as
5664 // being of the new, wider type.
5665 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005666 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005667 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5668
Eli Friedmane6d33952013-07-08 20:20:06 +00005669 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005670
John McCalle3027922010-08-25 11:45:40 +00005671 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005672
John McCall70aa5392010-01-06 05:24:50 +00005673 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005674 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005675 return OutputTypeRange;
5676
5677 IntRange SubRange
5678 = GetExprRange(C, CE->getSubExpr(),
5679 std::min(MaxWidth, OutputTypeRange.Width));
5680
5681 // Bail out if the subexpr's range is as wide as the cast type.
5682 if (SubRange.Width >= OutputTypeRange.Width)
5683 return OutputTypeRange;
5684
5685 // Otherwise, we take the smaller width, and we're non-negative if
5686 // either the output type or the subexpr is.
5687 return IntRange(SubRange.Width,
5688 SubRange.NonNegative || OutputTypeRange.NonNegative);
5689 }
5690
5691 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5692 // If we can fold the condition, just take that operand.
5693 bool CondResult;
5694 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5695 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5696 : CO->getFalseExpr(),
5697 MaxWidth);
5698
5699 // Otherwise, conservatively merge.
5700 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5701 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5702 return IntRange::join(L, R);
5703 }
5704
5705 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5706 switch (BO->getOpcode()) {
5707
5708 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005709 case BO_LAnd:
5710 case BO_LOr:
5711 case BO_LT:
5712 case BO_GT:
5713 case BO_LE:
5714 case BO_GE:
5715 case BO_EQ:
5716 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005717 return IntRange::forBoolType();
5718
John McCallc3688382011-07-13 06:35:24 +00005719 // The type of the assignments is the type of the LHS, so the RHS
5720 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005721 case BO_MulAssign:
5722 case BO_DivAssign:
5723 case BO_RemAssign:
5724 case BO_AddAssign:
5725 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005726 case BO_XorAssign:
5727 case BO_OrAssign:
5728 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005729 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005730
John McCallc3688382011-07-13 06:35:24 +00005731 // Simple assignments just pass through the RHS, which will have
5732 // been coerced to the LHS type.
5733 case BO_Assign:
5734 // TODO: bitfields?
5735 return GetExprRange(C, BO->getRHS(), MaxWidth);
5736
John McCall70aa5392010-01-06 05:24:50 +00005737 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005738 case BO_PtrMemD:
5739 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005740 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005741
John McCall2ce81ad2010-01-06 22:07:33 +00005742 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005743 case BO_And:
5744 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005745 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5746 GetExprRange(C, BO->getRHS(), MaxWidth));
5747
John McCall70aa5392010-01-06 05:24:50 +00005748 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005749 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005750 // ...except that we want to treat '1 << (blah)' as logically
5751 // positive. It's an important idiom.
5752 if (IntegerLiteral *I
5753 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5754 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005755 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005756 return IntRange(R.Width, /*NonNegative*/ true);
5757 }
5758 }
5759 // fallthrough
5760
John McCalle3027922010-08-25 11:45:40 +00005761 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005762 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005763
John McCall2ce81ad2010-01-06 22:07:33 +00005764 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005765 case BO_Shr:
5766 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005767 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5768
5769 // If the shift amount is a positive constant, drop the width by
5770 // that much.
5771 llvm::APSInt shift;
5772 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5773 shift.isNonNegative()) {
5774 unsigned zext = shift.getZExtValue();
5775 if (zext >= L.Width)
5776 L.Width = (L.NonNegative ? 0 : 1);
5777 else
5778 L.Width -= zext;
5779 }
5780
5781 return L;
5782 }
5783
5784 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005785 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005786 return GetExprRange(C, BO->getRHS(), MaxWidth);
5787
John McCall2ce81ad2010-01-06 22:07:33 +00005788 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005789 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005790 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005791 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005792 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005793
John McCall51431812011-07-14 22:39:48 +00005794 // The width of a division result is mostly determined by the size
5795 // of the LHS.
5796 case BO_Div: {
5797 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005798 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005799 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5800
5801 // If the divisor is constant, use that.
5802 llvm::APSInt divisor;
5803 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5804 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5805 if (log2 >= L.Width)
5806 L.Width = (L.NonNegative ? 0 : 1);
5807 else
5808 L.Width = std::min(L.Width - log2, MaxWidth);
5809 return L;
5810 }
5811
5812 // Otherwise, just use the LHS's width.
5813 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5814 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5815 }
5816
5817 // The result of a remainder can't be larger than the result of
5818 // either side.
5819 case BO_Rem: {
5820 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005821 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005822 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5823 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5824
5825 IntRange meet = IntRange::meet(L, R);
5826 meet.Width = std::min(meet.Width, MaxWidth);
5827 return meet;
5828 }
5829
5830 // The default behavior is okay for these.
5831 case BO_Mul:
5832 case BO_Add:
5833 case BO_Xor:
5834 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005835 break;
5836 }
5837
John McCall51431812011-07-14 22:39:48 +00005838 // The default case is to treat the operation as if it were closed
5839 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005840 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5841 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5842 return IntRange::join(L, R);
5843 }
5844
5845 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5846 switch (UO->getOpcode()) {
5847 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005848 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005849 return IntRange::forBoolType();
5850
5851 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005852 case UO_Deref:
5853 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005854 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005855
5856 default:
5857 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5858 }
5859 }
5860
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005861 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5862 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5863
John McCalld25db7e2013-05-06 21:39:12 +00005864 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005865 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005866 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005867
Eli Friedmane6d33952013-07-08 20:20:06 +00005868 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005869}
John McCall263a48b2010-01-04 23:31:57 +00005870
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005871static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005872 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005873}
5874
John McCall263a48b2010-01-04 23:31:57 +00005875/// Checks whether the given value, which currently has the given
5876/// source semantics, has the same value when coerced through the
5877/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005878static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5879 const llvm::fltSemantics &Src,
5880 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005881 llvm::APFloat truncated = value;
5882
5883 bool ignored;
5884 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5885 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5886
5887 return truncated.bitwiseIsEqual(value);
5888}
5889
5890/// Checks whether the given value, which currently has the given
5891/// source semantics, has the same value when coerced through the
5892/// target semantics.
5893///
5894/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005895static bool IsSameFloatAfterCast(const APValue &value,
5896 const llvm::fltSemantics &Src,
5897 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005898 if (value.isFloat())
5899 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5900
5901 if (value.isVector()) {
5902 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5903 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5904 return false;
5905 return true;
5906 }
5907
5908 assert(value.isComplexFloat());
5909 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5910 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5911}
5912
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005913static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005914
Ted Kremenek6274be42010-09-23 21:43:44 +00005915static bool IsZero(Sema &S, Expr *E) {
5916 // Suppress cases where we are comparing against an enum constant.
5917 if (const DeclRefExpr *DR =
5918 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5919 if (isa<EnumConstantDecl>(DR->getDecl()))
5920 return false;
5921
5922 // Suppress cases where the '0' value is expanded from a macro.
5923 if (E->getLocStart().isMacroID())
5924 return false;
5925
John McCallcc7e5bf2010-05-06 08:58:33 +00005926 llvm::APSInt Value;
5927 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5928}
5929
John McCall2551c1b2010-10-06 00:25:24 +00005930static bool HasEnumType(Expr *E) {
5931 // Strip off implicit integral promotions.
5932 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005933 if (ICE->getCastKind() != CK_IntegralCast &&
5934 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005935 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005936 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005937 }
5938
5939 return E->getType()->isEnumeralType();
5940}
5941
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005942static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005943 // Disable warning in template instantiations.
5944 if (!S.ActiveTemplateInstantiations.empty())
5945 return;
5946
John McCalle3027922010-08-25 11:45:40 +00005947 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005948 if (E->isValueDependent())
5949 return;
5950
John McCalle3027922010-08-25 11:45:40 +00005951 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005952 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005953 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005954 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005955 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005956 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005957 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005958 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005959 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005960 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005961 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005962 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005963 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005964 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005965 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005966 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5967 }
5968}
5969
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005970static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005971 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005972 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005973 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005974 // Disable warning in template instantiations.
5975 if (!S.ActiveTemplateInstantiations.empty())
5976 return;
5977
Richard Trieu0f097742014-04-04 04:13:47 +00005978 // TODO: Investigate using GetExprRange() to get tighter bounds
5979 // on the bit ranges.
5980 QualType OtherT = Other->getType();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005981 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5982 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00005983 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5984 unsigned OtherWidth = OtherRange.Width;
5985
5986 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5987
Richard Trieu560910c2012-11-14 22:50:24 +00005988 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00005989 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00005990 return;
5991
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005992 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00005993 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005994
Richard Trieu0f097742014-04-04 04:13:47 +00005995 // Used for diagnostic printout.
5996 enum {
5997 LiteralConstant = 0,
5998 CXXBoolLiteralTrue,
5999 CXXBoolLiteralFalse
6000 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006001
Richard Trieu0f097742014-04-04 04:13:47 +00006002 if (!OtherIsBooleanType) {
6003 QualType ConstantT = Constant->getType();
6004 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00006005
Richard Trieu0f097742014-04-04 04:13:47 +00006006 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6007 return;
6008 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6009 "comparison with non-integer type");
6010
6011 bool ConstantSigned = ConstantT->isSignedIntegerType();
6012 bool CommonSigned = CommonT->isSignedIntegerType();
6013
6014 bool EqualityOnly = false;
6015
6016 if (CommonSigned) {
6017 // The common type is signed, therefore no signed to unsigned conversion.
6018 if (!OtherRange.NonNegative) {
6019 // Check that the constant is representable in type OtherT.
6020 if (ConstantSigned) {
6021 if (OtherWidth >= Value.getMinSignedBits())
6022 return;
6023 } else { // !ConstantSigned
6024 if (OtherWidth >= Value.getActiveBits() + 1)
6025 return;
6026 }
6027 } else { // !OtherSigned
6028 // Check that the constant is representable in type OtherT.
6029 // Negative values are out of range.
6030 if (ConstantSigned) {
6031 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6032 return;
6033 } else { // !ConstantSigned
6034 if (OtherWidth >= Value.getActiveBits())
6035 return;
6036 }
Richard Trieu560910c2012-11-14 22:50:24 +00006037 }
Richard Trieu0f097742014-04-04 04:13:47 +00006038 } else { // !CommonSigned
6039 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006040 if (OtherWidth >= Value.getActiveBits())
6041 return;
Craig Toppercf360162014-06-18 05:13:11 +00006042 } else { // OtherSigned
6043 assert(!ConstantSigned &&
6044 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006045 // Check to see if the constant is representable in OtherT.
6046 if (OtherWidth > Value.getActiveBits())
6047 return;
6048 // Check to see if the constant is equivalent to a negative value
6049 // cast to CommonT.
6050 if (S.Context.getIntWidth(ConstantT) ==
6051 S.Context.getIntWidth(CommonT) &&
6052 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6053 return;
6054 // The constant value rests between values that OtherT can represent
6055 // after conversion. Relational comparison still works, but equality
6056 // comparisons will be tautological.
6057 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006058 }
6059 }
Richard Trieu0f097742014-04-04 04:13:47 +00006060
6061 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6062
6063 if (op == BO_EQ || op == BO_NE) {
6064 IsTrue = op == BO_NE;
6065 } else if (EqualityOnly) {
6066 return;
6067 } else if (RhsConstant) {
6068 if (op == BO_GT || op == BO_GE)
6069 IsTrue = !PositiveConstant;
6070 else // op == BO_LT || op == BO_LE
6071 IsTrue = PositiveConstant;
6072 } else {
6073 if (op == BO_LT || op == BO_LE)
6074 IsTrue = !PositiveConstant;
6075 else // op == BO_GT || op == BO_GE
6076 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006077 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006078 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00006079 // Other isKnownToHaveBooleanValue
6080 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6081 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6082 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6083
6084 static const struct LinkedConditions {
6085 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6086 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6087 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6088 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6089 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6090 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6091
6092 } TruthTable = {
6093 // Constant on LHS. | Constant on RHS. |
6094 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6095 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6096 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6097 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6098 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6099 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6100 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6101 };
6102
6103 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6104
6105 enum ConstantValue ConstVal = Zero;
6106 if (Value.isUnsigned() || Value.isNonNegative()) {
6107 if (Value == 0) {
6108 LiteralOrBoolConstant =
6109 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6110 ConstVal = Zero;
6111 } else if (Value == 1) {
6112 LiteralOrBoolConstant =
6113 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6114 ConstVal = One;
6115 } else {
6116 LiteralOrBoolConstant = LiteralConstant;
6117 ConstVal = GT_One;
6118 }
6119 } else {
6120 ConstVal = LT_Zero;
6121 }
6122
6123 CompareBoolWithConstantResult CmpRes;
6124
6125 switch (op) {
6126 case BO_LT:
6127 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6128 break;
6129 case BO_GT:
6130 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6131 break;
6132 case BO_LE:
6133 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6134 break;
6135 case BO_GE:
6136 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6137 break;
6138 case BO_EQ:
6139 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6140 break;
6141 case BO_NE:
6142 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6143 break;
6144 default:
6145 CmpRes = Unkwn;
6146 break;
6147 }
6148
6149 if (CmpRes == AFals) {
6150 IsTrue = false;
6151 } else if (CmpRes == ATrue) {
6152 IsTrue = true;
6153 } else {
6154 return;
6155 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006156 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006157
6158 // If this is a comparison to an enum constant, include that
6159 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006160 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006161 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6162 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6163
6164 SmallString<64> PrettySourceValue;
6165 llvm::raw_svector_ostream OS(PrettySourceValue);
6166 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00006167 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006168 else
6169 OS << Value;
6170
Richard Trieu0f097742014-04-04 04:13:47 +00006171 S.DiagRuntimeBehavior(
6172 E->getOperatorLoc(), E,
6173 S.PDiag(diag::warn_out_of_range_compare)
6174 << OS.str() << LiteralOrBoolConstant
6175 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6176 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006177}
6178
John McCallcc7e5bf2010-05-06 08:58:33 +00006179/// Analyze the operands of the given comparison. Implements the
6180/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006181static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00006182 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6183 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006184}
John McCall263a48b2010-01-04 23:31:57 +00006185
John McCallca01b222010-01-04 23:21:16 +00006186/// \brief Implements -Wsign-compare.
6187///
Richard Trieu82402a02011-09-15 21:56:47 +00006188/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006189static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006190 // The type the comparison is being performed in.
6191 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006192
6193 // Only analyze comparison operators where both sides have been converted to
6194 // the same type.
6195 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6196 return AnalyzeImpConvsInComparison(S, E);
6197
6198 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006199 if (E->isValueDependent())
6200 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006201
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006202 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6203 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006204
6205 bool IsComparisonConstant = false;
6206
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006207 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006208 // of 'true' or 'false'.
6209 if (T->isIntegralType(S.Context)) {
6210 llvm::APSInt RHSValue;
6211 bool IsRHSIntegralLiteral =
6212 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6213 llvm::APSInt LHSValue;
6214 bool IsLHSIntegralLiteral =
6215 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6216 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6217 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6218 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6219 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6220 else
6221 IsComparisonConstant =
6222 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006223 } else if (!T->hasUnsignedIntegerRepresentation())
6224 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006225
John McCallcc7e5bf2010-05-06 08:58:33 +00006226 // We don't do anything special if this isn't an unsigned integral
6227 // comparison: we're only interested in integral comparisons, and
6228 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00006229 //
6230 // We also don't care about value-dependent expressions or expressions
6231 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006232 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00006233 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006234
John McCallcc7e5bf2010-05-06 08:58:33 +00006235 // Check to see if one of the (unmodified) operands is of different
6236 // signedness.
6237 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00006238 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6239 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00006240 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00006241 signedOperand = LHS;
6242 unsignedOperand = RHS;
6243 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6244 signedOperand = RHS;
6245 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00006246 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00006247 CheckTrivialUnsignedComparison(S, E);
6248 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006249 }
6250
John McCallcc7e5bf2010-05-06 08:58:33 +00006251 // Otherwise, calculate the effective range of the signed operand.
6252 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00006253
John McCallcc7e5bf2010-05-06 08:58:33 +00006254 // Go ahead and analyze implicit conversions in the operands. Note
6255 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00006256 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6257 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00006258
John McCallcc7e5bf2010-05-06 08:58:33 +00006259 // If the signed range is non-negative, -Wsign-compare won't fire,
6260 // but we should still check for comparisons which are always true
6261 // or false.
6262 if (signedRange.NonNegative)
6263 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006264
6265 // For (in)equality comparisons, if the unsigned operand is a
6266 // constant which cannot collide with a overflowed signed operand,
6267 // then reinterpreting the signed operand as unsigned will not
6268 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00006269 if (E->isEqualityOp()) {
6270 unsigned comparisonWidth = S.Context.getIntWidth(T);
6271 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00006272
John McCallcc7e5bf2010-05-06 08:58:33 +00006273 // We should never be unable to prove that the unsigned operand is
6274 // non-negative.
6275 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6276
6277 if (unsignedRange.Width < comparisonWidth)
6278 return;
6279 }
6280
Douglas Gregorbfb4a212012-05-01 01:53:49 +00006281 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6282 S.PDiag(diag::warn_mixed_sign_comparison)
6283 << LHS->getType() << RHS->getType()
6284 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00006285}
6286
John McCall1f425642010-11-11 03:21:53 +00006287/// Analyzes an attempt to assign the given value to a bitfield.
6288///
6289/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006290static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6291 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00006292 assert(Bitfield->isBitField());
6293 if (Bitfield->isInvalidDecl())
6294 return false;
6295
John McCalldeebbcf2010-11-11 05:33:51 +00006296 // White-list bool bitfields.
6297 if (Bitfield->getType()->isBooleanType())
6298 return false;
6299
Douglas Gregor789adec2011-02-04 13:09:01 +00006300 // Ignore value- or type-dependent expressions.
6301 if (Bitfield->getBitWidth()->isValueDependent() ||
6302 Bitfield->getBitWidth()->isTypeDependent() ||
6303 Init->isValueDependent() ||
6304 Init->isTypeDependent())
6305 return false;
6306
John McCall1f425642010-11-11 03:21:53 +00006307 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6308
Richard Smith5fab0c92011-12-28 19:48:30 +00006309 llvm::APSInt Value;
6310 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00006311 return false;
6312
John McCall1f425642010-11-11 03:21:53 +00006313 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00006314 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00006315
6316 if (OriginalWidth <= FieldWidth)
6317 return false;
6318
Eli Friedmanc267a322012-01-26 23:11:39 +00006319 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006320 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00006321 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00006322
Eli Friedmanc267a322012-01-26 23:11:39 +00006323 // Check whether the stored value is equal to the original value.
6324 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00006325 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00006326 return false;
6327
Eli Friedmanc267a322012-01-26 23:11:39 +00006328 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00006329 // therefore don't strictly fit into a signed bitfield of width 1.
6330 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00006331 return false;
6332
John McCall1f425642010-11-11 03:21:53 +00006333 std::string PrettyValue = Value.toString(10);
6334 std::string PrettyTrunc = TruncatedValue.toString(10);
6335
6336 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6337 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6338 << Init->getSourceRange();
6339
6340 return true;
6341}
6342
John McCalld2a53122010-11-09 23:24:47 +00006343/// Analyze the given simple or compound assignment for warning-worthy
6344/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006345static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006346 // Just recurse on the LHS.
6347 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6348
6349 // We want to recurse on the RHS as normal unless we're assigning to
6350 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006351 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006352 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006353 E->getOperatorLoc())) {
6354 // Recurse, ignoring any implicit conversions on the RHS.
6355 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6356 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006357 }
6358 }
6359
6360 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6361}
6362
John McCall263a48b2010-01-04 23:31:57 +00006363/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006364static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006365 SourceLocation CContext, unsigned diag,
6366 bool pruneControlFlow = false) {
6367 if (pruneControlFlow) {
6368 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6369 S.PDiag(diag)
6370 << SourceType << T << E->getSourceRange()
6371 << SourceRange(CContext));
6372 return;
6373 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006374 S.Diag(E->getExprLoc(), diag)
6375 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6376}
6377
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006378/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006379static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006380 SourceLocation CContext, unsigned diag,
6381 bool pruneControlFlow = false) {
6382 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006383}
6384
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006385/// Diagnose an implicit cast from a literal expression. Does not warn when the
6386/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006387void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6388 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006389 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006390 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006391 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006392 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6393 T->hasUnsignedIntegerRepresentation());
6394 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006395 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006396 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006397 return;
6398
Eli Friedman07185912013-08-29 23:44:43 +00006399 // FIXME: Force the precision of the source value down so we don't print
6400 // digits which are usually useless (we don't really care here if we
6401 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6402 // would automatically print the shortest representation, but it's a bit
6403 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006404 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006405 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6406 precision = (precision * 59 + 195) / 196;
6407 Value.toString(PrettySourceValue, precision);
6408
David Blaikie9b88cc02012-05-15 17:18:27 +00006409 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006410 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6411 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6412 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006413 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006414
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006415 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006416 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6417 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006418}
6419
John McCall18a2c2c2010-11-09 22:22:12 +00006420std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6421 if (!Range.Width) return "0";
6422
6423 llvm::APSInt ValueInRange = Value;
6424 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006425 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006426 return ValueInRange.toString(10);
6427}
6428
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006429static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6430 if (!isa<ImplicitCastExpr>(Ex))
6431 return false;
6432
6433 Expr *InnerE = Ex->IgnoreParenImpCasts();
6434 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6435 const Type *Source =
6436 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6437 if (Target->isDependentType())
6438 return false;
6439
6440 const BuiltinType *FloatCandidateBT =
6441 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6442 const Type *BoolCandidateType = ToBool ? Target : Source;
6443
6444 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6445 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6446}
6447
6448void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6449 SourceLocation CC) {
6450 unsigned NumArgs = TheCall->getNumArgs();
6451 for (unsigned i = 0; i < NumArgs; ++i) {
6452 Expr *CurrA = TheCall->getArg(i);
6453 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6454 continue;
6455
6456 bool IsSwapped = ((i > 0) &&
6457 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6458 IsSwapped |= ((i < (NumArgs - 1)) &&
6459 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6460 if (IsSwapped) {
6461 // Warn on this floating-point to bool conversion.
6462 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6463 CurrA->getType(), CC,
6464 diag::warn_impcast_floating_point_to_bool);
6465 }
6466 }
6467}
6468
Richard Trieu5b993502014-10-15 03:42:06 +00006469static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6470 SourceLocation CC) {
6471 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6472 E->getExprLoc()))
6473 return;
6474
6475 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6476 const Expr::NullPointerConstantKind NullKind =
6477 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6478 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6479 return;
6480
6481 // Return if target type is a safe conversion.
6482 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6483 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6484 return;
6485
6486 SourceLocation Loc = E->getSourceRange().getBegin();
6487
6488 // __null is usually wrapped in a macro. Go up a macro if that is the case.
6489 if (NullKind == Expr::NPCK_GNUNull) {
6490 if (Loc.isMacroID())
6491 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6492 }
6493
6494 // Only warn if the null and context location are in the same macro expansion.
6495 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6496 return;
6497
6498 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6499 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6500 << FixItHint::CreateReplacement(Loc,
6501 S.getFixItZeroLiteralForType(T, Loc));
6502}
6503
John McCallcc7e5bf2010-05-06 08:58:33 +00006504void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00006505 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006506 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00006507
John McCallcc7e5bf2010-05-06 08:58:33 +00006508 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6509 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6510 if (Source == Target) return;
6511 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00006512
Chandler Carruthc22845a2011-07-26 05:40:03 +00006513 // If the conversion context location is invalid don't complain. We also
6514 // don't want to emit a warning if the issue occurs from the expansion of
6515 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6516 // delay this check as long as possible. Once we detect we are in that
6517 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006518 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00006519 return;
6520
Richard Trieu021baa32011-09-23 20:10:00 +00006521 // Diagnose implicit casts to bool.
6522 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6523 if (isa<StringLiteral>(E))
6524 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00006525 // and expressions, for instance, assert(0 && "error here"), are
6526 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00006527 return DiagnoseImpCast(S, E, T, CC,
6528 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00006529 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6530 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6531 // This covers the literal expressions that evaluate to Objective-C
6532 // objects.
6533 return DiagnoseImpCast(S, E, T, CC,
6534 diag::warn_impcast_objective_c_literal_to_bool);
6535 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006536 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6537 // Warn on pointer to bool conversion that is always true.
6538 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6539 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00006540 }
Richard Trieu021baa32011-09-23 20:10:00 +00006541 }
John McCall263a48b2010-01-04 23:31:57 +00006542
6543 // Strip vector types.
6544 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006545 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006546 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006547 return;
John McCallacf0ee52010-10-08 02:01:28 +00006548 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006549 }
Chris Lattneree7286f2011-06-14 04:51:15 +00006550
6551 // If the vector cast is cast between two vectors of the same size, it is
6552 // a bitcast, not a conversion.
6553 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6554 return;
John McCall263a48b2010-01-04 23:31:57 +00006555
6556 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6557 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6558 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00006559 if (auto VecTy = dyn_cast<VectorType>(Target))
6560 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00006561
6562 // Strip complex types.
6563 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006564 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006565 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006566 return;
6567
John McCallacf0ee52010-10-08 02:01:28 +00006568 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006569 }
John McCall263a48b2010-01-04 23:31:57 +00006570
6571 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6572 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6573 }
6574
6575 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6576 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6577
6578 // If the source is floating point...
6579 if (SourceBT && SourceBT->isFloatingPoint()) {
6580 // ...and the target is floating point...
6581 if (TargetBT && TargetBT->isFloatingPoint()) {
6582 // ...then warn if we're dropping FP rank.
6583
6584 // Builtin FP kinds are ordered by increasing FP rank.
6585 if (SourceBT->getKind() > TargetBT->getKind()) {
6586 // Don't warn about float constants that are precisely
6587 // representable in the target type.
6588 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006589 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00006590 // Value might be a float, a float vector, or a float complex.
6591 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00006592 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6593 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00006594 return;
6595 }
6596
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006597 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006598 return;
6599
John McCallacf0ee52010-10-08 02:01:28 +00006600 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00006601 }
6602 return;
6603 }
6604
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006605 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00006606 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006607 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006608 return;
6609
Chandler Carruth22c7a792011-02-17 11:05:49 +00006610 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00006611 // We also want to warn on, e.g., "int i = -1.234"
6612 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6613 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6614 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6615
Chandler Carruth016ef402011-04-10 08:36:24 +00006616 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6617 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00006618 } else {
6619 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6620 }
6621 }
John McCall263a48b2010-01-04 23:31:57 +00006622
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006623 // If the target is bool, warn if expr is a function or method call.
6624 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6625 isa<CallExpr>(E)) {
6626 // Check last argument of function call to see if it is an
6627 // implicit cast from a type matching the type the result
6628 // is being cast to.
6629 CallExpr *CEx = cast<CallExpr>(E);
6630 unsigned NumArgs = CEx->getNumArgs();
6631 if (NumArgs > 0) {
6632 Expr *LastA = CEx->getArg(NumArgs - 1);
6633 Expr *InnerE = LastA->IgnoreParenImpCasts();
6634 const Type *InnerType =
6635 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6636 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6637 // Warn on this floating-point to bool conversion
6638 DiagnoseImpCast(S, E, T, CC,
6639 diag::warn_impcast_floating_point_to_bool);
6640 }
6641 }
6642 }
John McCall263a48b2010-01-04 23:31:57 +00006643 return;
6644 }
6645
Richard Trieu5b993502014-10-15 03:42:06 +00006646 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00006647
David Blaikie9366d2b2012-06-19 21:19:06 +00006648 if (!Source->isIntegerType() || !Target->isIntegerType())
6649 return;
6650
David Blaikie7555b6a2012-05-15 16:56:36 +00006651 // TODO: remove this early return once the false positives for constant->bool
6652 // in templates, macros, etc, are reduced or removed.
6653 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6654 return;
6655
John McCallcc7e5bf2010-05-06 08:58:33 +00006656 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00006657 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00006658
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006659 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00006660 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006661 // TODO: this should happen for bitfield stores, too.
6662 llvm::APSInt Value(32);
6663 if (E->isIntegerConstantExpr(Value, S.Context)) {
6664 if (S.SourceMgr.isInSystemMacro(CC))
6665 return;
6666
John McCall18a2c2c2010-11-09 22:22:12 +00006667 std::string PrettySourceValue = Value.toString(10);
6668 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006669
Ted Kremenek33ba9952011-10-22 02:37:33 +00006670 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6671 S.PDiag(diag::warn_impcast_integer_precision_constant)
6672 << PrettySourceValue << PrettyTargetValue
6673 << E->getType() << T << E->getSourceRange()
6674 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006675 return;
6676 }
6677
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006678 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6679 if (S.SourceMgr.isInSystemMacro(CC))
6680 return;
6681
David Blaikie9455da02012-04-12 22:40:54 +00006682 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006683 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6684 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006685 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006686 }
6687
6688 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6689 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6690 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006691
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006692 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006693 return;
6694
John McCallcc7e5bf2010-05-06 08:58:33 +00006695 unsigned DiagID = diag::warn_impcast_integer_sign;
6696
6697 // Traditionally, gcc has warned about this under -Wsign-compare.
6698 // We also want to warn about it in -Wconversion.
6699 // So if -Wconversion is off, use a completely identical diagnostic
6700 // in the sign-compare group.
6701 // The conditional-checking code will
6702 if (ICContext) {
6703 DiagID = diag::warn_impcast_integer_sign_conditional;
6704 *ICContext = true;
6705 }
6706
John McCallacf0ee52010-10-08 02:01:28 +00006707 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006708 }
6709
Douglas Gregora78f1932011-02-22 02:45:07 +00006710 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006711 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6712 // type, to give us better diagnostics.
6713 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006714 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006715 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6716 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6717 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6718 SourceType = S.Context.getTypeDeclType(Enum);
6719 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6720 }
6721 }
6722
Douglas Gregora78f1932011-02-22 02:45:07 +00006723 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6724 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006725 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6726 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006727 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006728 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006729 return;
6730
Douglas Gregor364f7db2011-03-12 00:14:31 +00006731 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006732 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006733 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006734
John McCall263a48b2010-01-04 23:31:57 +00006735 return;
6736}
6737
David Blaikie18e9ac72012-05-15 21:57:38 +00006738void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6739 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006740
6741void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006742 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006743 E = E->IgnoreParenImpCasts();
6744
6745 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006746 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006747
John McCallacf0ee52010-10-08 02:01:28 +00006748 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006749 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006750 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006751 return;
6752}
6753
David Blaikie18e9ac72012-05-15 21:57:38 +00006754void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6755 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00006756 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006757
6758 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006759 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6760 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006761
6762 // If -Wconversion would have warned about either of the candidates
6763 // for a signedness conversion to the context type...
6764 if (!Suspicious) return;
6765
6766 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006767 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006768 return;
6769
John McCallcc7e5bf2010-05-06 08:58:33 +00006770 // ...then check whether it would have warned about either of the
6771 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006772 if (E->getType() == T) return;
6773
6774 Suspicious = false;
6775 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6776 E->getType(), CC, &Suspicious);
6777 if (!Suspicious)
6778 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006779 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006780}
6781
Richard Trieu65724892014-11-15 06:37:39 +00006782/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6783/// Input argument E is a logical expression.
6784static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
6785 if (S.getLangOpts().Bool)
6786 return;
6787 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
6788}
6789
John McCallcc7e5bf2010-05-06 08:58:33 +00006790/// AnalyzeImplicitConversions - Find and report any interesting
6791/// implicit conversions in the given expression. There are a couple
6792/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006793void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006794 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006795 Expr *E = OrigE->IgnoreParenImpCasts();
6796
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006797 if (E->isTypeDependent() || E->isValueDependent())
6798 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006799
John McCallcc7e5bf2010-05-06 08:58:33 +00006800 // For conditional operators, we analyze the arguments as if they
6801 // were being fed directly into the output.
6802 if (isa<ConditionalOperator>(E)) {
6803 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006804 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006805 return;
6806 }
6807
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006808 // Check implicit argument conversions for function calls.
6809 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6810 CheckImplicitArgumentConversions(S, Call, CC);
6811
John McCallcc7e5bf2010-05-06 08:58:33 +00006812 // Go ahead and check any implicit conversions we might have skipped.
6813 // The non-canonical typecheck is just an optimization;
6814 // CheckImplicitConversion will filter out dead implicit conversions.
6815 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006816 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006817
6818 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006819
6820 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006821 if (POE->getResultExpr())
6822 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006823 }
6824
Fariborz Jahanian947efbc2015-02-26 17:59:54 +00006825 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
6826 if (OVE->getSourceExpr())
6827 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6828 return;
6829 }
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006830
John McCallcc7e5bf2010-05-06 08:58:33 +00006831 // Skip past explicit casts.
6832 if (isa<ExplicitCastExpr>(E)) {
6833 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006834 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006835 }
6836
John McCalld2a53122010-11-09 23:24:47 +00006837 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6838 // Do a somewhat different check with comparison operators.
6839 if (BO->isComparisonOp())
6840 return AnalyzeComparison(S, BO);
6841
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006842 // And with simple assignments.
6843 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006844 return AnalyzeAssignment(S, BO);
6845 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006846
6847 // These break the otherwise-useful invariant below. Fortunately,
6848 // we don't really need to recurse into them, because any internal
6849 // expressions should have been analyzed already when they were
6850 // built into statements.
6851 if (isa<StmtExpr>(E)) return;
6852
6853 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006854 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006855
6856 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006857 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006858 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006859 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006860 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006861 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006862 if (!ChildExpr)
6863 continue;
6864
Richard Trieu955231d2014-01-25 01:10:35 +00006865 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006866 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006867 // Ignore checking string literals that are in logical and operators.
6868 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006869 continue;
6870 AnalyzeImplicitConversions(S, ChildExpr, CC);
6871 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006872
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006873 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00006874 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
6875 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006876 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00006877
6878 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
6879 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006880 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006881 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006882
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006883 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
6884 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00006885 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006886}
6887
6888} // end anonymous namespace
6889
Richard Trieu3bb8b562014-02-26 02:36:06 +00006890enum {
6891 AddressOf,
6892 FunctionPointer,
6893 ArrayPointer
6894};
6895
Richard Trieuc1888e02014-06-28 23:25:37 +00006896// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6897// Returns true when emitting a warning about taking the address of a reference.
6898static bool CheckForReference(Sema &SemaRef, const Expr *E,
6899 PartialDiagnostic PD) {
6900 E = E->IgnoreParenImpCasts();
6901
6902 const FunctionDecl *FD = nullptr;
6903
6904 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6905 if (!DRE->getDecl()->getType()->isReferenceType())
6906 return false;
6907 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6908 if (!M->getMemberDecl()->getType()->isReferenceType())
6909 return false;
6910 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00006911 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00006912 return false;
6913 FD = Call->getDirectCallee();
6914 } else {
6915 return false;
6916 }
6917
6918 SemaRef.Diag(E->getExprLoc(), PD);
6919
6920 // If possible, point to location of function.
6921 if (FD) {
6922 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6923 }
6924
6925 return true;
6926}
6927
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006928// Returns true if the SourceLocation is expanded from any macro body.
6929// Returns false if the SourceLocation is invalid, is from not in a macro
6930// expansion, or is from expanded from a top-level macro argument.
6931static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
6932 if (Loc.isInvalid())
6933 return false;
6934
6935 while (Loc.isMacroID()) {
6936 if (SM.isMacroBodyExpansion(Loc))
6937 return true;
6938 Loc = SM.getImmediateMacroCallerLoc(Loc);
6939 }
6940
6941 return false;
6942}
6943
Richard Trieu3bb8b562014-02-26 02:36:06 +00006944/// \brief Diagnose pointers that are always non-null.
6945/// \param E the expression containing the pointer
6946/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6947/// compared to a null pointer
6948/// \param IsEqual True when the comparison is equal to a null pointer
6949/// \param Range Extra SourceRange to highlight in the diagnostic
6950void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6951 Expr::NullPointerConstantKind NullKind,
6952 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00006953 if (!E)
6954 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006955
6956 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006957 if (E->getExprLoc().isMacroID()) {
6958 const SourceManager &SM = getSourceManager();
6959 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
6960 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00006961 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006962 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006963 E = E->IgnoreImpCasts();
6964
6965 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6966
Richard Trieuf7432752014-06-06 21:39:26 +00006967 if (isa<CXXThisExpr>(E)) {
6968 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6969 : diag::warn_this_bool_conversion;
6970 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6971 return;
6972 }
6973
Richard Trieu3bb8b562014-02-26 02:36:06 +00006974 bool IsAddressOf = false;
6975
6976 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6977 if (UO->getOpcode() != UO_AddrOf)
6978 return;
6979 IsAddressOf = true;
6980 E = UO->getSubExpr();
6981 }
6982
Richard Trieuc1888e02014-06-28 23:25:37 +00006983 if (IsAddressOf) {
6984 unsigned DiagID = IsCompare
6985 ? diag::warn_address_of_reference_null_compare
6986 : diag::warn_address_of_reference_bool_conversion;
6987 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6988 << IsEqual;
6989 if (CheckForReference(*this, E, PD)) {
6990 return;
6991 }
6992 }
6993
Richard Trieu3bb8b562014-02-26 02:36:06 +00006994 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00006995 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006996 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6997 D = R->getDecl();
6998 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6999 D = M->getMemberDecl();
7000 }
7001
7002 // Weak Decls can be null.
7003 if (!D || D->isWeak())
7004 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007005
7006 // Check for parameter decl with nonnull attribute
7007 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
7008 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
7009 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
7010 unsigned NumArgs = FD->getNumParams();
7011 llvm::SmallBitVector AttrNonNull(NumArgs);
7012 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
7013 if (!NonNull->args_size()) {
7014 AttrNonNull.set(0, NumArgs);
7015 break;
7016 }
7017 for (unsigned Val : NonNull->args()) {
7018 if (Val >= NumArgs)
7019 continue;
7020 AttrNonNull.set(Val);
7021 }
7022 }
7023 if (!AttrNonNull.empty())
7024 for (unsigned i = 0; i < NumArgs; ++i)
Aaron Ballman2521f362014-12-11 19:35:42 +00007025 if (FD->getParamDecl(i) == PV &&
7026 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007027 std::string Str;
7028 llvm::raw_string_ostream S(Str);
7029 E->printPretty(S, nullptr, getPrintingPolicy());
7030 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
7031 : diag::warn_cast_nonnull_to_bool;
7032 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
7033 << Range << IsEqual;
7034 return;
7035 }
7036 }
7037 }
7038
Richard Trieu3bb8b562014-02-26 02:36:06 +00007039 QualType T = D->getType();
7040 const bool IsArray = T->isArrayType();
7041 const bool IsFunction = T->isFunctionType();
7042
Richard Trieuc1888e02014-06-28 23:25:37 +00007043 // Address of function is used to silence the function warning.
7044 if (IsAddressOf && IsFunction) {
7045 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007046 }
7047
7048 // Found nothing.
7049 if (!IsAddressOf && !IsFunction && !IsArray)
7050 return;
7051
7052 // Pretty print the expression for the diagnostic.
7053 std::string Str;
7054 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00007055 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00007056
7057 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7058 : diag::warn_impcast_pointer_to_bool;
7059 unsigned DiagType;
7060 if (IsAddressOf)
7061 DiagType = AddressOf;
7062 else if (IsFunction)
7063 DiagType = FunctionPointer;
7064 else if (IsArray)
7065 DiagType = ArrayPointer;
7066 else
7067 llvm_unreachable("Could not determine diagnostic.");
7068 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7069 << Range << IsEqual;
7070
7071 if (!IsFunction)
7072 return;
7073
7074 // Suggest '&' to silence the function warning.
7075 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7076 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7077
7078 // Check to see if '()' fixit should be emitted.
7079 QualType ReturnType;
7080 UnresolvedSet<4> NonTemplateOverloads;
7081 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7082 if (ReturnType.isNull())
7083 return;
7084
7085 if (IsCompare) {
7086 // There are two cases here. If there is null constant, the only suggest
7087 // for a pointer return type. If the null is 0, then suggest if the return
7088 // type is a pointer or an integer type.
7089 if (!ReturnType->isPointerType()) {
7090 if (NullKind == Expr::NPCK_ZeroExpression ||
7091 NullKind == Expr::NPCK_ZeroLiteral) {
7092 if (!ReturnType->isIntegerType())
7093 return;
7094 } else {
7095 return;
7096 }
7097 }
7098 } else { // !IsCompare
7099 // For function to bool, only suggest if the function pointer has bool
7100 // return type.
7101 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7102 return;
7103 }
7104 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007105 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00007106}
7107
7108
John McCallcc7e5bf2010-05-06 08:58:33 +00007109/// Diagnoses "dangerous" implicit conversions within the given
7110/// expression (which is a full expression). Implements -Wconversion
7111/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007112///
7113/// \param CC the "context" location of the implicit conversion, i.e.
7114/// the most location of the syntactic entity requiring the implicit
7115/// conversion
7116void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007117 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00007118 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00007119 return;
7120
7121 // Don't diagnose for value- or type-dependent expressions.
7122 if (E->isTypeDependent() || E->isValueDependent())
7123 return;
7124
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007125 // Check for array bounds violations in cases where the check isn't triggered
7126 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7127 // ArraySubscriptExpr is on the RHS of a variable initialization.
7128 CheckArrayAccess(E);
7129
John McCallacf0ee52010-10-08 02:01:28 +00007130 // This is not the right CC for (e.g.) a variable initialization.
7131 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007132}
7133
Richard Trieu65724892014-11-15 06:37:39 +00007134/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7135/// Input argument E is a logical expression.
7136void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7137 ::CheckBoolLikeConversion(*this, E, CC);
7138}
7139
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007140/// Diagnose when expression is an integer constant expression and its evaluation
7141/// results in integer overflow
7142void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00007143 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7144 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007145}
7146
Richard Smithc406cb72013-01-17 01:17:56 +00007147namespace {
7148/// \brief Visitor for expressions which looks for unsequenced operations on the
7149/// same object.
7150class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007151 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7152
Richard Smithc406cb72013-01-17 01:17:56 +00007153 /// \brief A tree of sequenced regions within an expression. Two regions are
7154 /// unsequenced if one is an ancestor or a descendent of the other. When we
7155 /// finish processing an expression with sequencing, such as a comma
7156 /// expression, we fold its tree nodes into its parent, since they are
7157 /// unsequenced with respect to nodes we will visit later.
7158 class SequenceTree {
7159 struct Value {
7160 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7161 unsigned Parent : 31;
7162 bool Merged : 1;
7163 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007164 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00007165
7166 public:
7167 /// \brief A region within an expression which may be sequenced with respect
7168 /// to some other region.
7169 class Seq {
7170 explicit Seq(unsigned N) : Index(N) {}
7171 unsigned Index;
7172 friend class SequenceTree;
7173 public:
7174 Seq() : Index(0) {}
7175 };
7176
7177 SequenceTree() { Values.push_back(Value(0)); }
7178 Seq root() const { return Seq(0); }
7179
7180 /// \brief Create a new sequence of operations, which is an unsequenced
7181 /// subset of \p Parent. This sequence of operations is sequenced with
7182 /// respect to other children of \p Parent.
7183 Seq allocate(Seq Parent) {
7184 Values.push_back(Value(Parent.Index));
7185 return Seq(Values.size() - 1);
7186 }
7187
7188 /// \brief Merge a sequence of operations into its parent.
7189 void merge(Seq S) {
7190 Values[S.Index].Merged = true;
7191 }
7192
7193 /// \brief Determine whether two operations are unsequenced. This operation
7194 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7195 /// should have been merged into its parent as appropriate.
7196 bool isUnsequenced(Seq Cur, Seq Old) {
7197 unsigned C = representative(Cur.Index);
7198 unsigned Target = representative(Old.Index);
7199 while (C >= Target) {
7200 if (C == Target)
7201 return true;
7202 C = Values[C].Parent;
7203 }
7204 return false;
7205 }
7206
7207 private:
7208 /// \brief Pick a representative for a sequence.
7209 unsigned representative(unsigned K) {
7210 if (Values[K].Merged)
7211 // Perform path compression as we go.
7212 return Values[K].Parent = representative(Values[K].Parent);
7213 return K;
7214 }
7215 };
7216
7217 /// An object for which we can track unsequenced uses.
7218 typedef NamedDecl *Object;
7219
7220 /// Different flavors of object usage which we track. We only track the
7221 /// least-sequenced usage of each kind.
7222 enum UsageKind {
7223 /// A read of an object. Multiple unsequenced reads are OK.
7224 UK_Use,
7225 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00007226 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00007227 UK_ModAsValue,
7228 /// A modification of an object which is not sequenced before the value
7229 /// computation of the expression, such as n++.
7230 UK_ModAsSideEffect,
7231
7232 UK_Count = UK_ModAsSideEffect + 1
7233 };
7234
7235 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00007236 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00007237 Expr *Use;
7238 SequenceTree::Seq Seq;
7239 };
7240
7241 struct UsageInfo {
7242 UsageInfo() : Diagnosed(false) {}
7243 Usage Uses[UK_Count];
7244 /// Have we issued a diagnostic for this variable already?
7245 bool Diagnosed;
7246 };
7247 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7248
7249 Sema &SemaRef;
7250 /// Sequenced regions within the expression.
7251 SequenceTree Tree;
7252 /// Declaration modifications and references which we have seen.
7253 UsageInfoMap UsageMap;
7254 /// The region we are currently within.
7255 SequenceTree::Seq Region;
7256 /// Filled in with declarations which were modified as a side-effect
7257 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007258 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00007259 /// Expressions to check later. We defer checking these to reduce
7260 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007261 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00007262
7263 /// RAII object wrapping the visitation of a sequenced subexpression of an
7264 /// expression. At the end of this process, the side-effects of the evaluation
7265 /// become sequenced with respect to the value computation of the result, so
7266 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7267 /// UK_ModAsValue.
7268 struct SequencedSubexpression {
7269 SequencedSubexpression(SequenceChecker &Self)
7270 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7271 Self.ModAsSideEffect = &ModAsSideEffect;
7272 }
7273 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00007274 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7275 MI != ME; ++MI) {
7276 UsageInfo &U = Self.UsageMap[MI->first];
7277 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7278 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7279 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00007280 }
7281 Self.ModAsSideEffect = OldModAsSideEffect;
7282 }
7283
7284 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007285 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7286 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00007287 };
7288
Richard Smith40238f02013-06-20 22:21:56 +00007289 /// RAII object wrapping the visitation of a subexpression which we might
7290 /// choose to evaluate as a constant. If any subexpression is evaluated and
7291 /// found to be non-constant, this allows us to suppress the evaluation of
7292 /// the outer expression.
7293 class EvaluationTracker {
7294 public:
7295 EvaluationTracker(SequenceChecker &Self)
7296 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7297 Self.EvalTracker = this;
7298 }
7299 ~EvaluationTracker() {
7300 Self.EvalTracker = Prev;
7301 if (Prev)
7302 Prev->EvalOK &= EvalOK;
7303 }
7304
7305 bool evaluate(const Expr *E, bool &Result) {
7306 if (!EvalOK || E->isValueDependent())
7307 return false;
7308 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7309 return EvalOK;
7310 }
7311
7312 private:
7313 SequenceChecker &Self;
7314 EvaluationTracker *Prev;
7315 bool EvalOK;
7316 } *EvalTracker;
7317
Richard Smithc406cb72013-01-17 01:17:56 +00007318 /// \brief Find the object which is produced by the specified expression,
7319 /// if any.
7320 Object getObject(Expr *E, bool Mod) const {
7321 E = E->IgnoreParenCasts();
7322 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7323 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7324 return getObject(UO->getSubExpr(), Mod);
7325 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7326 if (BO->getOpcode() == BO_Comma)
7327 return getObject(BO->getRHS(), Mod);
7328 if (Mod && BO->isAssignmentOp())
7329 return getObject(BO->getLHS(), Mod);
7330 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7331 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7332 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7333 return ME->getMemberDecl();
7334 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7335 // FIXME: If this is a reference, map through to its value.
7336 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00007337 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00007338 }
7339
7340 /// \brief Note that an object was modified or used by an expression.
7341 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7342 Usage &U = UI.Uses[UK];
7343 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7344 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7345 ModAsSideEffect->push_back(std::make_pair(O, U));
7346 U.Use = Ref;
7347 U.Seq = Region;
7348 }
7349 }
7350 /// \brief Check whether a modification or use conflicts with a prior usage.
7351 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7352 bool IsModMod) {
7353 if (UI.Diagnosed)
7354 return;
7355
7356 const Usage &U = UI.Uses[OtherKind];
7357 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7358 return;
7359
7360 Expr *Mod = U.Use;
7361 Expr *ModOrUse = Ref;
7362 if (OtherKind == UK_Use)
7363 std::swap(Mod, ModOrUse);
7364
7365 SemaRef.Diag(Mod->getExprLoc(),
7366 IsModMod ? diag::warn_unsequenced_mod_mod
7367 : diag::warn_unsequenced_mod_use)
7368 << O << SourceRange(ModOrUse->getExprLoc());
7369 UI.Diagnosed = true;
7370 }
7371
7372 void notePreUse(Object O, Expr *Use) {
7373 UsageInfo &U = UsageMap[O];
7374 // Uses conflict with other modifications.
7375 checkUsage(O, U, Use, UK_ModAsValue, false);
7376 }
7377 void notePostUse(Object O, Expr *Use) {
7378 UsageInfo &U = UsageMap[O];
7379 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7380 addUsage(U, O, Use, UK_Use);
7381 }
7382
7383 void notePreMod(Object O, Expr *Mod) {
7384 UsageInfo &U = UsageMap[O];
7385 // Modifications conflict with other modifications and with uses.
7386 checkUsage(O, U, Mod, UK_ModAsValue, true);
7387 checkUsage(O, U, Mod, UK_Use, false);
7388 }
7389 void notePostMod(Object O, Expr *Use, UsageKind UK) {
7390 UsageInfo &U = UsageMap[O];
7391 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7392 addUsage(U, O, Use, UK);
7393 }
7394
7395public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007396 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00007397 : Base(S.Context), SemaRef(S), Region(Tree.root()),
7398 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007399 Visit(E);
7400 }
7401
7402 void VisitStmt(Stmt *S) {
7403 // Skip all statements which aren't expressions for now.
7404 }
7405
7406 void VisitExpr(Expr *E) {
7407 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00007408 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007409 }
7410
7411 void VisitCastExpr(CastExpr *E) {
7412 Object O = Object();
7413 if (E->getCastKind() == CK_LValueToRValue)
7414 O = getObject(E->getSubExpr(), false);
7415
7416 if (O)
7417 notePreUse(O, E);
7418 VisitExpr(E);
7419 if (O)
7420 notePostUse(O, E);
7421 }
7422
7423 void VisitBinComma(BinaryOperator *BO) {
7424 // C++11 [expr.comma]p1:
7425 // Every value computation and side effect associated with the left
7426 // expression is sequenced before every value computation and side
7427 // effect associated with the right expression.
7428 SequenceTree::Seq LHS = Tree.allocate(Region);
7429 SequenceTree::Seq RHS = Tree.allocate(Region);
7430 SequenceTree::Seq OldRegion = Region;
7431
7432 {
7433 SequencedSubexpression SeqLHS(*this);
7434 Region = LHS;
7435 Visit(BO->getLHS());
7436 }
7437
7438 Region = RHS;
7439 Visit(BO->getRHS());
7440
7441 Region = OldRegion;
7442
7443 // Forget that LHS and RHS are sequenced. They are both unsequenced
7444 // with respect to other stuff.
7445 Tree.merge(LHS);
7446 Tree.merge(RHS);
7447 }
7448
7449 void VisitBinAssign(BinaryOperator *BO) {
7450 // The modification is sequenced after the value computation of the LHS
7451 // and RHS, so check it before inspecting the operands and update the
7452 // map afterwards.
7453 Object O = getObject(BO->getLHS(), true);
7454 if (!O)
7455 return VisitExpr(BO);
7456
7457 notePreMod(O, BO);
7458
7459 // C++11 [expr.ass]p7:
7460 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7461 // only once.
7462 //
7463 // Therefore, for a compound assignment operator, O is considered used
7464 // everywhere except within the evaluation of E1 itself.
7465 if (isa<CompoundAssignOperator>(BO))
7466 notePreUse(O, BO);
7467
7468 Visit(BO->getLHS());
7469
7470 if (isa<CompoundAssignOperator>(BO))
7471 notePostUse(O, BO);
7472
7473 Visit(BO->getRHS());
7474
Richard Smith83e37bee2013-06-26 23:16:51 +00007475 // C++11 [expr.ass]p1:
7476 // the assignment is sequenced [...] before the value computation of the
7477 // assignment expression.
7478 // C11 6.5.16/3 has no such rule.
7479 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7480 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007481 }
7482 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7483 VisitBinAssign(CAO);
7484 }
7485
7486 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7487 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7488 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7489 Object O = getObject(UO->getSubExpr(), true);
7490 if (!O)
7491 return VisitExpr(UO);
7492
7493 notePreMod(O, UO);
7494 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00007495 // C++11 [expr.pre.incr]p1:
7496 // the expression ++x is equivalent to x+=1
7497 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7498 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007499 }
7500
7501 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7502 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7503 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7504 Object O = getObject(UO->getSubExpr(), true);
7505 if (!O)
7506 return VisitExpr(UO);
7507
7508 notePreMod(O, UO);
7509 Visit(UO->getSubExpr());
7510 notePostMod(O, UO, UK_ModAsSideEffect);
7511 }
7512
7513 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7514 void VisitBinLOr(BinaryOperator *BO) {
7515 // The side-effects of the LHS of an '&&' are sequenced before the
7516 // value computation of the RHS, and hence before the value computation
7517 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7518 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00007519 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007520 {
7521 SequencedSubexpression Sequenced(*this);
7522 Visit(BO->getLHS());
7523 }
7524
7525 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007526 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007527 if (!Result)
7528 Visit(BO->getRHS());
7529 } else {
7530 // Check for unsequenced operations in the RHS, treating it as an
7531 // entirely separate evaluation.
7532 //
7533 // FIXME: If there are operations in the RHS which are unsequenced
7534 // with respect to operations outside the RHS, and those operations
7535 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00007536 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007537 }
Richard Smithc406cb72013-01-17 01:17:56 +00007538 }
7539 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00007540 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007541 {
7542 SequencedSubexpression Sequenced(*this);
7543 Visit(BO->getLHS());
7544 }
7545
7546 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007547 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007548 if (Result)
7549 Visit(BO->getRHS());
7550 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00007551 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007552 }
Richard Smithc406cb72013-01-17 01:17:56 +00007553 }
7554
7555 // Only visit the condition, unless we can be sure which subexpression will
7556 // be chosen.
7557 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00007558 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00007559 {
7560 SequencedSubexpression Sequenced(*this);
7561 Visit(CO->getCond());
7562 }
Richard Smithc406cb72013-01-17 01:17:56 +00007563
7564 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007565 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00007566 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007567 else {
Richard Smithd33f5202013-01-17 23:18:09 +00007568 WorkList.push_back(CO->getTrueExpr());
7569 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007570 }
Richard Smithc406cb72013-01-17 01:17:56 +00007571 }
7572
Richard Smithe3dbfe02013-06-30 10:40:20 +00007573 void VisitCallExpr(CallExpr *CE) {
7574 // C++11 [intro.execution]p15:
7575 // When calling a function [...], every value computation and side effect
7576 // associated with any argument expression, or with the postfix expression
7577 // designating the called function, is sequenced before execution of every
7578 // expression or statement in the body of the function [and thus before
7579 // the value computation of its result].
7580 SequencedSubexpression Sequenced(*this);
7581 Base::VisitCallExpr(CE);
7582
7583 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7584 }
7585
Richard Smithc406cb72013-01-17 01:17:56 +00007586 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007587 // This is a call, so all subexpressions are sequenced before the result.
7588 SequencedSubexpression Sequenced(*this);
7589
Richard Smithc406cb72013-01-17 01:17:56 +00007590 if (!CCE->isListInitialization())
7591 return VisitExpr(CCE);
7592
7593 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007594 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007595 SequenceTree::Seq Parent = Region;
7596 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7597 E = CCE->arg_end();
7598 I != E; ++I) {
7599 Region = Tree.allocate(Parent);
7600 Elts.push_back(Region);
7601 Visit(*I);
7602 }
7603
7604 // Forget that the initializers are sequenced.
7605 Region = Parent;
7606 for (unsigned I = 0; I < Elts.size(); ++I)
7607 Tree.merge(Elts[I]);
7608 }
7609
7610 void VisitInitListExpr(InitListExpr *ILE) {
7611 if (!SemaRef.getLangOpts().CPlusPlus11)
7612 return VisitExpr(ILE);
7613
7614 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007615 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007616 SequenceTree::Seq Parent = Region;
7617 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7618 Expr *E = ILE->getInit(I);
7619 if (!E) continue;
7620 Region = Tree.allocate(Parent);
7621 Elts.push_back(Region);
7622 Visit(E);
7623 }
7624
7625 // Forget that the initializers are sequenced.
7626 Region = Parent;
7627 for (unsigned I = 0; I < Elts.size(); ++I)
7628 Tree.merge(Elts[I]);
7629 }
7630};
7631}
7632
7633void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007634 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00007635 WorkList.push_back(E);
7636 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00007637 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00007638 SequenceChecker(*this, Item, WorkList);
7639 }
Richard Smithc406cb72013-01-17 01:17:56 +00007640}
7641
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007642void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7643 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007644 CheckImplicitConversions(E, CheckLoc);
7645 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007646 if (!IsConstexpr && !E->isValueDependent())
7647 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007648}
7649
John McCall1f425642010-11-11 03:21:53 +00007650void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7651 FieldDecl *BitField,
7652 Expr *Init) {
7653 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7654}
7655
Mike Stump0c2ec772010-01-21 03:59:47 +00007656/// CheckParmsForFunctionDef - Check that the parameters of the given
7657/// function are appropriate for the definition of a function. This
7658/// takes care of any checks that cannot be performed on the
7659/// declaration itself, e.g., that the types of each of the function
7660/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00007661bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7662 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00007663 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007664 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00007665 for (; P != PEnd; ++P) {
7666 ParmVarDecl *Param = *P;
7667
Mike Stump0c2ec772010-01-21 03:59:47 +00007668 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7669 // function declarator that is part of a function definition of
7670 // that function shall not have incomplete type.
7671 //
7672 // This is also C++ [dcl.fct]p6.
7673 if (!Param->isInvalidDecl() &&
7674 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007675 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007676 Param->setInvalidDecl();
7677 HasInvalidParm = true;
7678 }
7679
7680 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7681 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00007682 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00007683 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00007684 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007685 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00007686 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00007687
7688 // C99 6.7.5.3p12:
7689 // If the function declarator is not part of a definition of that
7690 // function, parameters may have incomplete type and may use the [*]
7691 // notation in their sequences of declarator specifiers to specify
7692 // variable length array types.
7693 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007694 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00007695 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00007696 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00007697 // information is added for it.
7698 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007699 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00007700 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007701 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00007702 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007703
7704 // MSVC destroys objects passed by value in the callee. Therefore a
7705 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007706 // object's destructor. However, we don't perform any direct access check
7707 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00007708 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7709 .getCXXABI()
7710 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00007711 if (!Param->isInvalidDecl()) {
7712 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7713 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7714 if (!ClassDecl->isInvalidDecl() &&
7715 !ClassDecl->hasIrrelevantDestructor() &&
7716 !ClassDecl->isDependentContext()) {
7717 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7718 MarkFunctionReferenced(Param->getLocation(), Destructor);
7719 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7720 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007721 }
7722 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007723 }
Mike Stump0c2ec772010-01-21 03:59:47 +00007724 }
7725
7726 return HasInvalidParm;
7727}
John McCall2b5c1b22010-08-12 21:44:57 +00007728
7729/// CheckCastAlign - Implements -Wcast-align, which warns when a
7730/// pointer cast increases the alignment requirements.
7731void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7732 // This is actually a lot of work to potentially be doing on every
7733 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007734 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00007735 return;
7736
7737 // Ignore dependent types.
7738 if (T->isDependentType() || Op->getType()->isDependentType())
7739 return;
7740
7741 // Require that the destination be a pointer type.
7742 const PointerType *DestPtr = T->getAs<PointerType>();
7743 if (!DestPtr) return;
7744
7745 // If the destination has alignment 1, we're done.
7746 QualType DestPointee = DestPtr->getPointeeType();
7747 if (DestPointee->isIncompleteType()) return;
7748 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7749 if (DestAlign.isOne()) return;
7750
7751 // Require that the source be a pointer type.
7752 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7753 if (!SrcPtr) return;
7754 QualType SrcPointee = SrcPtr->getPointeeType();
7755
7756 // Whitelist casts from cv void*. We already implicitly
7757 // whitelisted casts to cv void*, since they have alignment 1.
7758 // Also whitelist casts involving incomplete types, which implicitly
7759 // includes 'void'.
7760 if (SrcPointee->isIncompleteType()) return;
7761
7762 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7763 if (SrcAlign >= DestAlign) return;
7764
7765 Diag(TRange.getBegin(), diag::warn_cast_align)
7766 << Op->getType() << T
7767 << static_cast<unsigned>(SrcAlign.getQuantity())
7768 << static_cast<unsigned>(DestAlign.getQuantity())
7769 << TRange << Op->getSourceRange();
7770}
7771
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007772static const Type* getElementType(const Expr *BaseExpr) {
7773 const Type* EltType = BaseExpr->getType().getTypePtr();
7774 if (EltType->isAnyPointerType())
7775 return EltType->getPointeeType().getTypePtr();
7776 else if (EltType->isArrayType())
7777 return EltType->getBaseElementTypeUnsafe();
7778 return EltType;
7779}
7780
Chandler Carruth28389f02011-08-05 09:10:50 +00007781/// \brief Check whether this array fits the idiom of a size-one tail padded
7782/// array member of a struct.
7783///
7784/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7785/// commonly used to emulate flexible arrays in C89 code.
7786static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7787 const NamedDecl *ND) {
7788 if (Size != 1 || !ND) return false;
7789
7790 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7791 if (!FD) return false;
7792
7793 // Don't consider sizes resulting from macro expansions or template argument
7794 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00007795
7796 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007797 while (TInfo) {
7798 TypeLoc TL = TInfo->getTypeLoc();
7799 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007800 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7801 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007802 TInfo = TDL->getTypeSourceInfo();
7803 continue;
7804 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007805 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7806 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007807 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7808 return false;
7809 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007810 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007811 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007812
7813 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007814 if (!RD) return false;
7815 if (RD->isUnion()) return false;
7816 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7817 if (!CRD->isStandardLayout()) return false;
7818 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007819
Benjamin Kramer8c543672011-08-06 03:04:42 +00007820 // See if this is the last field decl in the record.
7821 const Decl *D = FD;
7822 while ((D = D->getNextDeclInContext()))
7823 if (isa<FieldDecl>(D))
7824 return false;
7825 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007826}
7827
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007828void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007829 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007830 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007831 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007832 if (IndexExpr->isValueDependent())
7833 return;
7834
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007835 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007836 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007837 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007838 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007839 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007840 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007841
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007842 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007843 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007844 return;
Richard Smith13f67182011-12-16 19:31:14 +00007845 if (IndexNegated)
7846 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007847
Craig Topperc3ec1492014-05-26 06:22:03 +00007848 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007849 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7850 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007851 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007852 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007853
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007854 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007855 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007856 if (!size.isStrictlyPositive())
7857 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007858
7859 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007860 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007861 // Make sure we're comparing apples to apples when comparing index to size
7862 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7863 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007864 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007865 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007866 if (ptrarith_typesize != array_typesize) {
7867 // There's a cast to a different size type involved
7868 uint64_t ratio = array_typesize / ptrarith_typesize;
7869 // TODO: Be smarter about handling cases where array_typesize is not a
7870 // multiple of ptrarith_typesize
7871 if (ptrarith_typesize * ratio == array_typesize)
7872 size *= llvm::APInt(size.getBitWidth(), ratio);
7873 }
7874 }
7875
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007876 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007877 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007878 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007879 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007880
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007881 // For array subscripting the index must be less than size, but for pointer
7882 // arithmetic also allow the index (offset) to be equal to size since
7883 // computing the next address after the end of the array is legal and
7884 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007885 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007886 return;
7887
7888 // Also don't warn for arrays of size 1 which are members of some
7889 // structure. These are often used to approximate flexible arrays in C89
7890 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007891 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007892 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007893
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007894 // Suppress the warning if the subscript expression (as identified by the
7895 // ']' location) and the index expression are both from macro expansions
7896 // within a system header.
7897 if (ASE) {
7898 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7899 ASE->getRBracketLoc());
7900 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7901 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7902 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007903 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007904 return;
7905 }
7906 }
7907
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007908 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007909 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007910 DiagID = diag::warn_array_index_exceeds_bounds;
7911
7912 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7913 PDiag(DiagID) << index.toString(10, true)
7914 << size.toString(10, true)
7915 << (unsigned)size.getLimitedValue(~0U)
7916 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007917 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007918 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007919 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007920 DiagID = diag::warn_ptr_arith_precedes_bounds;
7921 if (index.isNegative()) index = -index;
7922 }
7923
7924 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7925 PDiag(DiagID) << index.toString(10, true)
7926 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007927 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007928
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007929 if (!ND) {
7930 // Try harder to find a NamedDecl to point at in the note.
7931 while (const ArraySubscriptExpr *ASE =
7932 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7933 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7934 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7935 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7936 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7937 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7938 }
7939
Chandler Carruth1af88f12011-02-17 21:10:52 +00007940 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007941 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7942 PDiag(diag::note_array_index_out_of_bounds)
7943 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007944}
7945
Ted Kremenekdf26df72011-03-01 18:41:00 +00007946void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007947 int AllowOnePastEnd = 0;
7948 while (expr) {
7949 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007950 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007951 case Stmt::ArraySubscriptExprClass: {
7952 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007953 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007954 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007955 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007956 }
7957 case Stmt::UnaryOperatorClass: {
7958 // Only unwrap the * and & unary operators
7959 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7960 expr = UO->getSubExpr();
7961 switch (UO->getOpcode()) {
7962 case UO_AddrOf:
7963 AllowOnePastEnd++;
7964 break;
7965 case UO_Deref:
7966 AllowOnePastEnd--;
7967 break;
7968 default:
7969 return;
7970 }
7971 break;
7972 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007973 case Stmt::ConditionalOperatorClass: {
7974 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7975 if (const Expr *lhs = cond->getLHS())
7976 CheckArrayAccess(lhs);
7977 if (const Expr *rhs = cond->getRHS())
7978 CheckArrayAccess(rhs);
7979 return;
7980 }
7981 default:
7982 return;
7983 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007984 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007985}
John McCall31168b02011-06-15 23:02:42 +00007986
7987//===--- CHECK: Objective-C retain cycles ----------------------------------//
7988
7989namespace {
7990 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00007991 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00007992 VarDecl *Variable;
7993 SourceRange Range;
7994 SourceLocation Loc;
7995 bool Indirect;
7996
7997 void setLocsFrom(Expr *e) {
7998 Loc = e->getExprLoc();
7999 Range = e->getSourceRange();
8000 }
8001 };
8002}
8003
8004/// Consider whether capturing the given variable can possibly lead to
8005/// a retain cycle.
8006static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00008007 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00008008 // lifetime. In MRR, it's captured strongly if the variable is
8009 // __block and has an appropriate type.
8010 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8011 return false;
8012
8013 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008014 if (ref)
8015 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00008016 return true;
8017}
8018
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008019static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00008020 while (true) {
8021 e = e->IgnoreParens();
8022 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
8023 switch (cast->getCastKind()) {
8024 case CK_BitCast:
8025 case CK_LValueBitCast:
8026 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00008027 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00008028 e = cast->getSubExpr();
8029 continue;
8030
John McCall31168b02011-06-15 23:02:42 +00008031 default:
8032 return false;
8033 }
8034 }
8035
8036 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
8037 ObjCIvarDecl *ivar = ref->getDecl();
8038 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8039 return false;
8040
8041 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008042 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00008043 return false;
8044
8045 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8046 owner.Indirect = true;
8047 return true;
8048 }
8049
8050 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8051 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8052 if (!var) return false;
8053 return considerVariable(var, ref, owner);
8054 }
8055
John McCall31168b02011-06-15 23:02:42 +00008056 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8057 if (member->isArrow()) return false;
8058
8059 // Don't count this as an indirect ownership.
8060 e = member->getBase();
8061 continue;
8062 }
8063
John McCallfe96e0b2011-11-06 09:01:30 +00008064 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8065 // Only pay attention to pseudo-objects on property references.
8066 ObjCPropertyRefExpr *pre
8067 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8068 ->IgnoreParens());
8069 if (!pre) return false;
8070 if (pre->isImplicitProperty()) return false;
8071 ObjCPropertyDecl *property = pre->getExplicitProperty();
8072 if (!property->isRetaining() &&
8073 !(property->getPropertyIvarDecl() &&
8074 property->getPropertyIvarDecl()->getType()
8075 .getObjCLifetime() == Qualifiers::OCL_Strong))
8076 return false;
8077
8078 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008079 if (pre->isSuperReceiver()) {
8080 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8081 if (!owner.Variable)
8082 return false;
8083 owner.Loc = pre->getLocation();
8084 owner.Range = pre->getSourceRange();
8085 return true;
8086 }
John McCallfe96e0b2011-11-06 09:01:30 +00008087 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8088 ->getSourceExpr());
8089 continue;
8090 }
8091
John McCall31168b02011-06-15 23:02:42 +00008092 // Array ivars?
8093
8094 return false;
8095 }
8096}
8097
8098namespace {
8099 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8100 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8101 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008102 Context(Context), Variable(variable), Capturer(nullptr),
8103 VarWillBeReased(false) {}
8104 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00008105 VarDecl *Variable;
8106 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008107 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00008108
8109 void VisitDeclRefExpr(DeclRefExpr *ref) {
8110 if (ref->getDecl() == Variable && !Capturer)
8111 Capturer = ref;
8112 }
8113
John McCall31168b02011-06-15 23:02:42 +00008114 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8115 if (Capturer) return;
8116 Visit(ref->getBase());
8117 if (Capturer && ref->isFreeIvar())
8118 Capturer = ref;
8119 }
8120
8121 void VisitBlockExpr(BlockExpr *block) {
8122 // Look inside nested blocks
8123 if (block->getBlockDecl()->capturesVariable(Variable))
8124 Visit(block->getBlockDecl()->getBody());
8125 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00008126
8127 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8128 if (Capturer) return;
8129 if (OVE->getSourceExpr())
8130 Visit(OVE->getSourceExpr());
8131 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008132 void VisitBinaryOperator(BinaryOperator *BinOp) {
8133 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8134 return;
8135 Expr *LHS = BinOp->getLHS();
8136 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8137 if (DRE->getDecl() != Variable)
8138 return;
8139 if (Expr *RHS = BinOp->getRHS()) {
8140 RHS = RHS->IgnoreParenCasts();
8141 llvm::APSInt Value;
8142 VarWillBeReased =
8143 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8144 }
8145 }
8146 }
John McCall31168b02011-06-15 23:02:42 +00008147 };
8148}
8149
8150/// Check whether the given argument is a block which captures a
8151/// variable.
8152static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8153 assert(owner.Variable && owner.Loc.isValid());
8154
8155 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00008156
8157 // Look through [^{...} copy] and Block_copy(^{...}).
8158 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8159 Selector Cmd = ME->getSelector();
8160 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8161 e = ME->getInstanceReceiver();
8162 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00008163 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00008164 e = e->IgnoreParenCasts();
8165 }
8166 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8167 if (CE->getNumArgs() == 1) {
8168 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00008169 if (Fn) {
8170 const IdentifierInfo *FnI = Fn->getIdentifier();
8171 if (FnI && FnI->isStr("_Block_copy")) {
8172 e = CE->getArg(0)->IgnoreParenCasts();
8173 }
8174 }
Jordan Rose67e887c2012-09-17 17:54:30 +00008175 }
8176 }
8177
John McCall31168b02011-06-15 23:02:42 +00008178 BlockExpr *block = dyn_cast<BlockExpr>(e);
8179 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00008180 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00008181
8182 FindCaptureVisitor visitor(S.Context, owner.Variable);
8183 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008184 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00008185}
8186
8187static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8188 RetainCycleOwner &owner) {
8189 assert(capturer);
8190 assert(owner.Variable && owner.Loc.isValid());
8191
8192 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8193 << owner.Variable << capturer->getSourceRange();
8194 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8195 << owner.Indirect << owner.Range;
8196}
8197
8198/// Check for a keyword selector that starts with the word 'add' or
8199/// 'set'.
8200static bool isSetterLikeSelector(Selector sel) {
8201 if (sel.isUnarySelector()) return false;
8202
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008203 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00008204 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008205 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00008206 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008207 else if (str.startswith("add")) {
8208 // Specially whitelist 'addOperationWithBlock:'.
8209 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8210 return false;
8211 str = str.substr(3);
8212 }
John McCall31168b02011-06-15 23:02:42 +00008213 else
8214 return false;
8215
8216 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00008217 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00008218}
8219
Benjamin Kramer3a743452015-03-09 15:03:32 +00008220static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
8221 ObjCMessageExpr *Message) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008222 if (S.NSMutableArrayPointer.isNull()) {
8223 IdentifierInfo *NSMutableArrayId =
8224 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableArray);
8225 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableArrayId,
8226 Message->getLocStart(),
8227 Sema::LookupOrdinaryName);
8228 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8229 if (!InterfaceDecl) {
8230 return None;
8231 }
8232 QualType NSMutableArrayObject =
8233 S.Context.getObjCInterfaceType(InterfaceDecl);
8234 S.NSMutableArrayPointer =
8235 S.Context.getObjCObjectPointerType(NSMutableArrayObject);
8236 }
8237
8238 if (S.NSMutableArrayPointer != Message->getReceiverType()) {
8239 return None;
8240 }
8241
8242 Selector Sel = Message->getSelector();
8243
8244 Optional<NSAPI::NSArrayMethodKind> MKOpt =
8245 S.NSAPIObj->getNSArrayMethodKind(Sel);
8246 if (!MKOpt) {
8247 return None;
8248 }
8249
8250 NSAPI::NSArrayMethodKind MK = *MKOpt;
8251
8252 switch (MK) {
8253 case NSAPI::NSMutableArr_addObject:
8254 case NSAPI::NSMutableArr_insertObjectAtIndex:
8255 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
8256 return 0;
8257 case NSAPI::NSMutableArr_replaceObjectAtIndex:
8258 return 1;
8259
8260 default:
8261 return None;
8262 }
8263
8264 return None;
8265}
8266
8267static
8268Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
8269 ObjCMessageExpr *Message) {
8270
8271 if (S.NSMutableDictionaryPointer.isNull()) {
8272 IdentifierInfo *NSMutableDictionaryId =
8273 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableDictionary);
8274 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableDictionaryId,
8275 Message->getLocStart(),
8276 Sema::LookupOrdinaryName);
8277 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8278 if (!InterfaceDecl) {
8279 return None;
8280 }
8281 QualType NSMutableDictionaryObject =
8282 S.Context.getObjCInterfaceType(InterfaceDecl);
8283 S.NSMutableDictionaryPointer =
8284 S.Context.getObjCObjectPointerType(NSMutableDictionaryObject);
8285 }
8286
8287 if (S.NSMutableDictionaryPointer != Message->getReceiverType()) {
8288 return None;
8289 }
8290
8291 Selector Sel = Message->getSelector();
8292
8293 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
8294 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
8295 if (!MKOpt) {
8296 return None;
8297 }
8298
8299 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
8300
8301 switch (MK) {
8302 case NSAPI::NSMutableDict_setObjectForKey:
8303 case NSAPI::NSMutableDict_setValueForKey:
8304 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
8305 return 0;
8306
8307 default:
8308 return None;
8309 }
8310
8311 return None;
8312}
8313
8314static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
8315
8316 ObjCInterfaceDecl *InterfaceDecl;
8317 if (S.NSMutableSetPointer.isNull()) {
8318 IdentifierInfo *NSMutableSetId =
8319 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableSet);
8320 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableSetId,
8321 Message->getLocStart(),
8322 Sema::LookupOrdinaryName);
8323 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8324 if (InterfaceDecl) {
8325 QualType NSMutableSetObject =
8326 S.Context.getObjCInterfaceType(InterfaceDecl);
8327 S.NSMutableSetPointer =
8328 S.Context.getObjCObjectPointerType(NSMutableSetObject);
8329 }
8330 }
8331
8332 if (S.NSCountedSetPointer.isNull()) {
8333 IdentifierInfo *NSCountedSetId =
8334 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSCountedSet);
8335 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSCountedSetId,
8336 Message->getLocStart(),
8337 Sema::LookupOrdinaryName);
8338 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8339 if (InterfaceDecl) {
8340 QualType NSCountedSetObject =
8341 S.Context.getObjCInterfaceType(InterfaceDecl);
8342 S.NSCountedSetPointer =
8343 S.Context.getObjCObjectPointerType(NSCountedSetObject);
8344 }
8345 }
8346
8347 if (S.NSMutableOrderedSetPointer.isNull()) {
8348 IdentifierInfo *NSOrderedSetId =
8349 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableOrderedSet);
8350 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSOrderedSetId,
8351 Message->getLocStart(),
8352 Sema::LookupOrdinaryName);
8353 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8354 if (InterfaceDecl) {
8355 QualType NSOrderedSetObject =
8356 S.Context.getObjCInterfaceType(InterfaceDecl);
8357 S.NSMutableOrderedSetPointer =
8358 S.Context.getObjCObjectPointerType(NSOrderedSetObject);
8359 }
8360 }
8361
8362 QualType ReceiverType = Message->getReceiverType();
8363
8364 bool IsMutableSet = !S.NSMutableSetPointer.isNull() &&
8365 ReceiverType == S.NSMutableSetPointer;
8366 bool IsMutableOrderedSet = !S.NSMutableOrderedSetPointer.isNull() &&
8367 ReceiverType == S.NSMutableOrderedSetPointer;
8368 bool IsCountedSet = !S.NSCountedSetPointer.isNull() &&
8369 ReceiverType == S.NSCountedSetPointer;
8370
8371 if (!IsMutableSet && !IsMutableOrderedSet && !IsCountedSet) {
8372 return None;
8373 }
8374
8375 Selector Sel = Message->getSelector();
8376
8377 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
8378 if (!MKOpt) {
8379 return None;
8380 }
8381
8382 NSAPI::NSSetMethodKind MK = *MKOpt;
8383
8384 switch (MK) {
8385 case NSAPI::NSMutableSet_addObject:
8386 case NSAPI::NSOrderedSet_setObjectAtIndex:
8387 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
8388 case NSAPI::NSOrderedSet_insertObjectAtIndex:
8389 return 0;
8390 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
8391 return 1;
8392 }
8393
8394 return None;
8395}
8396
8397void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
8398 if (!Message->isInstanceMessage()) {
8399 return;
8400 }
8401
8402 Optional<int> ArgOpt;
8403
8404 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
8405 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
8406 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
8407 return;
8408 }
8409
8410 int ArgIndex = *ArgOpt;
8411
8412 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
8413 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
8414 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
8415 }
8416
8417 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
8418 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
8419 Arg = OE->getSourceExpr()->IgnoreImpCasts();
8420 }
8421
8422 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
8423 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
8424 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
8425 ValueDecl *Decl = ReceiverRE->getDecl();
8426 Diag(Message->getSourceRange().getBegin(),
8427 diag::warn_objc_circular_container)
8428 << Decl->getName();
8429 Diag(Decl->getLocation(),
8430 diag::note_objc_circular_container_declared_here)
8431 << Decl->getName();
8432 }
8433 }
8434 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
8435 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
8436 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
8437 ObjCIvarDecl *Decl = IvarRE->getDecl();
8438 Diag(Message->getSourceRange().getBegin(),
8439 diag::warn_objc_circular_container)
8440 << Decl->getName();
8441 Diag(Decl->getLocation(),
8442 diag::note_objc_circular_container_declared_here)
8443 << Decl->getName();
8444 }
8445 }
8446 }
8447
8448}
8449
John McCall31168b02011-06-15 23:02:42 +00008450/// Check a message send to see if it's likely to cause a retain cycle.
8451void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8452 // Only check instance methods whose selector looks like a setter.
8453 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8454 return;
8455
8456 // Try to find a variable that the receiver is strongly owned by.
8457 RetainCycleOwner owner;
8458 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008459 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00008460 return;
8461 } else {
8462 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8463 owner.Variable = getCurMethodDecl()->getSelfDecl();
8464 owner.Loc = msg->getSuperLoc();
8465 owner.Range = msg->getSuperLoc();
8466 }
8467
8468 // Check whether the receiver is captured by any of the arguments.
8469 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
8470 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
8471 return diagnoseRetainCycle(*this, capturer, owner);
8472}
8473
8474/// Check a property assign to see if it's likely to cause a retain cycle.
8475void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
8476 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008477 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00008478 return;
8479
8480 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
8481 diagnoseRetainCycle(*this, capturer, owner);
8482}
8483
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008484void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
8485 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00008486 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008487 return;
8488
8489 // Because we don't have an expression for the variable, we have to set the
8490 // location explicitly here.
8491 Owner.Loc = Var->getLocation();
8492 Owner.Range = Var->getSourceRange();
8493
8494 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8495 diagnoseRetainCycle(*this, Capturer, Owner);
8496}
8497
Ted Kremenek9304da92012-12-21 08:04:28 +00008498static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8499 Expr *RHS, bool isProperty) {
8500 // Check if RHS is an Objective-C object literal, which also can get
8501 // immediately zapped in a weak reference. Note that we explicitly
8502 // allow ObjCStringLiterals, since those are designed to never really die.
8503 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008504
Ted Kremenek64873352012-12-21 22:46:35 +00008505 // This enum needs to match with the 'select' in
8506 // warn_objc_arc_literal_assign (off-by-1).
8507 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8508 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8509 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008510
8511 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00008512 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00008513 << (isProperty ? 0 : 1)
8514 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008515
8516 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00008517}
8518
Ted Kremenekc1f014a2012-12-21 19:45:30 +00008519static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8520 Qualifiers::ObjCLifetime LT,
8521 Expr *RHS, bool isProperty) {
8522 // Strip off any implicit cast added to get to the one ARC-specific.
8523 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8524 if (cast->getCastKind() == CK_ARCConsumeObject) {
8525 S.Diag(Loc, diag::warn_arc_retained_assign)
8526 << (LT == Qualifiers::OCL_ExplicitNone)
8527 << (isProperty ? 0 : 1)
8528 << RHS->getSourceRange();
8529 return true;
8530 }
8531 RHS = cast->getSubExpr();
8532 }
8533
8534 if (LT == Qualifiers::OCL_Weak &&
8535 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8536 return true;
8537
8538 return false;
8539}
8540
Ted Kremenekb36234d2012-12-21 08:04:20 +00008541bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8542 QualType LHS, Expr *RHS) {
8543 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8544
8545 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8546 return false;
8547
8548 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8549 return true;
8550
8551 return false;
8552}
8553
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008554void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8555 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008556 QualType LHSType;
8557 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00008558 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008559 ObjCPropertyRefExpr *PRE
8560 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8561 if (PRE && !PRE->isImplicitProperty()) {
8562 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8563 if (PD)
8564 LHSType = PD->getType();
8565 }
8566
8567 if (LHSType.isNull())
8568 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00008569
8570 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8571
8572 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008573 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00008574 getCurFunction()->markSafeWeakUse(LHS);
8575 }
8576
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008577 if (checkUnsafeAssigns(Loc, LHSType, RHS))
8578 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00008579
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008580 // FIXME. Check for other life times.
8581 if (LT != Qualifiers::OCL_None)
8582 return;
8583
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008584 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008585 if (PRE->isImplicitProperty())
8586 return;
8587 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8588 if (!PD)
8589 return;
8590
Bill Wendling44426052012-12-20 19:22:21 +00008591 unsigned Attributes = PD->getPropertyAttributes();
8592 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008593 // when 'assign' attribute was not explicitly specified
8594 // by user, ignore it and rely on property type itself
8595 // for lifetime info.
8596 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
8597 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
8598 LHSType->isObjCRetainableType())
8599 return;
8600
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008601 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00008602 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008603 Diag(Loc, diag::warn_arc_retained_property_assign)
8604 << RHS->getSourceRange();
8605 return;
8606 }
8607 RHS = cast->getSubExpr();
8608 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008609 }
Bill Wendling44426052012-12-20 19:22:21 +00008610 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00008611 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
8612 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00008613 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008614 }
8615}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008616
8617//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8618
8619namespace {
8620bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8621 SourceLocation StmtLoc,
8622 const NullStmt *Body) {
8623 // Do not warn if the body is a macro that expands to nothing, e.g:
8624 //
8625 // #define CALL(x)
8626 // if (condition)
8627 // CALL(0);
8628 //
8629 if (Body->hasLeadingEmptyMacro())
8630 return false;
8631
8632 // Get line numbers of statement and body.
8633 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +00008634 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008635 &StmtLineInvalid);
8636 if (StmtLineInvalid)
8637 return false;
8638
8639 bool BodyLineInvalid;
8640 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8641 &BodyLineInvalid);
8642 if (BodyLineInvalid)
8643 return false;
8644
8645 // Warn if null statement and body are on the same line.
8646 if (StmtLine != BodyLine)
8647 return false;
8648
8649 return true;
8650}
8651} // Unnamed namespace
8652
8653void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8654 const Stmt *Body,
8655 unsigned DiagID) {
8656 // Since this is a syntactic check, don't emit diagnostic for template
8657 // instantiations, this just adds noise.
8658 if (CurrentInstantiationScope)
8659 return;
8660
8661 // The body should be a null statement.
8662 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8663 if (!NBody)
8664 return;
8665
8666 // Do the usual checks.
8667 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8668 return;
8669
8670 Diag(NBody->getSemiLoc(), DiagID);
8671 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8672}
8673
8674void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8675 const Stmt *PossibleBody) {
8676 assert(!CurrentInstantiationScope); // Ensured by caller
8677
8678 SourceLocation StmtLoc;
8679 const Stmt *Body;
8680 unsigned DiagID;
8681 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8682 StmtLoc = FS->getRParenLoc();
8683 Body = FS->getBody();
8684 DiagID = diag::warn_empty_for_body;
8685 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8686 StmtLoc = WS->getCond()->getSourceRange().getEnd();
8687 Body = WS->getBody();
8688 DiagID = diag::warn_empty_while_body;
8689 } else
8690 return; // Neither `for' nor `while'.
8691
8692 // The body should be a null statement.
8693 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8694 if (!NBody)
8695 return;
8696
8697 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008698 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008699 return;
8700
8701 // Do the usual checks.
8702 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8703 return;
8704
8705 // `for(...);' and `while(...);' are popular idioms, so in order to keep
8706 // noise level low, emit diagnostics only if for/while is followed by a
8707 // CompoundStmt, e.g.:
8708 // for (int i = 0; i < n; i++);
8709 // {
8710 // a(i);
8711 // }
8712 // or if for/while is followed by a statement with more indentation
8713 // than for/while itself:
8714 // for (int i = 0; i < n; i++);
8715 // a(i);
8716 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8717 if (!ProbableTypo) {
8718 bool BodyColInvalid;
8719 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8720 PossibleBody->getLocStart(),
8721 &BodyColInvalid);
8722 if (BodyColInvalid)
8723 return;
8724
8725 bool StmtColInvalid;
8726 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8727 S->getLocStart(),
8728 &StmtColInvalid);
8729 if (StmtColInvalid)
8730 return;
8731
8732 if (BodyCol > StmtCol)
8733 ProbableTypo = true;
8734 }
8735
8736 if (ProbableTypo) {
8737 Diag(NBody->getSemiLoc(), DiagID);
8738 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8739 }
8740}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008741
Richard Trieu36d0b2b2015-01-13 02:32:02 +00008742//===--- CHECK: Warn on self move with std::move. -------------------------===//
8743
8744/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
8745void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
8746 SourceLocation OpLoc) {
8747
8748 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
8749 return;
8750
8751 if (!ActiveTemplateInstantiations.empty())
8752 return;
8753
8754 // Strip parens and casts away.
8755 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8756 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8757
8758 // Check for a call expression
8759 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
8760 if (!CE || CE->getNumArgs() != 1)
8761 return;
8762
8763 // Check for a call to std::move
8764 const FunctionDecl *FD = CE->getDirectCallee();
8765 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
8766 !FD->getIdentifier()->isStr("move"))
8767 return;
8768
8769 // Get argument from std::move
8770 RHSExpr = CE->getArg(0);
8771
8772 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8773 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8774
8775 // Two DeclRefExpr's, check that the decls are the same.
8776 if (LHSDeclRef && RHSDeclRef) {
8777 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8778 return;
8779 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8780 RHSDeclRef->getDecl()->getCanonicalDecl())
8781 return;
8782
8783 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8784 << LHSExpr->getSourceRange()
8785 << RHSExpr->getSourceRange();
8786 return;
8787 }
8788
8789 // Member variables require a different approach to check for self moves.
8790 // MemberExpr's are the same if every nested MemberExpr refers to the same
8791 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
8792 // the base Expr's are CXXThisExpr's.
8793 const Expr *LHSBase = LHSExpr;
8794 const Expr *RHSBase = RHSExpr;
8795 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
8796 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
8797 if (!LHSME || !RHSME)
8798 return;
8799
8800 while (LHSME && RHSME) {
8801 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
8802 RHSME->getMemberDecl()->getCanonicalDecl())
8803 return;
8804
8805 LHSBase = LHSME->getBase();
8806 RHSBase = RHSME->getBase();
8807 LHSME = dyn_cast<MemberExpr>(LHSBase);
8808 RHSME = dyn_cast<MemberExpr>(RHSBase);
8809 }
8810
8811 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
8812 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
8813 if (LHSDeclRef && RHSDeclRef) {
8814 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8815 return;
8816 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8817 RHSDeclRef->getDecl()->getCanonicalDecl())
8818 return;
8819
8820 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8821 << LHSExpr->getSourceRange()
8822 << RHSExpr->getSourceRange();
8823 return;
8824 }
8825
8826 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
8827 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8828 << LHSExpr->getSourceRange()
8829 << RHSExpr->getSourceRange();
8830}
8831
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008832//===--- Layout compatibility ----------------------------------------------//
8833
8834namespace {
8835
8836bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8837
8838/// \brief Check if two enumeration types are layout-compatible.
8839bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8840 // C++11 [dcl.enum] p8:
8841 // Two enumeration types are layout-compatible if they have the same
8842 // underlying type.
8843 return ED1->isComplete() && ED2->isComplete() &&
8844 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8845}
8846
8847/// \brief Check if two fields are layout-compatible.
8848bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8849 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8850 return false;
8851
8852 if (Field1->isBitField() != Field2->isBitField())
8853 return false;
8854
8855 if (Field1->isBitField()) {
8856 // Make sure that the bit-fields are the same length.
8857 unsigned Bits1 = Field1->getBitWidthValue(C);
8858 unsigned Bits2 = Field2->getBitWidthValue(C);
8859
8860 if (Bits1 != Bits2)
8861 return false;
8862 }
8863
8864 return true;
8865}
8866
8867/// \brief Check if two standard-layout structs are layout-compatible.
8868/// (C++11 [class.mem] p17)
8869bool isLayoutCompatibleStruct(ASTContext &C,
8870 RecordDecl *RD1,
8871 RecordDecl *RD2) {
8872 // If both records are C++ classes, check that base classes match.
8873 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
8874 // If one of records is a CXXRecordDecl we are in C++ mode,
8875 // thus the other one is a CXXRecordDecl, too.
8876 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
8877 // Check number of base classes.
8878 if (D1CXX->getNumBases() != D2CXX->getNumBases())
8879 return false;
8880
8881 // Check the base classes.
8882 for (CXXRecordDecl::base_class_const_iterator
8883 Base1 = D1CXX->bases_begin(),
8884 BaseEnd1 = D1CXX->bases_end(),
8885 Base2 = D2CXX->bases_begin();
8886 Base1 != BaseEnd1;
8887 ++Base1, ++Base2) {
8888 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
8889 return false;
8890 }
8891 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
8892 // If only RD2 is a C++ class, it should have zero base classes.
8893 if (D2CXX->getNumBases() > 0)
8894 return false;
8895 }
8896
8897 // Check the fields.
8898 RecordDecl::field_iterator Field2 = RD2->field_begin(),
8899 Field2End = RD2->field_end(),
8900 Field1 = RD1->field_begin(),
8901 Field1End = RD1->field_end();
8902 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
8903 if (!isLayoutCompatible(C, *Field1, *Field2))
8904 return false;
8905 }
8906 if (Field1 != Field1End || Field2 != Field2End)
8907 return false;
8908
8909 return true;
8910}
8911
8912/// \brief Check if two standard-layout unions are layout-compatible.
8913/// (C++11 [class.mem] p18)
8914bool isLayoutCompatibleUnion(ASTContext &C,
8915 RecordDecl *RD1,
8916 RecordDecl *RD2) {
8917 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008918 for (auto *Field2 : RD2->fields())
8919 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008920
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008921 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008922 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
8923 I = UnmatchedFields.begin(),
8924 E = UnmatchedFields.end();
8925
8926 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008927 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008928 bool Result = UnmatchedFields.erase(*I);
8929 (void) Result;
8930 assert(Result);
8931 break;
8932 }
8933 }
8934 if (I == E)
8935 return false;
8936 }
8937
8938 return UnmatchedFields.empty();
8939}
8940
8941bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
8942 if (RD1->isUnion() != RD2->isUnion())
8943 return false;
8944
8945 if (RD1->isUnion())
8946 return isLayoutCompatibleUnion(C, RD1, RD2);
8947 else
8948 return isLayoutCompatibleStruct(C, RD1, RD2);
8949}
8950
8951/// \brief Check if two types are layout-compatible in C++11 sense.
8952bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
8953 if (T1.isNull() || T2.isNull())
8954 return false;
8955
8956 // C++11 [basic.types] p11:
8957 // If two types T1 and T2 are the same type, then T1 and T2 are
8958 // layout-compatible types.
8959 if (C.hasSameType(T1, T2))
8960 return true;
8961
8962 T1 = T1.getCanonicalType().getUnqualifiedType();
8963 T2 = T2.getCanonicalType().getUnqualifiedType();
8964
8965 const Type::TypeClass TC1 = T1->getTypeClass();
8966 const Type::TypeClass TC2 = T2->getTypeClass();
8967
8968 if (TC1 != TC2)
8969 return false;
8970
8971 if (TC1 == Type::Enum) {
8972 return isLayoutCompatible(C,
8973 cast<EnumType>(T1)->getDecl(),
8974 cast<EnumType>(T2)->getDecl());
8975 } else if (TC1 == Type::Record) {
8976 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
8977 return false;
8978
8979 return isLayoutCompatible(C,
8980 cast<RecordType>(T1)->getDecl(),
8981 cast<RecordType>(T2)->getDecl());
8982 }
8983
8984 return false;
8985}
8986}
8987
8988//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
8989
8990namespace {
8991/// \brief Given a type tag expression find the type tag itself.
8992///
8993/// \param TypeExpr Type tag expression, as it appears in user's code.
8994///
8995/// \param VD Declaration of an identifier that appears in a type tag.
8996///
8997/// \param MagicValue Type tag magic value.
8998bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
8999 const ValueDecl **VD, uint64_t *MagicValue) {
9000 while(true) {
9001 if (!TypeExpr)
9002 return false;
9003
9004 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
9005
9006 switch (TypeExpr->getStmtClass()) {
9007 case Stmt::UnaryOperatorClass: {
9008 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
9009 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
9010 TypeExpr = UO->getSubExpr();
9011 continue;
9012 }
9013 return false;
9014 }
9015
9016 case Stmt::DeclRefExprClass: {
9017 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
9018 *VD = DRE->getDecl();
9019 return true;
9020 }
9021
9022 case Stmt::IntegerLiteralClass: {
9023 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
9024 llvm::APInt MagicValueAPInt = IL->getValue();
9025 if (MagicValueAPInt.getActiveBits() <= 64) {
9026 *MagicValue = MagicValueAPInt.getZExtValue();
9027 return true;
9028 } else
9029 return false;
9030 }
9031
9032 case Stmt::BinaryConditionalOperatorClass:
9033 case Stmt::ConditionalOperatorClass: {
9034 const AbstractConditionalOperator *ACO =
9035 cast<AbstractConditionalOperator>(TypeExpr);
9036 bool Result;
9037 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
9038 if (Result)
9039 TypeExpr = ACO->getTrueExpr();
9040 else
9041 TypeExpr = ACO->getFalseExpr();
9042 continue;
9043 }
9044 return false;
9045 }
9046
9047 case Stmt::BinaryOperatorClass: {
9048 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
9049 if (BO->getOpcode() == BO_Comma) {
9050 TypeExpr = BO->getRHS();
9051 continue;
9052 }
9053 return false;
9054 }
9055
9056 default:
9057 return false;
9058 }
9059 }
9060}
9061
9062/// \brief Retrieve the C type corresponding to type tag TypeExpr.
9063///
9064/// \param TypeExpr Expression that specifies a type tag.
9065///
9066/// \param MagicValues Registered magic values.
9067///
9068/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
9069/// kind.
9070///
9071/// \param TypeInfo Information about the corresponding C type.
9072///
9073/// \returns true if the corresponding C type was found.
9074bool GetMatchingCType(
9075 const IdentifierInfo *ArgumentKind,
9076 const Expr *TypeExpr, const ASTContext &Ctx,
9077 const llvm::DenseMap<Sema::TypeTagMagicValue,
9078 Sema::TypeTagData> *MagicValues,
9079 bool &FoundWrongKind,
9080 Sema::TypeTagData &TypeInfo) {
9081 FoundWrongKind = false;
9082
9083 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00009084 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009085
9086 uint64_t MagicValue;
9087
9088 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
9089 return false;
9090
9091 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00009092 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009093 if (I->getArgumentKind() != ArgumentKind) {
9094 FoundWrongKind = true;
9095 return false;
9096 }
9097 TypeInfo.Type = I->getMatchingCType();
9098 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
9099 TypeInfo.MustBeNull = I->getMustBeNull();
9100 return true;
9101 }
9102 return false;
9103 }
9104
9105 if (!MagicValues)
9106 return false;
9107
9108 llvm::DenseMap<Sema::TypeTagMagicValue,
9109 Sema::TypeTagData>::const_iterator I =
9110 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
9111 if (I == MagicValues->end())
9112 return false;
9113
9114 TypeInfo = I->second;
9115 return true;
9116}
9117} // unnamed namespace
9118
9119void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9120 uint64_t MagicValue, QualType Type,
9121 bool LayoutCompatible,
9122 bool MustBeNull) {
9123 if (!TypeTagForDatatypeMagicValues)
9124 TypeTagForDatatypeMagicValues.reset(
9125 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
9126
9127 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
9128 (*TypeTagForDatatypeMagicValues)[Magic] =
9129 TypeTagData(Type, LayoutCompatible, MustBeNull);
9130}
9131
9132namespace {
9133bool IsSameCharType(QualType T1, QualType T2) {
9134 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
9135 if (!BT1)
9136 return false;
9137
9138 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
9139 if (!BT2)
9140 return false;
9141
9142 BuiltinType::Kind T1Kind = BT1->getKind();
9143 BuiltinType::Kind T2Kind = BT2->getKind();
9144
9145 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
9146 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
9147 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
9148 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
9149}
9150} // unnamed namespace
9151
9152void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9153 const Expr * const *ExprArgs) {
9154 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
9155 bool IsPointerAttr = Attr->getIsPointer();
9156
9157 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
9158 bool FoundWrongKind;
9159 TypeTagData TypeInfo;
9160 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
9161 TypeTagForDatatypeMagicValues.get(),
9162 FoundWrongKind, TypeInfo)) {
9163 if (FoundWrongKind)
9164 Diag(TypeTagExpr->getExprLoc(),
9165 diag::warn_type_tag_for_datatype_wrong_kind)
9166 << TypeTagExpr->getSourceRange();
9167 return;
9168 }
9169
9170 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
9171 if (IsPointerAttr) {
9172 // Skip implicit cast of pointer to `void *' (as a function argument).
9173 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00009174 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00009175 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009176 ArgumentExpr = ICE->getSubExpr();
9177 }
9178 QualType ArgumentType = ArgumentExpr->getType();
9179
9180 // Passing a `void*' pointer shouldn't trigger a warning.
9181 if (IsPointerAttr && ArgumentType->isVoidPointerType())
9182 return;
9183
9184 if (TypeInfo.MustBeNull) {
9185 // Type tag with matching void type requires a null pointer.
9186 if (!ArgumentExpr->isNullPointerConstant(Context,
9187 Expr::NPC_ValueDependentIsNotNull)) {
9188 Diag(ArgumentExpr->getExprLoc(),
9189 diag::warn_type_safety_null_pointer_required)
9190 << ArgumentKind->getName()
9191 << ArgumentExpr->getSourceRange()
9192 << TypeTagExpr->getSourceRange();
9193 }
9194 return;
9195 }
9196
9197 QualType RequiredType = TypeInfo.Type;
9198 if (IsPointerAttr)
9199 RequiredType = Context.getPointerType(RequiredType);
9200
9201 bool mismatch = false;
9202 if (!TypeInfo.LayoutCompatible) {
9203 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
9204
9205 // C++11 [basic.fundamental] p1:
9206 // Plain char, signed char, and unsigned char are three distinct types.
9207 //
9208 // But we treat plain `char' as equivalent to `signed char' or `unsigned
9209 // char' depending on the current char signedness mode.
9210 if (mismatch)
9211 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
9212 RequiredType->getPointeeType())) ||
9213 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
9214 mismatch = false;
9215 } else
9216 if (IsPointerAttr)
9217 mismatch = !isLayoutCompatible(Context,
9218 ArgumentType->getPointeeType(),
9219 RequiredType->getPointeeType());
9220 else
9221 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
9222
9223 if (mismatch)
9224 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00009225 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009226 << TypeInfo.LayoutCompatible << RequiredType
9227 << ArgumentExpr->getSourceRange()
9228 << TypeTagExpr->getSourceRange();
9229}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009230