blob: f8e6c9d5ee4a943199a3bc4b42be719ef48f269f [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"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000024#include "clang/AST/ExprOpenMP.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000025#include "clang/AST/StmtCXX.h"
26#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000028#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000029#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000030#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000031#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "clang/Sema/Lookup.h"
34#include "clang/Sema/ScopeInfo.h"
35#include "clang/Sema/Sema.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000036#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000037#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "llvm/ADT/SmallString.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000039#include "llvm/Support/ConvertUTF.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "llvm/Support/raw_ostream.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000041#include <limits>
Chris Lattnerb87b1b32007-08-10 20:18:51 +000042using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000043using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000044
Chris Lattnera26fb342009-02-18 17:49:48 +000045SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
46 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000047 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
48 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000049}
50
John McCallbebede42011-02-26 05:39:39 +000051/// Checks that a call expression's argument count is the desired number.
52/// This is useful when doing custom type-checking. Returns true on error.
53static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
54 unsigned argCount = call->getNumArgs();
55 if (argCount == desiredArgCount) return false;
56
57 if (argCount < desiredArgCount)
58 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
59 << 0 /*function call*/ << desiredArgCount << argCount
60 << call->getSourceRange();
61
62 // Highlight all the excess arguments.
63 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
64 call->getArg(argCount - 1)->getLocEnd());
65
66 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
67 << 0 /*function call*/ << desiredArgCount << argCount
68 << call->getArg(1)->getSourceRange();
69}
70
Julien Lerouge4a5b4442012-04-28 17:39:16 +000071/// Check that the first argument to __builtin_annotation is an integer
72/// and the second argument is a non-wide string literal.
73static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
74 if (checkArgCount(S, TheCall, 2))
75 return true;
76
77 // First argument should be an integer.
78 Expr *ValArg = TheCall->getArg(0);
79 QualType Ty = ValArg->getType();
80 if (!Ty->isIntegerType()) {
81 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
82 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000083 return true;
84 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000085
86 // Second argument should be a constant string.
87 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
88 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
89 if (!Literal || !Literal->isAscii()) {
90 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
91 << StrArg->getSourceRange();
92 return true;
93 }
94
95 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000096 return false;
97}
98
Richard Smith6cbd65d2013-07-11 02:27:57 +000099/// Check that the argument to __builtin_addressof is a glvalue, and set the
100/// result type to the corresponding pointer type.
101static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
102 if (checkArgCount(S, TheCall, 1))
103 return true;
104
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000105 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000106 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
107 if (ResultType.isNull())
108 return true;
109
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000110 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000111 TheCall->setType(ResultType);
112 return false;
113}
114
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000115static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
116 CallExpr *TheCall, unsigned SizeIdx,
117 unsigned DstSizeIdx) {
118 if (TheCall->getNumArgs() <= SizeIdx ||
119 TheCall->getNumArgs() <= DstSizeIdx)
120 return;
121
122 const Expr *SizeArg = TheCall->getArg(SizeIdx);
123 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
124
125 llvm::APSInt Size, DstSize;
126
127 // find out if both sizes are known at compile time
128 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
129 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
130 return;
131
132 if (Size.ule(DstSize))
133 return;
134
135 // confirmed overflow so generate the diagnostic.
136 IdentifierInfo *FnName = FDecl->getIdentifier();
137 SourceLocation SL = TheCall->getLocStart();
138 SourceRange SR = TheCall->getSourceRange();
139
140 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
141}
142
Peter Collingbournef7706832014-12-12 23:41:25 +0000143static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
144 if (checkArgCount(S, BuiltinCall, 2))
145 return true;
146
147 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
148 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
149 Expr *Call = BuiltinCall->getArg(0);
150 Expr *Chain = BuiltinCall->getArg(1);
151
152 if (Call->getStmtClass() != Stmt::CallExprClass) {
153 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
154 << Call->getSourceRange();
155 return true;
156 }
157
158 auto CE = cast<CallExpr>(Call);
159 if (CE->getCallee()->getType()->isBlockPointerType()) {
160 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
161 << Call->getSourceRange();
162 return true;
163 }
164
165 const Decl *TargetDecl = CE->getCalleeDecl();
166 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
167 if (FD->getBuiltinID()) {
168 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
169 << Call->getSourceRange();
170 return true;
171 }
172
173 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
174 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
175 << Call->getSourceRange();
176 return true;
177 }
178
179 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
180 if (ChainResult.isInvalid())
181 return true;
182 if (!ChainResult.get()->getType()->isPointerType()) {
183 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
184 << Chain->getSourceRange();
185 return true;
186 }
187
David Majnemerced8bdf2015-02-25 17:36:15 +0000188 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000189 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
190 QualType BuiltinTy = S.Context.getFunctionType(
191 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
192 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
193
194 Builtin =
195 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
196
197 BuiltinCall->setType(CE->getType());
198 BuiltinCall->setValueKind(CE->getValueKind());
199 BuiltinCall->setObjectKind(CE->getObjectKind());
200 BuiltinCall->setCallee(Builtin);
201 BuiltinCall->setArg(1, ChainResult.get());
202
203 return false;
204}
205
Reid Kleckner1d59f992015-01-22 01:36:17 +0000206static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
207 Scope::ScopeFlags NeededScopeFlags,
208 unsigned DiagID) {
209 // Scopes aren't available during instantiation. Fortunately, builtin
210 // functions cannot be template args so they cannot be formed through template
211 // instantiation. Therefore checking once during the parse is sufficient.
212 if (!SemaRef.ActiveTemplateInstantiations.empty())
213 return false;
214
215 Scope *S = SemaRef.getCurScope();
216 while (S && !S->isSEHExceptScope())
217 S = S->getParent();
218 if (!S || !(S->getFlags() & NeededScopeFlags)) {
219 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
220 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
221 << DRE->getDecl()->getIdentifier();
222 return true;
223 }
224
225 return false;
226}
227
John McCalldadc5752010-08-24 06:29:42 +0000228ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000229Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
230 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000231 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000232
Chris Lattner3be167f2010-10-01 23:23:24 +0000233 // Find out if any arguments are required to be integer constant expressions.
234 unsigned ICEArguments = 0;
235 ASTContext::GetBuiltinTypeError Error;
236 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
237 if (Error != ASTContext::GE_None)
238 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
239
240 // If any arguments are required to be ICE's, check and diagnose.
241 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
242 // Skip arguments not required to be ICE's.
243 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
244
245 llvm::APSInt Result;
246 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
247 return true;
248 ICEArguments &= ~(1 << ArgNo);
249 }
250
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000251 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000252 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000253 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000254 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000255 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000256 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000257 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000258 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000259 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000260 if (SemaBuiltinVAStart(TheCall))
261 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000262 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000263 case Builtin::BI__va_start: {
264 switch (Context.getTargetInfo().getTriple().getArch()) {
265 case llvm::Triple::arm:
266 case llvm::Triple::thumb:
267 if (SemaBuiltinVAStartARM(TheCall))
268 return ExprError();
269 break;
270 default:
271 if (SemaBuiltinVAStart(TheCall))
272 return ExprError();
273 break;
274 }
275 break;
276 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000277 case Builtin::BI__builtin_isgreater:
278 case Builtin::BI__builtin_isgreaterequal:
279 case Builtin::BI__builtin_isless:
280 case Builtin::BI__builtin_islessequal:
281 case Builtin::BI__builtin_islessgreater:
282 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000283 if (SemaBuiltinUnorderedCompare(TheCall))
284 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000285 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000286 case Builtin::BI__builtin_fpclassify:
287 if (SemaBuiltinFPClassification(TheCall, 6))
288 return ExprError();
289 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000290 case Builtin::BI__builtin_isfinite:
291 case Builtin::BI__builtin_isinf:
292 case Builtin::BI__builtin_isinf_sign:
293 case Builtin::BI__builtin_isnan:
294 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000295 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000296 return ExprError();
297 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000298 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000299 return SemaBuiltinShuffleVector(TheCall);
300 // TheCall will be freed by the smart pointer here, but that's fine, since
301 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000302 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000303 if (SemaBuiltinPrefetch(TheCall))
304 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000305 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000306 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000307 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000308 if (SemaBuiltinAssume(TheCall))
309 return ExprError();
310 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000311 case Builtin::BI__builtin_assume_aligned:
312 if (SemaBuiltinAssumeAligned(TheCall))
313 return ExprError();
314 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000315 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000316 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000317 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000318 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000319 case Builtin::BI__builtin_longjmp:
320 if (SemaBuiltinLongjmp(TheCall))
321 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000322 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000323 case Builtin::BI__builtin_setjmp:
324 if (SemaBuiltinSetjmp(TheCall))
325 return ExprError();
326 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000327 case Builtin::BI_setjmp:
328 case Builtin::BI_setjmpex:
329 if (checkArgCount(*this, TheCall, 1))
330 return true;
331 break;
John McCallbebede42011-02-26 05:39:39 +0000332
333 case Builtin::BI__builtin_classify_type:
334 if (checkArgCount(*this, TheCall, 1)) return true;
335 TheCall->setType(Context.IntTy);
336 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000337 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000338 if (checkArgCount(*this, TheCall, 1)) return true;
339 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000340 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000341 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000342 case Builtin::BI__sync_fetch_and_add_1:
343 case Builtin::BI__sync_fetch_and_add_2:
344 case Builtin::BI__sync_fetch_and_add_4:
345 case Builtin::BI__sync_fetch_and_add_8:
346 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000347 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000348 case Builtin::BI__sync_fetch_and_sub_1:
349 case Builtin::BI__sync_fetch_and_sub_2:
350 case Builtin::BI__sync_fetch_and_sub_4:
351 case Builtin::BI__sync_fetch_and_sub_8:
352 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000353 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000354 case Builtin::BI__sync_fetch_and_or_1:
355 case Builtin::BI__sync_fetch_and_or_2:
356 case Builtin::BI__sync_fetch_and_or_4:
357 case Builtin::BI__sync_fetch_and_or_8:
358 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000359 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000360 case Builtin::BI__sync_fetch_and_and_1:
361 case Builtin::BI__sync_fetch_and_and_2:
362 case Builtin::BI__sync_fetch_and_and_4:
363 case Builtin::BI__sync_fetch_and_and_8:
364 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000365 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000366 case Builtin::BI__sync_fetch_and_xor_1:
367 case Builtin::BI__sync_fetch_and_xor_2:
368 case Builtin::BI__sync_fetch_and_xor_4:
369 case Builtin::BI__sync_fetch_and_xor_8:
370 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000371 case Builtin::BI__sync_fetch_and_nand:
372 case Builtin::BI__sync_fetch_and_nand_1:
373 case Builtin::BI__sync_fetch_and_nand_2:
374 case Builtin::BI__sync_fetch_and_nand_4:
375 case Builtin::BI__sync_fetch_and_nand_8:
376 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000377 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000378 case Builtin::BI__sync_add_and_fetch_1:
379 case Builtin::BI__sync_add_and_fetch_2:
380 case Builtin::BI__sync_add_and_fetch_4:
381 case Builtin::BI__sync_add_and_fetch_8:
382 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000383 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000384 case Builtin::BI__sync_sub_and_fetch_1:
385 case Builtin::BI__sync_sub_and_fetch_2:
386 case Builtin::BI__sync_sub_and_fetch_4:
387 case Builtin::BI__sync_sub_and_fetch_8:
388 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000389 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000390 case Builtin::BI__sync_and_and_fetch_1:
391 case Builtin::BI__sync_and_and_fetch_2:
392 case Builtin::BI__sync_and_and_fetch_4:
393 case Builtin::BI__sync_and_and_fetch_8:
394 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000395 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000396 case Builtin::BI__sync_or_and_fetch_1:
397 case Builtin::BI__sync_or_and_fetch_2:
398 case Builtin::BI__sync_or_and_fetch_4:
399 case Builtin::BI__sync_or_and_fetch_8:
400 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000401 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000402 case Builtin::BI__sync_xor_and_fetch_1:
403 case Builtin::BI__sync_xor_and_fetch_2:
404 case Builtin::BI__sync_xor_and_fetch_4:
405 case Builtin::BI__sync_xor_and_fetch_8:
406 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000407 case Builtin::BI__sync_nand_and_fetch:
408 case Builtin::BI__sync_nand_and_fetch_1:
409 case Builtin::BI__sync_nand_and_fetch_2:
410 case Builtin::BI__sync_nand_and_fetch_4:
411 case Builtin::BI__sync_nand_and_fetch_8:
412 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000413 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000414 case Builtin::BI__sync_val_compare_and_swap_1:
415 case Builtin::BI__sync_val_compare_and_swap_2:
416 case Builtin::BI__sync_val_compare_and_swap_4:
417 case Builtin::BI__sync_val_compare_and_swap_8:
418 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000419 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000420 case Builtin::BI__sync_bool_compare_and_swap_1:
421 case Builtin::BI__sync_bool_compare_and_swap_2:
422 case Builtin::BI__sync_bool_compare_and_swap_4:
423 case Builtin::BI__sync_bool_compare_and_swap_8:
424 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000425 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000426 case Builtin::BI__sync_lock_test_and_set_1:
427 case Builtin::BI__sync_lock_test_and_set_2:
428 case Builtin::BI__sync_lock_test_and_set_4:
429 case Builtin::BI__sync_lock_test_and_set_8:
430 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000431 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000432 case Builtin::BI__sync_lock_release_1:
433 case Builtin::BI__sync_lock_release_2:
434 case Builtin::BI__sync_lock_release_4:
435 case Builtin::BI__sync_lock_release_8:
436 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000437 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000438 case Builtin::BI__sync_swap_1:
439 case Builtin::BI__sync_swap_2:
440 case Builtin::BI__sync_swap_4:
441 case Builtin::BI__sync_swap_8:
442 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000443 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000444 case Builtin::BI__builtin_nontemporal_load:
445 case Builtin::BI__builtin_nontemporal_store:
446 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000447#define BUILTIN(ID, TYPE, ATTRS)
448#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
449 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000450 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000451#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000452 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000453 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000454 return ExprError();
455 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000456 case Builtin::BI__builtin_addressof:
457 if (SemaBuiltinAddressof(*this, TheCall))
458 return ExprError();
459 break;
Richard Smith760520b2014-06-03 23:27:44 +0000460 case Builtin::BI__builtin_operator_new:
461 case Builtin::BI__builtin_operator_delete:
462 if (!getLangOpts().CPlusPlus) {
463 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
464 << (BuiltinID == Builtin::BI__builtin_operator_new
465 ? "__builtin_operator_new"
466 : "__builtin_operator_delete")
467 << "C++";
468 return ExprError();
469 }
470 // CodeGen assumes it can find the global new and delete to call,
471 // so ensure that they are declared.
472 DeclareGlobalNewDelete();
473 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000474
475 // check secure string manipulation functions where overflows
476 // are detectable at compile time
477 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000478 case Builtin::BI__builtin___memmove_chk:
479 case Builtin::BI__builtin___memset_chk:
480 case Builtin::BI__builtin___strlcat_chk:
481 case Builtin::BI__builtin___strlcpy_chk:
482 case Builtin::BI__builtin___strncat_chk:
483 case Builtin::BI__builtin___strncpy_chk:
484 case Builtin::BI__builtin___stpncpy_chk:
485 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
486 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000487 case Builtin::BI__builtin___memccpy_chk:
488 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
489 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000490 case Builtin::BI__builtin___snprintf_chk:
491 case Builtin::BI__builtin___vsnprintf_chk:
492 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
493 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000494
495 case Builtin::BI__builtin_call_with_static_chain:
496 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
497 return ExprError();
498 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000499
500 case Builtin::BI__exception_code:
501 case Builtin::BI_exception_code: {
502 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
503 diag::err_seh___except_block))
504 return ExprError();
505 break;
506 }
507 case Builtin::BI__exception_info:
508 case Builtin::BI_exception_info: {
509 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
510 diag::err_seh___except_filter))
511 return ExprError();
512 break;
513 }
514
David Majnemerba3e5ec2015-03-13 18:26:17 +0000515 case Builtin::BI__GetExceptionInfo:
516 if (checkArgCount(*this, TheCall, 1))
517 return ExprError();
518
519 if (CheckCXXThrowOperand(
520 TheCall->getLocStart(),
521 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
522 TheCall))
523 return ExprError();
524
525 TheCall->setType(Context.VoidPtrTy);
526 break;
527
Nate Begeman4904e322010-06-08 02:47:44 +0000528 }
Richard Smith760520b2014-06-03 23:27:44 +0000529
Nate Begeman4904e322010-06-08 02:47:44 +0000530 // Since the target specific builtins for each arch overlap, only check those
531 // of the arch we are compiling for.
Artem Belevich7230a222015-08-20 18:28:56 +0000532 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000533 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000534 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000535 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000536 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000537 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000538 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
539 return ExprError();
540 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000541 case llvm::Triple::aarch64:
542 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000543 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000544 return ExprError();
545 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000546 case llvm::Triple::mips:
547 case llvm::Triple::mipsel:
548 case llvm::Triple::mips64:
549 case llvm::Triple::mips64el:
550 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
551 return ExprError();
552 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +0000553 case llvm::Triple::systemz:
554 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
555 return ExprError();
556 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000557 case llvm::Triple::x86:
558 case llvm::Triple::x86_64:
559 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
560 return ExprError();
561 break;
Kit Bartone50adcb2015-03-30 19:40:59 +0000562 case llvm::Triple::ppc:
563 case llvm::Triple::ppc64:
564 case llvm::Triple::ppc64le:
565 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
566 return ExprError();
567 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000568 default:
569 break;
570 }
571 }
572
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000573 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000574}
575
Nate Begeman91e1fea2010-06-14 05:21:25 +0000576// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000577static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000578 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000579 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000580 switch (Type.getEltType()) {
581 case NeonTypeFlags::Int8:
582 case NeonTypeFlags::Poly8:
583 return shift ? 7 : (8 << IsQuad) - 1;
584 case NeonTypeFlags::Int16:
585 case NeonTypeFlags::Poly16:
586 return shift ? 15 : (4 << IsQuad) - 1;
587 case NeonTypeFlags::Int32:
588 return shift ? 31 : (2 << IsQuad) - 1;
589 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000590 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000591 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000592 case NeonTypeFlags::Poly128:
593 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000594 case NeonTypeFlags::Float16:
595 assert(!shift && "cannot shift float types!");
596 return (4 << IsQuad) - 1;
597 case NeonTypeFlags::Float32:
598 assert(!shift && "cannot shift float types!");
599 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000600 case NeonTypeFlags::Float64:
601 assert(!shift && "cannot shift float types!");
602 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000603 }
David Blaikie8a40f702012-01-17 06:56:22 +0000604 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000605}
606
Bob Wilsone4d77232011-11-08 05:04:11 +0000607/// getNeonEltType - Return the QualType corresponding to the elements of
608/// the vector type specified by the NeonTypeFlags. This is used to check
609/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000610static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000611 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000612 switch (Flags.getEltType()) {
613 case NeonTypeFlags::Int8:
614 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
615 case NeonTypeFlags::Int16:
616 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
617 case NeonTypeFlags::Int32:
618 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
619 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000620 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000621 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
622 else
623 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
624 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000625 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000626 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000627 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000628 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000629 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +0000630 if (IsInt64Long)
631 return Context.UnsignedLongTy;
632 else
633 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000634 case NeonTypeFlags::Poly128:
635 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000636 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000637 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000638 case NeonTypeFlags::Float32:
639 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000640 case NeonTypeFlags::Float64:
641 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000642 }
David Blaikie8a40f702012-01-17 06:56:22 +0000643 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000644}
645
Tim Northover12670412014-02-19 10:37:05 +0000646bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000647 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000648 uint64_t mask = 0;
649 unsigned TV = 0;
650 int PtrArgNum = -1;
651 bool HasConstPtr = false;
652 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000653#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000654#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000655#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000656 }
657
658 // For NEON intrinsics which are overloaded on vector element type, validate
659 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000660 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000661 if (mask) {
662 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
663 return true;
664
665 TV = Result.getLimitedValue(64);
666 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
667 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000668 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000669 }
670
671 if (PtrArgNum >= 0) {
672 // Check that pointer arguments have the specified type.
673 Expr *Arg = TheCall->getArg(PtrArgNum);
674 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
675 Arg = ICE->getSubExpr();
676 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
677 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000678
Tim Northovera2ee4332014-03-29 15:09:45 +0000679 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000680 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000681 bool IsInt64Long =
682 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
683 QualType EltTy =
684 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000685 if (HasConstPtr)
686 EltTy = EltTy.withConst();
687 QualType LHSTy = Context.getPointerType(EltTy);
688 AssignConvertType ConvTy;
689 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
690 if (RHS.isInvalid())
691 return true;
692 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
693 RHS.get(), AA_Assigning))
694 return true;
695 }
696
697 // For NEON intrinsics which take an immediate value as part of the
698 // instruction, range check them here.
699 unsigned i = 0, l = 0, u = 0;
700 switch (BuiltinID) {
701 default:
702 return false;
Tim Northover12670412014-02-19 10:37:05 +0000703#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000704#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000705#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000706 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000707
Richard Sandiford28940af2014-04-16 08:47:51 +0000708 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000709}
710
Tim Northovera2ee4332014-03-29 15:09:45 +0000711bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
712 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000713 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000714 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000715 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000716 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000717 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000718 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
719 BuiltinID == AArch64::BI__builtin_arm_strex ||
720 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000721 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000722 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000723 BuiltinID == ARM::BI__builtin_arm_ldaex ||
724 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
725 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000726
727 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
728
729 // Ensure that we have the proper number of arguments.
730 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
731 return true;
732
733 // Inspect the pointer argument of the atomic builtin. This should always be
734 // a pointer type, whose element is an integral scalar or pointer type.
735 // Because it is a pointer type, we don't have to worry about any implicit
736 // casts here.
737 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
738 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
739 if (PointerArgRes.isInvalid())
740 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000741 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000742
743 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
744 if (!pointerType) {
745 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
746 << PointerArg->getType() << PointerArg->getSourceRange();
747 return true;
748 }
749
750 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
751 // task is to insert the appropriate casts into the AST. First work out just
752 // what the appropriate type is.
753 QualType ValType = pointerType->getPointeeType();
754 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
755 if (IsLdrex)
756 AddrType.addConst();
757
758 // Issue a warning if the cast is dodgy.
759 CastKind CastNeeded = CK_NoOp;
760 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
761 CastNeeded = CK_BitCast;
762 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
763 << PointerArg->getType()
764 << Context.getPointerType(AddrType)
765 << AA_Passing << PointerArg->getSourceRange();
766 }
767
768 // Finally, do the cast and replace the argument with the corrected version.
769 AddrType = Context.getPointerType(AddrType);
770 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
771 if (PointerArgRes.isInvalid())
772 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000773 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000774
775 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
776
777 // In general, we allow ints, floats and pointers to be loaded and stored.
778 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
779 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
780 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
781 << PointerArg->getType() << PointerArg->getSourceRange();
782 return true;
783 }
784
785 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000786 if (Context.getTypeSize(ValType) > MaxWidth) {
787 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000788 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
789 << PointerArg->getType() << PointerArg->getSourceRange();
790 return true;
791 }
792
793 switch (ValType.getObjCLifetime()) {
794 case Qualifiers::OCL_None:
795 case Qualifiers::OCL_ExplicitNone:
796 // okay
797 break;
798
799 case Qualifiers::OCL_Weak:
800 case Qualifiers::OCL_Strong:
801 case Qualifiers::OCL_Autoreleasing:
802 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
803 << ValType << PointerArg->getSourceRange();
804 return true;
805 }
806
807
808 if (IsLdrex) {
809 TheCall->setType(ValType);
810 return false;
811 }
812
813 // Initialize the argument to be stored.
814 ExprResult ValArg = TheCall->getArg(0);
815 InitializedEntity Entity = InitializedEntity::InitializeParameter(
816 Context, ValType, /*consume*/ false);
817 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
818 if (ValArg.isInvalid())
819 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000820 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000821
822 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
823 // but the custom checker bypasses all default analysis.
824 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000825 return false;
826}
827
Nate Begeman4904e322010-06-08 02:47:44 +0000828bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000829 llvm::APSInt Result;
830
Tim Northover6aacd492013-07-16 09:47:53 +0000831 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000832 BuiltinID == ARM::BI__builtin_arm_ldaex ||
833 BuiltinID == ARM::BI__builtin_arm_strex ||
834 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000835 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000836 }
837
Yi Kong26d104a2014-08-13 19:18:14 +0000838 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
839 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
840 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
841 }
842
Luke Cheeseman59b2d832015-06-15 17:51:01 +0000843 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
844 BuiltinID == ARM::BI__builtin_arm_wsr64)
845 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
846
847 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
848 BuiltinID == ARM::BI__builtin_arm_rsrp ||
849 BuiltinID == ARM::BI__builtin_arm_wsr ||
850 BuiltinID == ARM::BI__builtin_arm_wsrp)
851 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
852
Tim Northover12670412014-02-19 10:37:05 +0000853 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
854 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000855
Yi Kong4efadfb2014-07-03 16:01:25 +0000856 // For intrinsics which take an immediate value as part of the instruction,
857 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000858 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000859 switch (BuiltinID) {
860 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000861 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
862 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000863 case ARM::BI__builtin_arm_vcvtr_f:
864 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000865 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +0000866 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +0000867 case ARM::BI__builtin_arm_isb:
868 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000869 }
Nate Begemand773fe62010-06-13 04:47:52 +0000870
Nate Begemanf568b072010-08-03 21:32:34 +0000871 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000872 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000873}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000874
Tim Northover573cbee2014-05-24 12:52:07 +0000875bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000876 CallExpr *TheCall) {
877 llvm::APSInt Result;
878
Tim Northover573cbee2014-05-24 12:52:07 +0000879 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000880 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
881 BuiltinID == AArch64::BI__builtin_arm_strex ||
882 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000883 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
884 }
885
Yi Konga5548432014-08-13 19:18:20 +0000886 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
887 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
888 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
889 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
890 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
891 }
892
Luke Cheeseman59b2d832015-06-15 17:51:01 +0000893 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
894 BuiltinID == AArch64::BI__builtin_arm_wsr64)
895 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, false);
896
897 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
898 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
899 BuiltinID == AArch64::BI__builtin_arm_wsr ||
900 BuiltinID == AArch64::BI__builtin_arm_wsrp)
901 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
902
Tim Northovera2ee4332014-03-29 15:09:45 +0000903 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
904 return true;
905
Yi Kong19a29ac2014-07-17 10:52:06 +0000906 // For intrinsics which take an immediate value as part of the instruction,
907 // range check them here.
908 unsigned i = 0, l = 0, u = 0;
909 switch (BuiltinID) {
910 default: return false;
911 case AArch64::BI__builtin_arm_dmb:
912 case AArch64::BI__builtin_arm_dsb:
913 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
914 }
915
Yi Kong19a29ac2014-07-17 10:52:06 +0000916 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +0000917}
918
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000919bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
920 unsigned i = 0, l = 0, u = 0;
921 switch (BuiltinID) {
922 default: return false;
923 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
924 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000925 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
926 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
927 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
928 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
929 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000930 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000931
Richard Sandiford28940af2014-04-16 08:47:51 +0000932 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000933}
934
Kit Bartone50adcb2015-03-30 19:40:59 +0000935bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
936 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +0000937 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
938 BuiltinID == PPC::BI__builtin_divdeu ||
939 BuiltinID == PPC::BI__builtin_bpermd;
940 bool IsTarget64Bit = Context.getTargetInfo()
941 .getTypeWidth(Context
942 .getTargetInfo()
943 .getIntPtrType()) == 64;
944 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
945 BuiltinID == PPC::BI__builtin_divweu ||
946 BuiltinID == PPC::BI__builtin_divde ||
947 BuiltinID == PPC::BI__builtin_divdeu;
948
949 if (Is64BitBltin && !IsTarget64Bit)
950 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
951 << TheCall->getSourceRange();
952
953 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
954 (BuiltinID == PPC::BI__builtin_bpermd &&
955 !Context.getTargetInfo().hasFeature("bpermd")))
956 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
957 << TheCall->getSourceRange();
958
Kit Bartone50adcb2015-03-30 19:40:59 +0000959 switch (BuiltinID) {
960 default: return false;
961 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
962 case PPC::BI__builtin_altivec_crypto_vshasigmad:
963 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
964 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
965 case PPC::BI__builtin_tbegin:
966 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
967 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
968 case PPC::BI__builtin_tabortwc:
969 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
970 case PPC::BI__builtin_tabortwci:
971 case PPC::BI__builtin_tabortdci:
972 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
973 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
974 }
975 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
976}
977
Ulrich Weigand3a610eb2015-04-01 12:54:25 +0000978bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
979 CallExpr *TheCall) {
980 if (BuiltinID == SystemZ::BI__builtin_tabort) {
981 Expr *Arg = TheCall->getArg(0);
982 llvm::APSInt AbortCode(32);
983 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
984 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
985 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
986 << Arg->getSourceRange();
987 }
988
Ulrich Weigand5722c0f2015-05-05 19:36:42 +0000989 // For intrinsics which take an immediate value as part of the instruction,
990 // range check them here.
991 unsigned i = 0, l = 0, u = 0;
992 switch (BuiltinID) {
993 default: return false;
994 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
995 case SystemZ::BI__builtin_s390_verimb:
996 case SystemZ::BI__builtin_s390_verimh:
997 case SystemZ::BI__builtin_s390_verimf:
998 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
999 case SystemZ::BI__builtin_s390_vfaeb:
1000 case SystemZ::BI__builtin_s390_vfaeh:
1001 case SystemZ::BI__builtin_s390_vfaef:
1002 case SystemZ::BI__builtin_s390_vfaebs:
1003 case SystemZ::BI__builtin_s390_vfaehs:
1004 case SystemZ::BI__builtin_s390_vfaefs:
1005 case SystemZ::BI__builtin_s390_vfaezb:
1006 case SystemZ::BI__builtin_s390_vfaezh:
1007 case SystemZ::BI__builtin_s390_vfaezf:
1008 case SystemZ::BI__builtin_s390_vfaezbs:
1009 case SystemZ::BI__builtin_s390_vfaezhs:
1010 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1011 case SystemZ::BI__builtin_s390_vfidb:
1012 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1013 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1014 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1015 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1016 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1017 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1018 case SystemZ::BI__builtin_s390_vstrcb:
1019 case SystemZ::BI__builtin_s390_vstrch:
1020 case SystemZ::BI__builtin_s390_vstrcf:
1021 case SystemZ::BI__builtin_s390_vstrczb:
1022 case SystemZ::BI__builtin_s390_vstrczh:
1023 case SystemZ::BI__builtin_s390_vstrczf:
1024 case SystemZ::BI__builtin_s390_vstrcbs:
1025 case SystemZ::BI__builtin_s390_vstrchs:
1026 case SystemZ::BI__builtin_s390_vstrcfs:
1027 case SystemZ::BI__builtin_s390_vstrczbs:
1028 case SystemZ::BI__builtin_s390_vstrczhs:
1029 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1030 }
1031 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001032}
1033
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001034bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001035 unsigned i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001036 switch (BuiltinID) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001037 default: return false;
Eric Christopherd9832702015-06-29 21:00:05 +00001038 case X86::BI__builtin_cpu_supports:
1039 return SemaBuiltinCpuSupports(TheCall);
Charles Davisc7d5c942015-09-17 20:55:33 +00001040 case X86::BI__builtin_ms_va_start:
1041 return SemaBuiltinMSVAStart(TheCall);
Craig Topperdd84ec52014-12-27 07:00:08 +00001042 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
Craig Topper16015252015-01-31 06:31:23 +00001043 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001044 case X86::BI__builtin_ia32_vpermil2pd:
1045 case X86::BI__builtin_ia32_vpermil2pd256:
1046 case X86::BI__builtin_ia32_vpermil2ps:
1047 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
Craig Topper95b0d732015-01-25 23:30:05 +00001048 case X86::BI__builtin_ia32_cmpb128_mask:
1049 case X86::BI__builtin_ia32_cmpw128_mask:
1050 case X86::BI__builtin_ia32_cmpd128_mask:
1051 case X86::BI__builtin_ia32_cmpq128_mask:
1052 case X86::BI__builtin_ia32_cmpb256_mask:
1053 case X86::BI__builtin_ia32_cmpw256_mask:
1054 case X86::BI__builtin_ia32_cmpd256_mask:
1055 case X86::BI__builtin_ia32_cmpq256_mask:
1056 case X86::BI__builtin_ia32_cmpb512_mask:
1057 case X86::BI__builtin_ia32_cmpw512_mask:
1058 case X86::BI__builtin_ia32_cmpd512_mask:
1059 case X86::BI__builtin_ia32_cmpq512_mask:
1060 case X86::BI__builtin_ia32_ucmpb128_mask:
1061 case X86::BI__builtin_ia32_ucmpw128_mask:
1062 case X86::BI__builtin_ia32_ucmpd128_mask:
1063 case X86::BI__builtin_ia32_ucmpq128_mask:
1064 case X86::BI__builtin_ia32_ucmpb256_mask:
1065 case X86::BI__builtin_ia32_ucmpw256_mask:
1066 case X86::BI__builtin_ia32_ucmpd256_mask:
1067 case X86::BI__builtin_ia32_ucmpq256_mask:
1068 case X86::BI__builtin_ia32_ucmpb512_mask:
1069 case X86::BI__builtin_ia32_ucmpw512_mask:
1070 case X86::BI__builtin_ia32_ucmpd512_mask:
1071 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
Craig Topper16015252015-01-31 06:31:23 +00001072 case X86::BI__builtin_ia32_roundps:
1073 case X86::BI__builtin_ia32_roundpd:
1074 case X86::BI__builtin_ia32_roundps256:
1075 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
1076 case X86::BI__builtin_ia32_roundss:
1077 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
1078 case X86::BI__builtin_ia32_cmpps:
1079 case X86::BI__builtin_ia32_cmpss:
1080 case X86::BI__builtin_ia32_cmppd:
1081 case X86::BI__builtin_ia32_cmpsd:
1082 case X86::BI__builtin_ia32_cmpps256:
1083 case X86::BI__builtin_ia32_cmppd256:
1084 case X86::BI__builtin_ia32_cmpps512_mask:
1085 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001086 case X86::BI__builtin_ia32_vpcomub:
1087 case X86::BI__builtin_ia32_vpcomuw:
1088 case X86::BI__builtin_ia32_vpcomud:
1089 case X86::BI__builtin_ia32_vpcomuq:
1090 case X86::BI__builtin_ia32_vpcomb:
1091 case X86::BI__builtin_ia32_vpcomw:
1092 case X86::BI__builtin_ia32_vpcomd:
1093 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001094 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001095 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001096}
1097
Richard Smith55ce3522012-06-25 20:30:08 +00001098/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1099/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1100/// Returns true when the format fits the function and the FormatStringInfo has
1101/// been populated.
1102bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1103 FormatStringInfo *FSI) {
1104 FSI->HasVAListArg = Format->getFirstArg() == 0;
1105 FSI->FormatIdx = Format->getFormatIdx() - 1;
1106 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001107
Richard Smith55ce3522012-06-25 20:30:08 +00001108 // The way the format attribute works in GCC, the implicit this argument
1109 // of member functions is counted. However, it doesn't appear in our own
1110 // lists, so decrement format_idx in that case.
1111 if (IsCXXMember) {
1112 if(FSI->FormatIdx == 0)
1113 return false;
1114 --FSI->FormatIdx;
1115 if (FSI->FirstDataArg != 0)
1116 --FSI->FirstDataArg;
1117 }
1118 return true;
1119}
Mike Stump11289f42009-09-09 15:08:12 +00001120
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001121/// Checks if a the given expression evaluates to null.
1122///
1123/// \brief Returns true if the value evaluates to null.
1124static bool CheckNonNullExpr(Sema &S,
1125 const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001126 // If the expression has non-null type, it doesn't evaluate to null.
1127 if (auto nullability
1128 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1129 if (*nullability == NullabilityKind::NonNull)
1130 return false;
1131 }
1132
Ted Kremeneka146db32014-01-17 06:24:47 +00001133 // As a special case, transparent unions initialized with zero are
1134 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001135 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001136 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1137 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001138 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001139 if (const InitListExpr *ILE =
1140 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001141 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001142 }
1143
1144 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001145 return (!Expr->isValueDependent() &&
1146 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1147 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001148}
1149
1150static void CheckNonNullArgument(Sema &S,
1151 const Expr *ArgExpr,
1152 SourceLocation CallSiteLoc) {
1153 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001154 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
1155}
1156
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001157bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1158 FormatStringInfo FSI;
1159 if ((GetFormatStringType(Format) == FST_NSString) &&
1160 getFormatStringInfo(Format, false, &FSI)) {
1161 Idx = FSI.FormatIdx;
1162 return true;
1163 }
1164 return false;
1165}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001166/// \brief Diagnose use of %s directive in an NSString which is being passed
1167/// as formatting string to formatting method.
1168static void
1169DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1170 const NamedDecl *FDecl,
1171 Expr **Args,
1172 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001173 unsigned Idx = 0;
1174 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001175 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1176 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001177 Idx = 2;
1178 Format = true;
1179 }
1180 else
1181 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1182 if (S.GetFormatNSStringIdx(I, Idx)) {
1183 Format = true;
1184 break;
1185 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001186 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001187 if (!Format || NumArgs <= Idx)
1188 return;
1189 const Expr *FormatExpr = Args[Idx];
1190 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1191 FormatExpr = CSCE->getSubExpr();
1192 const StringLiteral *FormatString;
1193 if (const ObjCStringLiteral *OSL =
1194 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1195 FormatString = OSL->getString();
1196 else
1197 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1198 if (!FormatString)
1199 return;
1200 if (S.FormatStringHasSArg(FormatString)) {
1201 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1202 << "%s" << 1 << 1;
1203 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1204 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001205 }
1206}
1207
Douglas Gregorb4866e82015-06-19 18:13:19 +00001208/// Determine whether the given type has a non-null nullability annotation.
1209static bool isNonNullType(ASTContext &ctx, QualType type) {
1210 if (auto nullability = type->getNullability(ctx))
1211 return *nullability == NullabilityKind::NonNull;
1212
1213 return false;
1214}
1215
Ted Kremenek2bc73332014-01-17 06:24:43 +00001216static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001217 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00001218 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00001219 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001220 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001221 assert((FDecl || Proto) && "Need a function declaration or prototype");
1222
Ted Kremenek9aedc152014-01-17 06:24:56 +00001223 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001224 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001225 if (FDecl) {
1226 // Handle the nonnull attribute on the function/method declaration itself.
1227 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1228 if (!NonNull->args_size()) {
1229 // Easy case: all pointer arguments are nonnull.
1230 for (const auto *Arg : Args)
1231 if (S.isValidPointerAttrType(Arg->getType()))
1232 CheckNonNullArgument(S, Arg, CallSiteLoc);
1233 return;
1234 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001235
Douglas Gregorb4866e82015-06-19 18:13:19 +00001236 for (unsigned Val : NonNull->args()) {
1237 if (Val >= Args.size())
1238 continue;
1239 if (NonNullArgs.empty())
1240 NonNullArgs.resize(Args.size());
1241 NonNullArgs.set(Val);
1242 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001243 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001244 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001245
Douglas Gregorb4866e82015-06-19 18:13:19 +00001246 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1247 // Handle the nonnull attribute on the parameters of the
1248 // function/method.
1249 ArrayRef<ParmVarDecl*> parms;
1250 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1251 parms = FD->parameters();
1252 else
1253 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1254
1255 unsigned ParamIndex = 0;
1256 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1257 I != E; ++I, ++ParamIndex) {
1258 const ParmVarDecl *PVD = *I;
1259 if (PVD->hasAttr<NonNullAttr>() ||
1260 isNonNullType(S.Context, PVD->getType())) {
1261 if (NonNullArgs.empty())
1262 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00001263
Douglas Gregorb4866e82015-06-19 18:13:19 +00001264 NonNullArgs.set(ParamIndex);
1265 }
1266 }
1267 } else {
1268 // If we have a non-function, non-method declaration but no
1269 // function prototype, try to dig out the function prototype.
1270 if (!Proto) {
1271 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1272 QualType type = VD->getType().getNonReferenceType();
1273 if (auto pointerType = type->getAs<PointerType>())
1274 type = pointerType->getPointeeType();
1275 else if (auto blockType = type->getAs<BlockPointerType>())
1276 type = blockType->getPointeeType();
1277 // FIXME: data member pointers?
1278
1279 // Dig out the function prototype, if there is one.
1280 Proto = type->getAs<FunctionProtoType>();
1281 }
1282 }
1283
1284 // Fill in non-null argument information from the nullability
1285 // information on the parameter types (if we have them).
1286 if (Proto) {
1287 unsigned Index = 0;
1288 for (auto paramType : Proto->getParamTypes()) {
1289 if (isNonNullType(S.Context, paramType)) {
1290 if (NonNullArgs.empty())
1291 NonNullArgs.resize(Args.size());
1292
1293 NonNullArgs.set(Index);
1294 }
1295
1296 ++Index;
1297 }
1298 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001299 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001300
Douglas Gregorb4866e82015-06-19 18:13:19 +00001301 // Check for non-null arguments.
1302 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1303 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001304 if (NonNullArgs[ArgIndex])
1305 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00001306 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001307}
1308
Richard Smith55ce3522012-06-25 20:30:08 +00001309/// Handles the checks for format strings, non-POD arguments to vararg
1310/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001311void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1312 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00001313 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001314 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001315 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001316 if (CurContext->isDependentContext())
1317 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001318
Ted Kremenekb8176da2010-09-09 04:33:05 +00001319 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001320 llvm::SmallBitVector CheckedVarArgs;
1321 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001322 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001323 // Only create vector if there are format attributes.
1324 CheckedVarArgs.resize(Args.size());
1325
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001326 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001327 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001328 }
Richard Smithd7293d72013-08-05 18:49:43 +00001329 }
Richard Smith55ce3522012-06-25 20:30:08 +00001330
1331 // Refuse POD arguments that weren't caught by the format string
1332 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001333 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001334 unsigned NumParams = Proto ? Proto->getNumParams()
1335 : FDecl && isa<FunctionDecl>(FDecl)
1336 ? cast<FunctionDecl>(FDecl)->getNumParams()
1337 : FDecl && isa<ObjCMethodDecl>(FDecl)
1338 ? cast<ObjCMethodDecl>(FDecl)->param_size()
1339 : 0;
1340
Alp Toker9cacbab2014-01-20 20:26:09 +00001341 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001342 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001343 if (const Expr *Arg = Args[ArgIdx]) {
1344 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1345 checkVariadicArgument(Arg, CallType);
1346 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001347 }
Richard Smithd7293d72013-08-05 18:49:43 +00001348 }
Mike Stump11289f42009-09-09 15:08:12 +00001349
Douglas Gregorb4866e82015-06-19 18:13:19 +00001350 if (FDecl || Proto) {
1351 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001352
Richard Trieu41bc0992013-06-22 00:20:41 +00001353 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001354 if (FDecl) {
1355 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1356 CheckArgumentWithTypeTag(I, Args.data());
1357 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001358 }
Richard Smith55ce3522012-06-25 20:30:08 +00001359}
1360
1361/// CheckConstructorCall - Check a constructor call for correctness and safety
1362/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001363void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1364 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001365 const FunctionProtoType *Proto,
1366 SourceLocation Loc) {
1367 VariadicCallType CallType =
1368 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001369 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1370 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00001371}
1372
1373/// CheckFunctionCall - Check a direct function call for various correctness
1374/// and safety properties not strictly enforced by the C type system.
1375bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1376 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001377 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1378 isa<CXXMethodDecl>(FDecl);
1379 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1380 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001381 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1382 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00001383 Expr** Args = TheCall->getArgs();
1384 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001385 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001386 // If this is a call to a member operator, hide the first argument
1387 // from checkCall.
1388 // FIXME: Our choice of AST representation here is less than ideal.
1389 ++Args;
1390 --NumArgs;
1391 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00001392 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00001393 IsMemberFunction, TheCall->getRParenLoc(),
1394 TheCall->getCallee()->getSourceRange(), CallType);
1395
1396 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1397 // None of the checks below are needed for functions that don't have
1398 // simple names (e.g., C++ conversion functions).
1399 if (!FnInfo)
1400 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001401
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001402 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001403 if (getLangOpts().ObjC1)
1404 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001405
Anna Zaks22122702012-01-17 00:37:07 +00001406 unsigned CMId = FDecl->getMemoryFunctionKind();
1407 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001408 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001409
Anna Zaks201d4892012-01-13 21:52:01 +00001410 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001411 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001412 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001413 else if (CMId == Builtin::BIstrncat)
1414 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001415 else
Anna Zaks22122702012-01-17 00:37:07 +00001416 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001417
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001418 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001419}
1420
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001421bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001422 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001423 VariadicCallType CallType =
1424 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001425
Douglas Gregorb4866e82015-06-19 18:13:19 +00001426 checkCall(Method, nullptr, Args,
1427 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1428 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001429
1430 return false;
1431}
1432
Richard Trieu664c4c62013-06-20 21:03:13 +00001433bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1434 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00001435 QualType Ty;
1436 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001437 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001438 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001439 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001440 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001441 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001442
Douglas Gregorb4866e82015-06-19 18:13:19 +00001443 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
1444 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001445 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001446
Richard Trieu664c4c62013-06-20 21:03:13 +00001447 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001448 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001449 CallType = VariadicDoesNotApply;
1450 } else if (Ty->isBlockPointerType()) {
1451 CallType = VariadicBlock;
1452 } else { // Ty->isFunctionPointerType()
1453 CallType = VariadicFunction;
1454 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001455
Douglas Gregorb4866e82015-06-19 18:13:19 +00001456 checkCall(NDecl, Proto,
1457 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1458 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001459 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001460
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001461 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001462}
1463
Richard Trieu41bc0992013-06-22 00:20:41 +00001464/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1465/// such as function pointers returned from functions.
1466bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001467 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001468 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00001469 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001470 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00001471 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001472 TheCall->getCallee()->getSourceRange(), CallType);
1473
1474 return false;
1475}
1476
Tim Northovere94a34c2014-03-11 10:49:14 +00001477static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1478 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1479 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1480 return false;
1481
1482 switch (Op) {
1483 case AtomicExpr::AO__c11_atomic_init:
1484 llvm_unreachable("There is no ordering argument for an init");
1485
1486 case AtomicExpr::AO__c11_atomic_load:
1487 case AtomicExpr::AO__atomic_load_n:
1488 case AtomicExpr::AO__atomic_load:
1489 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1490 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1491
1492 case AtomicExpr::AO__c11_atomic_store:
1493 case AtomicExpr::AO__atomic_store:
1494 case AtomicExpr::AO__atomic_store_n:
1495 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1496 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1497 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1498
1499 default:
1500 return true;
1501 }
1502}
1503
Richard Smithfeea8832012-04-12 05:08:17 +00001504ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1505 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001506 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1507 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001508
Richard Smithfeea8832012-04-12 05:08:17 +00001509 // All these operations take one of the following forms:
1510 enum {
1511 // C __c11_atomic_init(A *, C)
1512 Init,
1513 // C __c11_atomic_load(A *, int)
1514 Load,
1515 // void __atomic_load(A *, CP, int)
1516 Copy,
1517 // C __c11_atomic_add(A *, M, int)
1518 Arithmetic,
1519 // C __atomic_exchange_n(A *, CP, int)
1520 Xchg,
1521 // void __atomic_exchange(A *, C *, CP, int)
1522 GNUXchg,
1523 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1524 C11CmpXchg,
1525 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1526 GNUCmpXchg
1527 } Form = Init;
1528 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1529 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1530 // where:
1531 // C is an appropriate type,
1532 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1533 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1534 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1535 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001536
Gabor Horvath98bd0982015-03-16 09:59:54 +00001537 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1538 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1539 AtomicExpr::AO__atomic_load,
1540 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00001541 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1542 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1543 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1544 Op == AtomicExpr::AO__atomic_store_n ||
1545 Op == AtomicExpr::AO__atomic_exchange_n ||
1546 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1547 bool IsAddSub = false;
1548
1549 switch (Op) {
1550 case AtomicExpr::AO__c11_atomic_init:
1551 Form = Init;
1552 break;
1553
1554 case AtomicExpr::AO__c11_atomic_load:
1555 case AtomicExpr::AO__atomic_load_n:
1556 Form = Load;
1557 break;
1558
1559 case AtomicExpr::AO__c11_atomic_store:
1560 case AtomicExpr::AO__atomic_load:
1561 case AtomicExpr::AO__atomic_store:
1562 case AtomicExpr::AO__atomic_store_n:
1563 Form = Copy;
1564 break;
1565
1566 case AtomicExpr::AO__c11_atomic_fetch_add:
1567 case AtomicExpr::AO__c11_atomic_fetch_sub:
1568 case AtomicExpr::AO__atomic_fetch_add:
1569 case AtomicExpr::AO__atomic_fetch_sub:
1570 case AtomicExpr::AO__atomic_add_fetch:
1571 case AtomicExpr::AO__atomic_sub_fetch:
1572 IsAddSub = true;
1573 // Fall through.
1574 case AtomicExpr::AO__c11_atomic_fetch_and:
1575 case AtomicExpr::AO__c11_atomic_fetch_or:
1576 case AtomicExpr::AO__c11_atomic_fetch_xor:
1577 case AtomicExpr::AO__atomic_fetch_and:
1578 case AtomicExpr::AO__atomic_fetch_or:
1579 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001580 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001581 case AtomicExpr::AO__atomic_and_fetch:
1582 case AtomicExpr::AO__atomic_or_fetch:
1583 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001584 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001585 Form = Arithmetic;
1586 break;
1587
1588 case AtomicExpr::AO__c11_atomic_exchange:
1589 case AtomicExpr::AO__atomic_exchange_n:
1590 Form = Xchg;
1591 break;
1592
1593 case AtomicExpr::AO__atomic_exchange:
1594 Form = GNUXchg;
1595 break;
1596
1597 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1598 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1599 Form = C11CmpXchg;
1600 break;
1601
1602 case AtomicExpr::AO__atomic_compare_exchange:
1603 case AtomicExpr::AO__atomic_compare_exchange_n:
1604 Form = GNUCmpXchg;
1605 break;
1606 }
1607
1608 // Check we have the right number of arguments.
1609 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001610 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001611 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001612 << TheCall->getCallee()->getSourceRange();
1613 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001614 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1615 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001616 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001617 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001618 << TheCall->getCallee()->getSourceRange();
1619 return ExprError();
1620 }
1621
Richard Smithfeea8832012-04-12 05:08:17 +00001622 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001623 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001624 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1625 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1626 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001627 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001628 << Ptr->getType() << Ptr->getSourceRange();
1629 return ExprError();
1630 }
1631
Richard Smithfeea8832012-04-12 05:08:17 +00001632 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1633 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1634 QualType ValType = AtomTy; // 'C'
1635 if (IsC11) {
1636 if (!AtomTy->isAtomicType()) {
1637 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1638 << Ptr->getType() << Ptr->getSourceRange();
1639 return ExprError();
1640 }
Richard Smithe00921a2012-09-15 06:09:58 +00001641 if (AtomTy.isConstQualified()) {
1642 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1643 << Ptr->getType() << Ptr->getSourceRange();
1644 return ExprError();
1645 }
Richard Smithfeea8832012-04-12 05:08:17 +00001646 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001647 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001648
Richard Smithfeea8832012-04-12 05:08:17 +00001649 // For an arithmetic operation, the implied arithmetic must be well-formed.
1650 if (Form == Arithmetic) {
1651 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1652 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1653 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1654 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1655 return ExprError();
1656 }
1657 if (!IsAddSub && !ValType->isIntegerType()) {
1658 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1659 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1660 return ExprError();
1661 }
David Majnemere85cff82015-01-28 05:48:06 +00001662 if (IsC11 && ValType->isPointerType() &&
1663 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1664 diag::err_incomplete_type)) {
1665 return ExprError();
1666 }
Richard Smithfeea8832012-04-12 05:08:17 +00001667 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1668 // For __atomic_*_n operations, the value type must be a scalar integral or
1669 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001670 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001671 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1672 return ExprError();
1673 }
1674
Eli Friedmanaa769812013-09-11 03:49:34 +00001675 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1676 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001677 // For GNU atomics, require a trivially-copyable type. This is not part of
1678 // the GNU atomics specification, but we enforce it for sanity.
1679 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001680 << Ptr->getType() << Ptr->getSourceRange();
1681 return ExprError();
1682 }
1683
Richard Smithfeea8832012-04-12 05:08:17 +00001684 // FIXME: For any builtin other than a load, the ValType must not be
1685 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001686
1687 switch (ValType.getObjCLifetime()) {
1688 case Qualifiers::OCL_None:
1689 case Qualifiers::OCL_ExplicitNone:
1690 // okay
1691 break;
1692
1693 case Qualifiers::OCL_Weak:
1694 case Qualifiers::OCL_Strong:
1695 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001696 // FIXME: Can this happen? By this point, ValType should be known
1697 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001698 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1699 << ValType << Ptr->getSourceRange();
1700 return ExprError();
1701 }
1702
David Majnemerc6eb6502015-06-03 00:26:35 +00001703 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
1704 // volatile-ness of the pointee-type inject itself into the result or the
1705 // other operands.
1706 ValType.removeLocalVolatile();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001707 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001708 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001709 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001710 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001711 ResultType = Context.BoolTy;
1712
Richard Smithfeea8832012-04-12 05:08:17 +00001713 // The type of a parameter passed 'by value'. In the GNU atomics, such
1714 // arguments are actually passed as pointers.
1715 QualType ByValType = ValType; // 'CP'
1716 if (!IsC11 && !IsN)
1717 ByValType = Ptr->getType();
1718
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001719 // The first argument --- the pointer --- has a fixed type; we
1720 // deduce the types of the rest of the arguments accordingly. Walk
1721 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001722 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001723 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001724 if (i < NumVals[Form] + 1) {
1725 switch (i) {
1726 case 1:
1727 // The second argument is the non-atomic operand. For arithmetic, this
1728 // is always passed by value, and for a compare_exchange it is always
1729 // passed by address. For the rest, GNU uses by-address and C11 uses
1730 // by-value.
1731 assert(Form != Load);
1732 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1733 Ty = ValType;
1734 else if (Form == Copy || Form == Xchg)
1735 Ty = ByValType;
1736 else if (Form == Arithmetic)
1737 Ty = Context.getPointerDiffType();
1738 else
1739 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1740 break;
1741 case 2:
1742 // The third argument to compare_exchange / GNU exchange is a
1743 // (pointer to a) desired value.
1744 Ty = ByValType;
1745 break;
1746 case 3:
1747 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1748 Ty = Context.BoolTy;
1749 break;
1750 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001751 } else {
1752 // The order(s) are always converted to int.
1753 Ty = Context.IntTy;
1754 }
Richard Smithfeea8832012-04-12 05:08:17 +00001755
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001756 InitializedEntity Entity =
1757 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001758 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001759 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1760 if (Arg.isInvalid())
1761 return true;
1762 TheCall->setArg(i, Arg.get());
1763 }
1764
Richard Smithfeea8832012-04-12 05:08:17 +00001765 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001766 SmallVector<Expr*, 5> SubExprs;
1767 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001768 switch (Form) {
1769 case Init:
1770 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001771 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001772 break;
1773 case Load:
1774 SubExprs.push_back(TheCall->getArg(1)); // Order
1775 break;
1776 case Copy:
1777 case Arithmetic:
1778 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001779 SubExprs.push_back(TheCall->getArg(2)); // Order
1780 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001781 break;
1782 case GNUXchg:
1783 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1784 SubExprs.push_back(TheCall->getArg(3)); // Order
1785 SubExprs.push_back(TheCall->getArg(1)); // Val1
1786 SubExprs.push_back(TheCall->getArg(2)); // Val2
1787 break;
1788 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001789 SubExprs.push_back(TheCall->getArg(3)); // Order
1790 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001791 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001792 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001793 break;
1794 case GNUCmpXchg:
1795 SubExprs.push_back(TheCall->getArg(4)); // Order
1796 SubExprs.push_back(TheCall->getArg(1)); // Val1
1797 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1798 SubExprs.push_back(TheCall->getArg(2)); // Val2
1799 SubExprs.push_back(TheCall->getArg(3)); // Weak
1800 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001801 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001802
1803 if (SubExprs.size() >= 2 && Form != Init) {
1804 llvm::APSInt Result(32);
1805 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1806 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001807 Diag(SubExprs[1]->getLocStart(),
1808 diag::warn_atomic_op_has_invalid_memory_order)
1809 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001810 }
1811
Fariborz Jahanian615de762013-05-28 17:37:39 +00001812 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1813 SubExprs, ResultType, Op,
1814 TheCall->getRParenLoc());
1815
1816 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1817 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1818 Context.AtomicUsesUnsupportedLibcall(AE))
1819 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1820 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001821
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001822 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001823}
1824
1825
John McCall29ad95b2011-08-27 01:09:30 +00001826/// checkBuiltinArgument - Given a call to a builtin function, perform
1827/// normal type-checking on the given argument, updating the call in
1828/// place. This is useful when a builtin function requires custom
1829/// type-checking for some of its arguments but not necessarily all of
1830/// them.
1831///
1832/// Returns true on error.
1833static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1834 FunctionDecl *Fn = E->getDirectCallee();
1835 assert(Fn && "builtin call without direct callee!");
1836
1837 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1838 InitializedEntity Entity =
1839 InitializedEntity::InitializeParameter(S.Context, Param);
1840
1841 ExprResult Arg = E->getArg(0);
1842 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1843 if (Arg.isInvalid())
1844 return true;
1845
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001846 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001847 return false;
1848}
1849
Chris Lattnerdc046542009-05-08 06:58:22 +00001850/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1851/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1852/// type of its first argument. The main ActOnCallExpr routines have already
1853/// promoted the types of arguments because all of these calls are prototyped as
1854/// void(...).
1855///
1856/// This function goes through and does final semantic checking for these
1857/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001858ExprResult
1859Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001860 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001861 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1862 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1863
1864 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001865 if (TheCall->getNumArgs() < 1) {
1866 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1867 << 0 << 1 << TheCall->getNumArgs()
1868 << TheCall->getCallee()->getSourceRange();
1869 return ExprError();
1870 }
Mike Stump11289f42009-09-09 15:08:12 +00001871
Chris Lattnerdc046542009-05-08 06:58:22 +00001872 // Inspect the first argument of the atomic builtin. This should always be
1873 // a pointer type, whose element is an integral scalar or pointer type.
1874 // Because it is a pointer type, we don't have to worry about any implicit
1875 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001876 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001877 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001878 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1879 if (FirstArgResult.isInvalid())
1880 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001881 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001882 TheCall->setArg(0, FirstArg);
1883
John McCall31168b02011-06-15 23:02:42 +00001884 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1885 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001886 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1887 << FirstArg->getType() << FirstArg->getSourceRange();
1888 return ExprError();
1889 }
Mike Stump11289f42009-09-09 15:08:12 +00001890
John McCall31168b02011-06-15 23:02:42 +00001891 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001892 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001893 !ValType->isBlockPointerType()) {
1894 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1895 << FirstArg->getType() << FirstArg->getSourceRange();
1896 return ExprError();
1897 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001898
John McCall31168b02011-06-15 23:02:42 +00001899 switch (ValType.getObjCLifetime()) {
1900 case Qualifiers::OCL_None:
1901 case Qualifiers::OCL_ExplicitNone:
1902 // okay
1903 break;
1904
1905 case Qualifiers::OCL_Weak:
1906 case Qualifiers::OCL_Strong:
1907 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001908 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001909 << ValType << FirstArg->getSourceRange();
1910 return ExprError();
1911 }
1912
John McCallb50451a2011-10-05 07:41:44 +00001913 // Strip any qualifiers off ValType.
1914 ValType = ValType.getUnqualifiedType();
1915
Chandler Carruth3973af72010-07-18 20:54:12 +00001916 // The majority of builtins return a value, but a few have special return
1917 // types, so allow them to override appropriately below.
1918 QualType ResultType = ValType;
1919
Chris Lattnerdc046542009-05-08 06:58:22 +00001920 // We need to figure out which concrete builtin this maps onto. For example,
1921 // __sync_fetch_and_add with a 2 byte object turns into
1922 // __sync_fetch_and_add_2.
1923#define BUILTIN_ROW(x) \
1924 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1925 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001926
Chris Lattnerdc046542009-05-08 06:58:22 +00001927 static const unsigned BuiltinIndices[][5] = {
1928 BUILTIN_ROW(__sync_fetch_and_add),
1929 BUILTIN_ROW(__sync_fetch_and_sub),
1930 BUILTIN_ROW(__sync_fetch_and_or),
1931 BUILTIN_ROW(__sync_fetch_and_and),
1932 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00001933 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00001934
Chris Lattnerdc046542009-05-08 06:58:22 +00001935 BUILTIN_ROW(__sync_add_and_fetch),
1936 BUILTIN_ROW(__sync_sub_and_fetch),
1937 BUILTIN_ROW(__sync_and_and_fetch),
1938 BUILTIN_ROW(__sync_or_and_fetch),
1939 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00001940 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001941
Chris Lattnerdc046542009-05-08 06:58:22 +00001942 BUILTIN_ROW(__sync_val_compare_and_swap),
1943 BUILTIN_ROW(__sync_bool_compare_and_swap),
1944 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001945 BUILTIN_ROW(__sync_lock_release),
1946 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001947 };
Mike Stump11289f42009-09-09 15:08:12 +00001948#undef BUILTIN_ROW
1949
Chris Lattnerdc046542009-05-08 06:58:22 +00001950 // Determine the index of the size.
1951 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001952 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001953 case 1: SizeIndex = 0; break;
1954 case 2: SizeIndex = 1; break;
1955 case 4: SizeIndex = 2; break;
1956 case 8: SizeIndex = 3; break;
1957 case 16: SizeIndex = 4; break;
1958 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001959 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1960 << FirstArg->getType() << FirstArg->getSourceRange();
1961 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001962 }
Mike Stump11289f42009-09-09 15:08:12 +00001963
Chris Lattnerdc046542009-05-08 06:58:22 +00001964 // Each of these builtins has one pointer argument, followed by some number of
1965 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1966 // that we ignore. Find out which row of BuiltinIndices to read from as well
1967 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001968 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001969 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00001970 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00001971 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001972 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001973 case Builtin::BI__sync_fetch_and_add:
1974 case Builtin::BI__sync_fetch_and_add_1:
1975 case Builtin::BI__sync_fetch_and_add_2:
1976 case Builtin::BI__sync_fetch_and_add_4:
1977 case Builtin::BI__sync_fetch_and_add_8:
1978 case Builtin::BI__sync_fetch_and_add_16:
1979 BuiltinIndex = 0;
1980 break;
1981
1982 case Builtin::BI__sync_fetch_and_sub:
1983 case Builtin::BI__sync_fetch_and_sub_1:
1984 case Builtin::BI__sync_fetch_and_sub_2:
1985 case Builtin::BI__sync_fetch_and_sub_4:
1986 case Builtin::BI__sync_fetch_and_sub_8:
1987 case Builtin::BI__sync_fetch_and_sub_16:
1988 BuiltinIndex = 1;
1989 break;
1990
1991 case Builtin::BI__sync_fetch_and_or:
1992 case Builtin::BI__sync_fetch_and_or_1:
1993 case Builtin::BI__sync_fetch_and_or_2:
1994 case Builtin::BI__sync_fetch_and_or_4:
1995 case Builtin::BI__sync_fetch_and_or_8:
1996 case Builtin::BI__sync_fetch_and_or_16:
1997 BuiltinIndex = 2;
1998 break;
1999
2000 case Builtin::BI__sync_fetch_and_and:
2001 case Builtin::BI__sync_fetch_and_and_1:
2002 case Builtin::BI__sync_fetch_and_and_2:
2003 case Builtin::BI__sync_fetch_and_and_4:
2004 case Builtin::BI__sync_fetch_and_and_8:
2005 case Builtin::BI__sync_fetch_and_and_16:
2006 BuiltinIndex = 3;
2007 break;
Mike Stump11289f42009-09-09 15:08:12 +00002008
Douglas Gregor73722482011-11-28 16:30:08 +00002009 case Builtin::BI__sync_fetch_and_xor:
2010 case Builtin::BI__sync_fetch_and_xor_1:
2011 case Builtin::BI__sync_fetch_and_xor_2:
2012 case Builtin::BI__sync_fetch_and_xor_4:
2013 case Builtin::BI__sync_fetch_and_xor_8:
2014 case Builtin::BI__sync_fetch_and_xor_16:
2015 BuiltinIndex = 4;
2016 break;
2017
Hal Finkeld2208b52014-10-02 20:53:50 +00002018 case Builtin::BI__sync_fetch_and_nand:
2019 case Builtin::BI__sync_fetch_and_nand_1:
2020 case Builtin::BI__sync_fetch_and_nand_2:
2021 case Builtin::BI__sync_fetch_and_nand_4:
2022 case Builtin::BI__sync_fetch_and_nand_8:
2023 case Builtin::BI__sync_fetch_and_nand_16:
2024 BuiltinIndex = 5;
2025 WarnAboutSemanticsChange = true;
2026 break;
2027
Douglas Gregor73722482011-11-28 16:30:08 +00002028 case Builtin::BI__sync_add_and_fetch:
2029 case Builtin::BI__sync_add_and_fetch_1:
2030 case Builtin::BI__sync_add_and_fetch_2:
2031 case Builtin::BI__sync_add_and_fetch_4:
2032 case Builtin::BI__sync_add_and_fetch_8:
2033 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002034 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002035 break;
2036
2037 case Builtin::BI__sync_sub_and_fetch:
2038 case Builtin::BI__sync_sub_and_fetch_1:
2039 case Builtin::BI__sync_sub_and_fetch_2:
2040 case Builtin::BI__sync_sub_and_fetch_4:
2041 case Builtin::BI__sync_sub_and_fetch_8:
2042 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002043 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002044 break;
2045
2046 case Builtin::BI__sync_and_and_fetch:
2047 case Builtin::BI__sync_and_and_fetch_1:
2048 case Builtin::BI__sync_and_and_fetch_2:
2049 case Builtin::BI__sync_and_and_fetch_4:
2050 case Builtin::BI__sync_and_and_fetch_8:
2051 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002052 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002053 break;
2054
2055 case Builtin::BI__sync_or_and_fetch:
2056 case Builtin::BI__sync_or_and_fetch_1:
2057 case Builtin::BI__sync_or_and_fetch_2:
2058 case Builtin::BI__sync_or_and_fetch_4:
2059 case Builtin::BI__sync_or_and_fetch_8:
2060 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002061 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002062 break;
2063
2064 case Builtin::BI__sync_xor_and_fetch:
2065 case Builtin::BI__sync_xor_and_fetch_1:
2066 case Builtin::BI__sync_xor_and_fetch_2:
2067 case Builtin::BI__sync_xor_and_fetch_4:
2068 case Builtin::BI__sync_xor_and_fetch_8:
2069 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002070 BuiltinIndex = 10;
2071 break;
2072
2073 case Builtin::BI__sync_nand_and_fetch:
2074 case Builtin::BI__sync_nand_and_fetch_1:
2075 case Builtin::BI__sync_nand_and_fetch_2:
2076 case Builtin::BI__sync_nand_and_fetch_4:
2077 case Builtin::BI__sync_nand_and_fetch_8:
2078 case Builtin::BI__sync_nand_and_fetch_16:
2079 BuiltinIndex = 11;
2080 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002081 break;
Mike Stump11289f42009-09-09 15:08:12 +00002082
Chris Lattnerdc046542009-05-08 06:58:22 +00002083 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002084 case Builtin::BI__sync_val_compare_and_swap_1:
2085 case Builtin::BI__sync_val_compare_and_swap_2:
2086 case Builtin::BI__sync_val_compare_and_swap_4:
2087 case Builtin::BI__sync_val_compare_and_swap_8:
2088 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002089 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002090 NumFixed = 2;
2091 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002092
Chris Lattnerdc046542009-05-08 06:58:22 +00002093 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002094 case Builtin::BI__sync_bool_compare_and_swap_1:
2095 case Builtin::BI__sync_bool_compare_and_swap_2:
2096 case Builtin::BI__sync_bool_compare_and_swap_4:
2097 case Builtin::BI__sync_bool_compare_and_swap_8:
2098 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002099 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002100 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002101 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002102 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002103
2104 case Builtin::BI__sync_lock_test_and_set:
2105 case Builtin::BI__sync_lock_test_and_set_1:
2106 case Builtin::BI__sync_lock_test_and_set_2:
2107 case Builtin::BI__sync_lock_test_and_set_4:
2108 case Builtin::BI__sync_lock_test_and_set_8:
2109 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002110 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002111 break;
2112
Chris Lattnerdc046542009-05-08 06:58:22 +00002113 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002114 case Builtin::BI__sync_lock_release_1:
2115 case Builtin::BI__sync_lock_release_2:
2116 case Builtin::BI__sync_lock_release_4:
2117 case Builtin::BI__sync_lock_release_8:
2118 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002119 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002120 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002121 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002122 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002123
2124 case Builtin::BI__sync_swap:
2125 case Builtin::BI__sync_swap_1:
2126 case Builtin::BI__sync_swap_2:
2127 case Builtin::BI__sync_swap_4:
2128 case Builtin::BI__sync_swap_8:
2129 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002130 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002131 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002132 }
Mike Stump11289f42009-09-09 15:08:12 +00002133
Chris Lattnerdc046542009-05-08 06:58:22 +00002134 // Now that we know how many fixed arguments we expect, first check that we
2135 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002136 if (TheCall->getNumArgs() < 1+NumFixed) {
2137 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2138 << 0 << 1+NumFixed << TheCall->getNumArgs()
2139 << TheCall->getCallee()->getSourceRange();
2140 return ExprError();
2141 }
Mike Stump11289f42009-09-09 15:08:12 +00002142
Hal Finkeld2208b52014-10-02 20:53:50 +00002143 if (WarnAboutSemanticsChange) {
2144 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2145 << TheCall->getCallee()->getSourceRange();
2146 }
2147
Chris Lattner5b9241b2009-05-08 15:36:58 +00002148 // Get the decl for the concrete builtin from this, we can tell what the
2149 // concrete integer type we should convert to is.
2150 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Eric Christopher02d5d862015-08-06 01:01:12 +00002151 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002152 FunctionDecl *NewBuiltinDecl;
2153 if (NewBuiltinID == BuiltinID)
2154 NewBuiltinDecl = FDecl;
2155 else {
2156 // Perform builtin lookup to avoid redeclaring it.
2157 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2158 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2159 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2160 assert(Res.getFoundDecl());
2161 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00002162 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002163 return ExprError();
2164 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002165
John McCallcf142162010-08-07 06:22:56 +00002166 // The first argument --- the pointer --- has a fixed type; we
2167 // deduce the types of the rest of the arguments accordingly. Walk
2168 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00002169 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002170 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002171
Chris Lattnerdc046542009-05-08 06:58:22 +00002172 // GCC does an implicit conversion to the pointer or integer ValType. This
2173 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002174 // Initialize the argument.
2175 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2176 ValType, /*consume*/ false);
2177 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002178 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002179 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002180
Chris Lattnerdc046542009-05-08 06:58:22 +00002181 // Okay, we have something that *can* be converted to the right type. Check
2182 // to see if there is a potentially weird extension going on here. This can
2183 // happen when you do an atomic operation on something like an char* and
2184 // pass in 42. The 42 gets converted to char. This is even more strange
2185 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002186 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002187 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002188 }
Mike Stump11289f42009-09-09 15:08:12 +00002189
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002190 ASTContext& Context = this->getASTContext();
2191
2192 // Create a new DeclRefExpr to refer to the new decl.
2193 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2194 Context,
2195 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002196 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002197 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002198 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002199 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002200 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002201 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002202
Chris Lattnerdc046542009-05-08 06:58:22 +00002203 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002204 // FIXME: This loses syntactic information.
2205 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2206 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2207 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002208 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002209
Chandler Carruthbc8cab12010-07-18 07:23:17 +00002210 // Change the result type of the call to match the original value type. This
2211 // is arbitrary, but the codegen for these builtins ins design to handle it
2212 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00002213 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002214
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002215 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002216}
2217
Michael Zolotukhin84df1232015-09-08 23:52:33 +00002218/// SemaBuiltinNontemporalOverloaded - We have a call to
2219/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2220/// overloaded function based on the pointer type of its last argument.
2221///
2222/// This function goes through and does final semantic checking for these
2223/// builtins.
2224ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
2225 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2226 DeclRefExpr *DRE =
2227 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2228 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2229 unsigned BuiltinID = FDecl->getBuiltinID();
2230 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
2231 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
2232 "Unexpected nontemporal load/store builtin!");
2233 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
2234 unsigned numArgs = isStore ? 2 : 1;
2235
2236 // Ensure that we have the proper number of arguments.
2237 if (checkArgCount(*this, TheCall, numArgs))
2238 return ExprError();
2239
2240 // Inspect the last argument of the nontemporal builtin. This should always
2241 // be a pointer type, from which we imply the type of the memory access.
2242 // Because it is a pointer type, we don't have to worry about any implicit
2243 // casts here.
2244 Expr *PointerArg = TheCall->getArg(numArgs - 1);
2245 ExprResult PointerArgResult =
2246 DefaultFunctionArrayLvalueConversion(PointerArg);
2247
2248 if (PointerArgResult.isInvalid())
2249 return ExprError();
2250 PointerArg = PointerArgResult.get();
2251 TheCall->setArg(numArgs - 1, PointerArg);
2252
2253 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2254 if (!pointerType) {
2255 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
2256 << PointerArg->getType() << PointerArg->getSourceRange();
2257 return ExprError();
2258 }
2259
2260 QualType ValType = pointerType->getPointeeType();
2261
2262 // Strip any qualifiers off ValType.
2263 ValType = ValType.getUnqualifiedType();
2264 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2265 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
2266 !ValType->isVectorType()) {
2267 Diag(DRE->getLocStart(),
2268 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
2269 << PointerArg->getType() << PointerArg->getSourceRange();
2270 return ExprError();
2271 }
2272
2273 if (!isStore) {
2274 TheCall->setType(ValType);
2275 return TheCallResult;
2276 }
2277
2278 ExprResult ValArg = TheCall->getArg(0);
2279 InitializedEntity Entity = InitializedEntity::InitializeParameter(
2280 Context, ValType, /*consume*/ false);
2281 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2282 if (ValArg.isInvalid())
2283 return ExprError();
2284
2285 TheCall->setArg(0, ValArg.get());
2286 TheCall->setType(Context.VoidTy);
2287 return TheCallResult;
2288}
2289
Chris Lattner6436fb62009-02-18 06:01:06 +00002290/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002291/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002292/// Note: It might also make sense to do the UTF-16 conversion here (would
2293/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002294bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002295 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002296 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2297
Douglas Gregorfb65e592011-07-27 05:40:30 +00002298 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002299 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2300 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002301 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002302 }
Mike Stump11289f42009-09-09 15:08:12 +00002303
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002304 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002305 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002306 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002307 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002308 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002309 UTF16 *ToPtr = &ToBuf[0];
2310
2311 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2312 &ToPtr, ToPtr + NumBytes,
2313 strictConversion);
2314 // Check for conversion failure.
2315 if (Result != conversionOK)
2316 Diag(Arg->getLocStart(),
2317 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2318 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002319 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002320}
2321
Charles Davisc7d5c942015-09-17 20:55:33 +00002322/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
2323/// for validity. Emit an error and return true on failure; return false
2324/// on success.
2325bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00002326 Expr *Fn = TheCall->getCallee();
2327 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002328 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002329 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002330 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2331 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002332 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002333 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002334 return true;
2335 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002336
2337 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002338 return Diag(TheCall->getLocEnd(),
2339 diag::err_typecheck_call_too_few_args_at_least)
2340 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002341 }
2342
John McCall29ad95b2011-08-27 01:09:30 +00002343 // Type-check the first argument normally.
2344 if (checkBuiltinArgument(*this, TheCall, 0))
2345 return true;
2346
Chris Lattnere202e6a2007-12-20 00:05:45 +00002347 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002348 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002349 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002350 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002351 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002352 else if (FunctionDecl *FD = getCurFunctionDecl())
2353 isVariadic = FD->isVariadic();
2354 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002355 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002356
Chris Lattnere202e6a2007-12-20 00:05:45 +00002357 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002358 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2359 return true;
2360 }
Mike Stump11289f42009-09-09 15:08:12 +00002361
Chris Lattner43be2e62007-12-19 23:59:04 +00002362 // Verify that the second argument to the builtin is the last argument of the
2363 // current function or method.
2364 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002365 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002366
Nico Weber9eea7642013-05-24 23:31:57 +00002367 // These are valid if SecondArgIsLastNamedArgument is false after the next
2368 // block.
2369 QualType Type;
2370 SourceLocation ParamLoc;
2371
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002372 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2373 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002374 // FIXME: This isn't correct for methods (results in bogus warning).
2375 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002376 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002377 if (CurBlock)
2378 LastArg = *(CurBlock->TheDecl->param_end()-1);
2379 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002380 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002381 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002382 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002383 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002384
2385 Type = PV->getType();
2386 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002387 }
2388 }
Mike Stump11289f42009-09-09 15:08:12 +00002389
Chris Lattner43be2e62007-12-19 23:59:04 +00002390 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002391 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002392 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002393 else if (Type->isReferenceType()) {
2394 Diag(Arg->getLocStart(),
2395 diag::warn_va_start_of_reference_type_is_undefined);
2396 Diag(ParamLoc, diag::note_parameter_type) << Type;
2397 }
2398
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002399 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002400 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002401}
Chris Lattner43be2e62007-12-19 23:59:04 +00002402
Charles Davisc7d5c942015-09-17 20:55:33 +00002403/// Check the arguments to '__builtin_va_start' for validity, and that
2404/// it was called from a function of the native ABI.
2405/// Emit an error and return true on failure; return false on success.
2406bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2407 // On x86-64 Unix, don't allow this in Win64 ABI functions.
2408 // On x64 Windows, don't allow this in System V ABI functions.
2409 // (Yes, that means there's no corresponding way to support variadic
2410 // System V ABI functions on Windows.)
2411 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
2412 unsigned OS = Context.getTargetInfo().getTriple().getOS();
2413 clang::CallingConv CC = CC_C;
2414 if (const FunctionDecl *FD = getCurFunctionDecl())
2415 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2416 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
2417 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
2418 return Diag(TheCall->getCallee()->getLocStart(),
2419 diag::err_va_start_used_in_wrong_abi_function)
2420 << (OS != llvm::Triple::Win32);
2421 }
2422 return SemaBuiltinVAStartImpl(TheCall);
2423}
2424
2425/// Check the arguments to '__builtin_ms_va_start' for validity, and that
2426/// it was called from a Win64 ABI function.
2427/// Emit an error and return true on failure; return false on success.
2428bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
2429 // This only makes sense for x86-64.
2430 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2431 Expr *Callee = TheCall->getCallee();
2432 if (TT.getArch() != llvm::Triple::x86_64)
2433 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
2434 // Don't allow this in System V ABI functions.
2435 clang::CallingConv CC = CC_C;
2436 if (const FunctionDecl *FD = getCurFunctionDecl())
2437 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2438 if (CC == CC_X86_64SysV ||
2439 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
2440 return Diag(Callee->getLocStart(),
2441 diag::err_ms_va_start_used_in_sysv_function);
2442 return SemaBuiltinVAStartImpl(TheCall);
2443}
2444
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002445bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2446 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2447 // const char *named_addr);
2448
2449 Expr *Func = Call->getCallee();
2450
2451 if (Call->getNumArgs() < 3)
2452 return Diag(Call->getLocEnd(),
2453 diag::err_typecheck_call_too_few_args_at_least)
2454 << 0 /*function call*/ << 3 << Call->getNumArgs();
2455
2456 // Determine whether the current function is variadic or not.
2457 bool IsVariadic;
2458 if (BlockScopeInfo *CurBlock = getCurBlock())
2459 IsVariadic = CurBlock->TheDecl->isVariadic();
2460 else if (FunctionDecl *FD = getCurFunctionDecl())
2461 IsVariadic = FD->isVariadic();
2462 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2463 IsVariadic = MD->isVariadic();
2464 else
2465 llvm_unreachable("unexpected statement type");
2466
2467 if (!IsVariadic) {
2468 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2469 return true;
2470 }
2471
2472 // Type-check the first argument normally.
2473 if (checkBuiltinArgument(*this, Call, 0))
2474 return true;
2475
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002476 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002477 unsigned ArgNo;
2478 QualType Type;
2479 } ArgumentTypes[] = {
2480 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2481 { 2, Context.getSizeType() },
2482 };
2483
2484 for (const auto &AT : ArgumentTypes) {
2485 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2486 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2487 continue;
2488 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2489 << Arg->getType() << AT.Type << 1 /* different class */
2490 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2491 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2492 }
2493
2494 return false;
2495}
2496
Chris Lattner2da14fb2007-12-20 00:26:33 +00002497/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2498/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002499bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2500 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002501 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002502 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002503 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002504 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002505 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002506 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002507 << SourceRange(TheCall->getArg(2)->getLocStart(),
2508 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002509
John Wiegley01296292011-04-08 18:41:53 +00002510 ExprResult OrigArg0 = TheCall->getArg(0);
2511 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002512
Chris Lattner2da14fb2007-12-20 00:26:33 +00002513 // Do standard promotions between the two arguments, returning their common
2514 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002515 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002516 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2517 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002518
2519 // Make sure any conversions are pushed back into the call; this is
2520 // type safe since unordered compare builtins are declared as "_Bool
2521 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002522 TheCall->setArg(0, OrigArg0.get());
2523 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002524
John Wiegley01296292011-04-08 18:41:53 +00002525 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002526 return false;
2527
Chris Lattner2da14fb2007-12-20 00:26:33 +00002528 // If the common type isn't a real floating type, then the arguments were
2529 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002530 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002531 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002532 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002533 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2534 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002535
Chris Lattner2da14fb2007-12-20 00:26:33 +00002536 return false;
2537}
2538
Benjamin Kramer634fc102010-02-15 22:42:31 +00002539/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2540/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002541/// to check everything. We expect the last argument to be a floating point
2542/// value.
2543bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2544 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002545 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002546 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002547 if (TheCall->getNumArgs() > NumArgs)
2548 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002549 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002550 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002551 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002552 (*(TheCall->arg_end()-1))->getLocEnd());
2553
Benjamin Kramer64aae502010-02-16 10:07:31 +00002554 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002555
Eli Friedman7e4faac2009-08-31 20:06:00 +00002556 if (OrigArg->isTypeDependent())
2557 return false;
2558
Chris Lattner68784ef2010-05-06 05:50:07 +00002559 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002560 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002561 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002562 diag::err_typecheck_call_invalid_unary_fp)
2563 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002564
Chris Lattner68784ef2010-05-06 05:50:07 +00002565 // If this is an implicit conversion from float -> double, remove it.
2566 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2567 Expr *CastArg = Cast->getSubExpr();
2568 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2569 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2570 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002571 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002572 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002573 }
2574 }
2575
Eli Friedman7e4faac2009-08-31 20:06:00 +00002576 return false;
2577}
2578
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002579/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2580// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002581ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002582 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002583 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002584 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002585 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2586 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002587
Nate Begemana0110022010-06-08 00:16:34 +00002588 // Determine which of the following types of shufflevector we're checking:
2589 // 1) unary, vector mask: (lhs, mask)
2590 // 2) binary, vector mask: (lhs, rhs, mask)
2591 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2592 QualType resType = TheCall->getArg(0)->getType();
2593 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002594
Douglas Gregorc25f7662009-05-19 22:10:17 +00002595 if (!TheCall->getArg(0)->isTypeDependent() &&
2596 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002597 QualType LHSType = TheCall->getArg(0)->getType();
2598 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002599
Craig Topperbaca3892013-07-29 06:47:04 +00002600 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2601 return ExprError(Diag(TheCall->getLocStart(),
2602 diag::err_shufflevector_non_vector)
2603 << SourceRange(TheCall->getArg(0)->getLocStart(),
2604 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002605
Nate Begemana0110022010-06-08 00:16:34 +00002606 numElements = LHSType->getAs<VectorType>()->getNumElements();
2607 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002608
Nate Begemana0110022010-06-08 00:16:34 +00002609 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2610 // with mask. If so, verify that RHS is an integer vector type with the
2611 // same number of elts as lhs.
2612 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002613 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002614 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002615 return ExprError(Diag(TheCall->getLocStart(),
2616 diag::err_shufflevector_incompatible_vector)
2617 << SourceRange(TheCall->getArg(1)->getLocStart(),
2618 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002619 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002620 return ExprError(Diag(TheCall->getLocStart(),
2621 diag::err_shufflevector_incompatible_vector)
2622 << SourceRange(TheCall->getArg(0)->getLocStart(),
2623 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002624 } else if (numElements != numResElements) {
2625 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002626 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002627 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002628 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002629 }
2630
2631 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002632 if (TheCall->getArg(i)->isTypeDependent() ||
2633 TheCall->getArg(i)->isValueDependent())
2634 continue;
2635
Nate Begemana0110022010-06-08 00:16:34 +00002636 llvm::APSInt Result(32);
2637 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2638 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002639 diag::err_shufflevector_nonconstant_argument)
2640 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002641
Craig Topper50ad5b72013-08-03 17:40:38 +00002642 // Allow -1 which will be translated to undef in the IR.
2643 if (Result.isSigned() && Result.isAllOnesValue())
2644 continue;
2645
Chris Lattner7ab824e2008-08-10 02:05:13 +00002646 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002647 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002648 diag::err_shufflevector_argument_too_large)
2649 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002650 }
2651
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002652 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002653
Chris Lattner7ab824e2008-08-10 02:05:13 +00002654 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002655 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002656 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002657 }
2658
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002659 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2660 TheCall->getCallee()->getLocStart(),
2661 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002662}
Chris Lattner43be2e62007-12-19 23:59:04 +00002663
Hal Finkelc4d7c822013-09-18 03:29:45 +00002664/// SemaConvertVectorExpr - Handle __builtin_convertvector
2665ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2666 SourceLocation BuiltinLoc,
2667 SourceLocation RParenLoc) {
2668 ExprValueKind VK = VK_RValue;
2669 ExprObjectKind OK = OK_Ordinary;
2670 QualType DstTy = TInfo->getType();
2671 QualType SrcTy = E->getType();
2672
2673 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2674 return ExprError(Diag(BuiltinLoc,
2675 diag::err_convertvector_non_vector)
2676 << E->getSourceRange());
2677 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2678 return ExprError(Diag(BuiltinLoc,
2679 diag::err_convertvector_non_vector_type));
2680
2681 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2682 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2683 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2684 if (SrcElts != DstElts)
2685 return ExprError(Diag(BuiltinLoc,
2686 diag::err_convertvector_incompatible_vector)
2687 << E->getSourceRange());
2688 }
2689
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002690 return new (Context)
2691 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002692}
2693
Daniel Dunbarb7257262008-07-21 22:59:13 +00002694/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2695// This is declared to take (const void*, ...) and can take two
2696// optional constant int args.
2697bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002698 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002699
Chris Lattner3b054132008-11-19 05:08:23 +00002700 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002701 return Diag(TheCall->getLocEnd(),
2702 diag::err_typecheck_call_too_many_args_at_most)
2703 << 0 /*function call*/ << 3 << NumArgs
2704 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002705
2706 // Argument 0 is checked for us and the remaining arguments must be
2707 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002708 for (unsigned i = 1; i != NumArgs; ++i)
2709 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002710 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002711
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002712 return false;
2713}
2714
Hal Finkelf0417332014-07-17 14:25:55 +00002715/// SemaBuiltinAssume - Handle __assume (MS Extension).
2716// __assume does not evaluate its arguments, and should warn if its argument
2717// has side effects.
2718bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2719 Expr *Arg = TheCall->getArg(0);
2720 if (Arg->isInstantiationDependent()) return false;
2721
2722 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00002723 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002724 << Arg->getSourceRange()
2725 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2726
2727 return false;
2728}
2729
2730/// Handle __builtin_assume_aligned. This is declared
2731/// as (const void*, size_t, ...) and can take one optional constant int arg.
2732bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2733 unsigned NumArgs = TheCall->getNumArgs();
2734
2735 if (NumArgs > 3)
2736 return Diag(TheCall->getLocEnd(),
2737 diag::err_typecheck_call_too_many_args_at_most)
2738 << 0 /*function call*/ << 3 << NumArgs
2739 << TheCall->getSourceRange();
2740
2741 // The alignment must be a constant integer.
2742 Expr *Arg = TheCall->getArg(1);
2743
2744 // We can't check the value of a dependent argument.
2745 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2746 llvm::APSInt Result;
2747 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2748 return true;
2749
2750 if (!Result.isPowerOf2())
2751 return Diag(TheCall->getLocStart(),
2752 diag::err_alignment_not_power_of_two)
2753 << Arg->getSourceRange();
2754 }
2755
2756 if (NumArgs > 2) {
2757 ExprResult Arg(TheCall->getArg(2));
2758 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2759 Context.getSizeType(), false);
2760 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2761 if (Arg.isInvalid()) return true;
2762 TheCall->setArg(2, Arg.get());
2763 }
Hal Finkelf0417332014-07-17 14:25:55 +00002764
2765 return false;
2766}
2767
Eric Christopher8d0c6212010-04-17 02:26:23 +00002768/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2769/// TheCall is a constant expression.
2770bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2771 llvm::APSInt &Result) {
2772 Expr *Arg = TheCall->getArg(ArgNum);
2773 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2774 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2775
2776 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2777
2778 if (!Arg->isIntegerConstantExpr(Result, Context))
2779 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002780 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002781
Chris Lattnerd545ad12009-09-23 06:06:36 +00002782 return false;
2783}
2784
Richard Sandiford28940af2014-04-16 08:47:51 +00002785/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2786/// TheCall is a constant expression in the range [Low, High].
2787bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2788 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002789 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002790
2791 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002792 Expr *Arg = TheCall->getArg(ArgNum);
2793 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002794 return false;
2795
Eric Christopher8d0c6212010-04-17 02:26:23 +00002796 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002797 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002798 return true;
2799
Richard Sandiford28940af2014-04-16 08:47:51 +00002800 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002801 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002802 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002803
2804 return false;
2805}
2806
Luke Cheeseman59b2d832015-06-15 17:51:01 +00002807/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
2808/// TheCall is an ARM/AArch64 special register string literal.
2809bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
2810 int ArgNum, unsigned ExpectedFieldNum,
2811 bool AllowName) {
2812 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2813 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
2814 BuiltinID == ARM::BI__builtin_arm_rsr ||
2815 BuiltinID == ARM::BI__builtin_arm_rsrp ||
2816 BuiltinID == ARM::BI__builtin_arm_wsr ||
2817 BuiltinID == ARM::BI__builtin_arm_wsrp;
2818 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2819 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
2820 BuiltinID == AArch64::BI__builtin_arm_rsr ||
2821 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2822 BuiltinID == AArch64::BI__builtin_arm_wsr ||
2823 BuiltinID == AArch64::BI__builtin_arm_wsrp;
2824 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
2825
2826 // We can't check the value of a dependent argument.
2827 Expr *Arg = TheCall->getArg(ArgNum);
2828 if (Arg->isTypeDependent() || Arg->isValueDependent())
2829 return false;
2830
2831 // Check if the argument is a string literal.
2832 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2833 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2834 << Arg->getSourceRange();
2835
2836 // Check the type of special register given.
2837 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2838 SmallVector<StringRef, 6> Fields;
2839 Reg.split(Fields, ":");
2840
2841 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
2842 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
2843 << Arg->getSourceRange();
2844
2845 // If the string is the name of a register then we cannot check that it is
2846 // valid here but if the string is of one the forms described in ACLE then we
2847 // can check that the supplied fields are integers and within the valid
2848 // ranges.
2849 if (Fields.size() > 1) {
2850 bool FiveFields = Fields.size() == 5;
2851
2852 bool ValidString = true;
2853 if (IsARMBuiltin) {
2854 ValidString &= Fields[0].startswith_lower("cp") ||
2855 Fields[0].startswith_lower("p");
2856 if (ValidString)
2857 Fields[0] =
2858 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
2859
2860 ValidString &= Fields[2].startswith_lower("c");
2861 if (ValidString)
2862 Fields[2] = Fields[2].drop_front(1);
2863
2864 if (FiveFields) {
2865 ValidString &= Fields[3].startswith_lower("c");
2866 if (ValidString)
2867 Fields[3] = Fields[3].drop_front(1);
2868 }
2869 }
2870
2871 SmallVector<int, 5> Ranges;
2872 if (FiveFields)
2873 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
2874 else
2875 Ranges.append({15, 7, 15});
2876
2877 for (unsigned i=0; i<Fields.size(); ++i) {
2878 int IntField;
2879 ValidString &= !Fields[i].getAsInteger(10, IntField);
2880 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
2881 }
2882
2883 if (!ValidString)
2884 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
2885 << Arg->getSourceRange();
2886
2887 } else if (IsAArch64Builtin && Fields.size() == 1) {
2888 // If the register name is one of those that appear in the condition below
2889 // and the special register builtin being used is one of the write builtins,
2890 // then we require that the argument provided for writing to the register
2891 // is an integer constant expression. This is because it will be lowered to
2892 // an MSR (immediate) instruction, so we need to know the immediate at
2893 // compile time.
2894 if (TheCall->getNumArgs() != 2)
2895 return false;
2896
2897 std::string RegLower = Reg.lower();
2898 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
2899 RegLower != "pan" && RegLower != "uao")
2900 return false;
2901
2902 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2903 }
2904
2905 return false;
2906}
2907
Eric Christopherd9832702015-06-29 21:00:05 +00002908/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
2909/// This checks that the target supports __builtin_cpu_supports and
2910/// that the string argument is constant and valid.
2911bool Sema::SemaBuiltinCpuSupports(CallExpr *TheCall) {
2912 Expr *Arg = TheCall->getArg(0);
2913
2914 // Check if the argument is a string literal.
2915 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2916 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2917 << Arg->getSourceRange();
2918
2919 // Check the contents of the string.
2920 StringRef Feature =
2921 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2922 if (!Context.getTargetInfo().validateCpuSupports(Feature))
2923 return Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
2924 << Arg->getSourceRange();
2925 return false;
2926}
2927
Eli Friedmanc97d0142009-05-03 06:04:26 +00002928/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002929/// This checks that the target supports __builtin_longjmp and
2930/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002931bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002932 if (!Context.getTargetInfo().hasSjLjLowering())
2933 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
2934 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2935
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002936 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002937 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002938
Eric Christopher8d0c6212010-04-17 02:26:23 +00002939 // TODO: This is less than ideal. Overload this to take a value.
2940 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2941 return true;
2942
2943 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002944 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2945 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2946
2947 return false;
2948}
2949
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002950
2951/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
2952/// This checks that the target supports __builtin_setjmp.
2953bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
2954 if (!Context.getTargetInfo().hasSjLjLowering())
2955 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
2956 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2957 return false;
2958}
2959
Richard Smithd7293d72013-08-05 18:49:43 +00002960namespace {
2961enum StringLiteralCheckType {
2962 SLCT_NotALiteral,
2963 SLCT_UncheckedLiteral,
2964 SLCT_CheckedLiteral
2965};
2966}
2967
Richard Smith55ce3522012-06-25 20:30:08 +00002968// Determine if an expression is a string literal or constant string.
2969// If this function returns false on the arguments to a function expecting a
2970// format string, we will usually need to emit a warning.
2971// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002972static StringLiteralCheckType
2973checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2974 bool HasVAListArg, unsigned format_idx,
2975 unsigned firstDataArg, Sema::FormatStringType Type,
2976 Sema::VariadicCallType CallType, bool InFunctionCall,
2977 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002978 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002979 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002980 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002981
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002982 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002983
Richard Smithd7293d72013-08-05 18:49:43 +00002984 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002985 // Technically -Wformat-nonliteral does not warn about this case.
2986 // The behavior of printf and friends in this case is implementation
2987 // dependent. Ideally if the format string cannot be null then
2988 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002989 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002990
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002991 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002992 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002993 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002994 // The expression is a literal if both sub-expressions were, and it was
2995 // completely checked only if both sub-expressions were checked.
2996 const AbstractConditionalOperator *C =
2997 cast<AbstractConditionalOperator>(E);
2998 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002999 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003000 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003001 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003002 if (Left == SLCT_NotALiteral)
3003 return SLCT_NotALiteral;
3004 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00003005 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003006 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003007 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003008 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003009 }
3010
3011 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00003012 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3013 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003014 }
3015
John McCallc07a0c72011-02-17 10:25:35 +00003016 case Stmt::OpaqueValueExprClass:
3017 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3018 E = src;
3019 goto tryAgain;
3020 }
Richard Smith55ce3522012-06-25 20:30:08 +00003021 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00003022
Ted Kremeneka8890832011-02-24 23:03:04 +00003023 case Stmt::PredefinedExprClass:
3024 // While __func__, etc., are technically not string literals, they
3025 // cannot contain format specifiers and thus are not a security
3026 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00003027 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00003028
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003029 case Stmt::DeclRefExprClass: {
3030 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003031
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003032 // As an exception, do not flag errors for variables binding to
3033 // const string literals.
3034 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3035 bool isConstant = false;
3036 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003037
Richard Smithd7293d72013-08-05 18:49:43 +00003038 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3039 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003040 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00003041 isConstant = T.isConstant(S.Context) &&
3042 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00003043 } else if (T->isObjCObjectPointerType()) {
3044 // In ObjC, there is usually no "const ObjectPointer" type,
3045 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00003046 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003047 }
Mike Stump11289f42009-09-09 15:08:12 +00003048
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003049 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003050 if (const Expr *Init = VD->getAnyInitializer()) {
3051 // Look through initializers like const char c[] = { "foo" }
3052 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3053 if (InitList->isStringLiteralInit())
3054 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3055 }
Richard Smithd7293d72013-08-05 18:49:43 +00003056 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003057 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003058 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003059 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003060 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003061 }
Mike Stump11289f42009-09-09 15:08:12 +00003062
Anders Carlssonb012ca92009-06-28 19:55:58 +00003063 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3064 // special check to see if the format string is a function parameter
3065 // of the function calling the printf function. If the function
3066 // has an attribute indicating it is a printf-like function, then we
3067 // should suppress warnings concerning non-literals being used in a call
3068 // to a vprintf function. For example:
3069 //
3070 // void
3071 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3072 // va_list ap;
3073 // va_start(ap, fmt);
3074 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3075 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00003076 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003077 if (HasVAListArg) {
3078 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3079 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3080 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003081 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003082 // adjust for implicit parameter
3083 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3084 if (MD->isInstance())
3085 ++PVIndex;
3086 // We also check if the formats are compatible.
3087 // We can't pass a 'scanf' string to a 'printf' function.
3088 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00003089 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00003090 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003091 }
3092 }
3093 }
3094 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003095 }
Mike Stump11289f42009-09-09 15:08:12 +00003096
Richard Smith55ce3522012-06-25 20:30:08 +00003097 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003098 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003099
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003100 case Stmt::CallExprClass:
3101 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003102 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003103 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3104 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3105 unsigned ArgIndex = FA->getFormatIdx();
3106 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3107 if (MD->isInstance())
3108 --ArgIndex;
3109 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00003110
Richard Smithd7293d72013-08-05 18:49:43 +00003111 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003112 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003113 Type, CallType, InFunctionCall,
3114 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003115 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3116 unsigned BuiltinID = FD->getBuiltinID();
3117 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3118 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3119 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00003120 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003121 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003122 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003123 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003124 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003125 }
3126 }
Mike Stump11289f42009-09-09 15:08:12 +00003127
Richard Smith55ce3522012-06-25 20:30:08 +00003128 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003129 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003130 case Stmt::ObjCStringLiteralClass:
3131 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00003132 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003133
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003134 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003135 StrE = ObjCFExpr->getString();
3136 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003137 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003138
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003139 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00003140 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
3141 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003142 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003143 }
Mike Stump11289f42009-09-09 15:08:12 +00003144
Richard Smith55ce3522012-06-25 20:30:08 +00003145 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003146 }
Mike Stump11289f42009-09-09 15:08:12 +00003147
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003148 default:
Richard Smith55ce3522012-06-25 20:30:08 +00003149 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003150 }
3151}
3152
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003153Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003154 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003155 .Case("scanf", FST_Scanf)
3156 .Cases("printf", "printf0", FST_Printf)
3157 .Cases("NSString", "CFString", FST_NSString)
3158 .Case("strftime", FST_Strftime)
3159 .Case("strfmon", FST_Strfmon)
3160 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003161 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00003162 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003163 .Default(FST_Unknown);
3164}
3165
Jordan Rose3e0ec582012-07-19 18:10:23 +00003166/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00003167/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003168/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003169bool Sema::CheckFormatArguments(const FormatAttr *Format,
3170 ArrayRef<const Expr *> Args,
3171 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003172 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003173 SourceLocation Loc, SourceRange Range,
3174 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00003175 FormatStringInfo FSI;
3176 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003177 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00003178 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00003179 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003180 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003181}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003182
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003183bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003184 bool HasVAListArg, unsigned format_idx,
3185 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003186 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003187 SourceLocation Loc, SourceRange Range,
3188 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003189 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003190 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003191 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00003192 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003193 }
Mike Stump11289f42009-09-09 15:08:12 +00003194
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003195 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003196
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003197 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00003198 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003199 // Dynamically generated format strings are difficult to
3200 // automatically vet at compile time. Requiring that format strings
3201 // are string literals: (1) permits the checking of format strings by
3202 // the compiler and thereby (2) can practically remove the source of
3203 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00003204
Mike Stump11289f42009-09-09 15:08:12 +00003205 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00003206 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00003207 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00003208 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003209 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00003210 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3211 format_idx, firstDataArg, Type, CallType,
3212 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003213 if (CT != SLCT_NotALiteral)
3214 // Literal format string found, check done!
3215 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00003216
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003217 // Strftime is particular as it always uses a single 'time' argument,
3218 // so it is safe to pass a non-literal string.
3219 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00003220 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003221
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003222 // Do not emit diag when the string param is a macro expansion and the
3223 // format is either NSString or CFString. This is a hack to prevent
3224 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3225 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00003226 if (Type == FST_NSString &&
3227 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00003228 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003229
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003230 // If there are no arguments specified, warn with -Wformat-security, otherwise
3231 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00003232 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003233 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003234 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003235 << OrigFormatExpr->getSourceRange();
3236 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003237 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003238 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003239 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00003240 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003241}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003242
Ted Kremenekab278de2010-01-28 23:39:18 +00003243namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00003244class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3245protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00003246 Sema &S;
3247 const StringLiteral *FExpr;
3248 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003249 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00003250 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00003251 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00003252 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003253 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00003254 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00003255 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00003256 bool usesPositionalArgs;
3257 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003258 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00003259 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00003260 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003261public:
Ted Kremenek02087932010-07-16 02:11:22 +00003262 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003263 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003264 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003265 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003266 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003267 Sema::VariadicCallType callType,
3268 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00003269 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003270 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3271 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003272 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00003273 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00003274 inFunctionCall(inFunctionCall), CallType(callType),
3275 CheckedVarArgs(CheckedVarArgs) {
3276 CoveredArgs.resize(numDataArgs);
3277 CoveredArgs.reset();
3278 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003279
Ted Kremenek019d2242010-01-29 01:50:07 +00003280 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003281
Ted Kremenek02087932010-07-16 02:11:22 +00003282 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003283 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003284
Jordan Rose92303592012-09-08 04:00:03 +00003285 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003286 const analyze_format_string::FormatSpecifier &FS,
3287 const analyze_format_string::ConversionSpecifier &CS,
3288 const char *startSpecifier, unsigned specifierLen,
3289 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00003290
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003291 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003292 const analyze_format_string::FormatSpecifier &FS,
3293 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003294
3295 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003296 const analyze_format_string::ConversionSpecifier &CS,
3297 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003298
Craig Toppere14c0f82014-03-12 04:55:44 +00003299 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003300
Craig Toppere14c0f82014-03-12 04:55:44 +00003301 void HandleInvalidPosition(const char *startSpecifier,
3302 unsigned specifierLen,
3303 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003304
Craig Toppere14c0f82014-03-12 04:55:44 +00003305 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003306
Craig Toppere14c0f82014-03-12 04:55:44 +00003307 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003308
Richard Trieu03cf7b72011-10-28 00:41:25 +00003309 template <typename Range>
3310 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3311 const Expr *ArgumentExpr,
3312 PartialDiagnostic PDiag,
3313 SourceLocation StringLoc,
3314 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003315 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003316
Ted Kremenek02087932010-07-16 02:11:22 +00003317protected:
Ted Kremenekce815422010-07-19 21:25:57 +00003318 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3319 const char *startSpec,
3320 unsigned specifierLen,
3321 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003322
3323 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
3324 const char *startSpec,
3325 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003326
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003327 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00003328 CharSourceRange getSpecifierRange(const char *startSpecifier,
3329 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00003330 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003331
Ted Kremenek5739de72010-01-29 01:06:55 +00003332 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003333
3334 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
3335 const analyze_format_string::ConversionSpecifier &CS,
3336 const char *startSpecifier, unsigned specifierLen,
3337 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003338
3339 template <typename Range>
3340 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3341 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003342 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00003343};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003344}
Ted Kremenekab278de2010-01-28 23:39:18 +00003345
Ted Kremenek02087932010-07-16 02:11:22 +00003346SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00003347 return OrigFormatExpr->getSourceRange();
3348}
3349
Ted Kremenek02087932010-07-16 02:11:22 +00003350CharSourceRange CheckFormatHandler::
3351getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00003352 SourceLocation Start = getLocationOfByte(startSpecifier);
3353 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3354
3355 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003356 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00003357
3358 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003359}
3360
Ted Kremenek02087932010-07-16 02:11:22 +00003361SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003362 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00003363}
3364
Ted Kremenek02087932010-07-16 02:11:22 +00003365void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
3366 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00003367 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
3368 getLocationOfByte(startSpecifier),
3369 /*IsStringLocation*/true,
3370 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00003371}
3372
Jordan Rose92303592012-09-08 04:00:03 +00003373void CheckFormatHandler::HandleInvalidLengthModifier(
3374 const analyze_format_string::FormatSpecifier &FS,
3375 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00003376 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00003377 using namespace analyze_format_string;
3378
3379 const LengthModifier &LM = FS.getLengthModifier();
3380 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3381
3382 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003383 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00003384 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003385 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003386 getLocationOfByte(LM.getStart()),
3387 /*IsStringLocation*/true,
3388 getSpecifierRange(startSpecifier, specifierLen));
3389
3390 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3391 << FixedLM->toString()
3392 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3393
3394 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003395 FixItHint Hint;
3396 if (DiagID == diag::warn_format_nonsensical_length)
3397 Hint = FixItHint::CreateRemoval(LMRange);
3398
3399 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003400 getLocationOfByte(LM.getStart()),
3401 /*IsStringLocation*/true,
3402 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00003403 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00003404 }
3405}
3406
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003407void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00003408 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003409 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003410 using namespace analyze_format_string;
3411
3412 const LengthModifier &LM = FS.getLengthModifier();
3413 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3414
3415 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003416 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00003417 if (FixedLM) {
3418 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3419 << LM.toString() << 0,
3420 getLocationOfByte(LM.getStart()),
3421 /*IsStringLocation*/true,
3422 getSpecifierRange(startSpecifier, specifierLen));
3423
3424 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3425 << FixedLM->toString()
3426 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3427
3428 } else {
3429 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3430 << LM.toString() << 0,
3431 getLocationOfByte(LM.getStart()),
3432 /*IsStringLocation*/true,
3433 getSpecifierRange(startSpecifier, specifierLen));
3434 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003435}
3436
3437void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3438 const analyze_format_string::ConversionSpecifier &CS,
3439 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00003440 using namespace analyze_format_string;
3441
3442 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00003443 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00003444 if (FixedCS) {
3445 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3446 << CS.toString() << /*conversion specifier*/1,
3447 getLocationOfByte(CS.getStart()),
3448 /*IsStringLocation*/true,
3449 getSpecifierRange(startSpecifier, specifierLen));
3450
3451 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3452 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3453 << FixedCS->toString()
3454 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3455 } else {
3456 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3457 << CS.toString() << /*conversion specifier*/1,
3458 getLocationOfByte(CS.getStart()),
3459 /*IsStringLocation*/true,
3460 getSpecifierRange(startSpecifier, specifierLen));
3461 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003462}
3463
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003464void CheckFormatHandler::HandlePosition(const char *startPos,
3465 unsigned posLen) {
3466 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3467 getLocationOfByte(startPos),
3468 /*IsStringLocation*/true,
3469 getSpecifierRange(startPos, posLen));
3470}
3471
Ted Kremenekd1668192010-02-27 01:41:03 +00003472void
Ted Kremenek02087932010-07-16 02:11:22 +00003473CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3474 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003475 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3476 << (unsigned) p,
3477 getLocationOfByte(startPos), /*IsStringLocation*/true,
3478 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003479}
3480
Ted Kremenek02087932010-07-16 02:11:22 +00003481void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003482 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003483 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3484 getLocationOfByte(startPos),
3485 /*IsStringLocation*/true,
3486 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003487}
3488
Ted Kremenek02087932010-07-16 02:11:22 +00003489void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003490 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003491 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003492 EmitFormatDiagnostic(
3493 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3494 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3495 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003496 }
Ted Kremenek02087932010-07-16 02:11:22 +00003497}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003498
Jordan Rose58bbe422012-07-19 18:10:08 +00003499// Note that this may return NULL if there was an error parsing or building
3500// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003501const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003502 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003503}
3504
3505void CheckFormatHandler::DoneProcessing() {
3506 // Does the number of data arguments exceed the number of
3507 // format conversions in the format string?
3508 if (!HasVAListArg) {
3509 // Find any arguments that weren't covered.
3510 CoveredArgs.flip();
3511 signed notCoveredArg = CoveredArgs.find_first();
3512 if (notCoveredArg >= 0) {
3513 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00003514 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3515 SourceLocation Loc = E->getLocStart();
3516 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3517 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3518 Loc, /*IsStringLocation*/false,
3519 getFormatStringRange());
3520 }
Bob Wilson23cd4342012-05-03 19:47:19 +00003521 }
Ted Kremenek02087932010-07-16 02:11:22 +00003522 }
3523 }
3524}
3525
Ted Kremenekce815422010-07-19 21:25:57 +00003526bool
3527CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3528 SourceLocation Loc,
3529 const char *startSpec,
3530 unsigned specifierLen,
3531 const char *csStart,
3532 unsigned csLen) {
3533
3534 bool keepGoing = true;
3535 if (argIndex < NumDataArgs) {
3536 // Consider the argument coverered, even though the specifier doesn't
3537 // make sense.
3538 CoveredArgs.set(argIndex);
3539 }
3540 else {
3541 // If argIndex exceeds the number of data arguments we
3542 // don't issue a warning because that is just a cascade of warnings (and
3543 // they may have intended '%%' anyway). We don't want to continue processing
3544 // the format string after this point, however, as we will like just get
3545 // gibberish when trying to match arguments.
3546 keepGoing = false;
3547 }
3548
Richard Trieu03cf7b72011-10-28 00:41:25 +00003549 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3550 << StringRef(csStart, csLen),
3551 Loc, /*IsStringLocation*/true,
3552 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003553
3554 return keepGoing;
3555}
3556
Richard Trieu03cf7b72011-10-28 00:41:25 +00003557void
3558CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3559 const char *startSpec,
3560 unsigned specifierLen) {
3561 EmitFormatDiagnostic(
3562 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3563 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3564}
3565
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003566bool
3567CheckFormatHandler::CheckNumArgs(
3568 const analyze_format_string::FormatSpecifier &FS,
3569 const analyze_format_string::ConversionSpecifier &CS,
3570 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3571
3572 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003573 PartialDiagnostic PDiag = FS.usesPositionalArg()
3574 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3575 << (argIndex+1) << NumDataArgs)
3576 : S.PDiag(diag::warn_printf_insufficient_data_args);
3577 EmitFormatDiagnostic(
3578 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3579 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003580 return false;
3581 }
3582 return true;
3583}
3584
Richard Trieu03cf7b72011-10-28 00:41:25 +00003585template<typename Range>
3586void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3587 SourceLocation Loc,
3588 bool IsStringLocation,
3589 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003590 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003591 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003592 Loc, IsStringLocation, StringRange, FixIt);
3593}
3594
3595/// \brief If the format string is not within the funcion call, emit a note
3596/// so that the function call and string are in diagnostic messages.
3597///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003598/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003599/// call and only one diagnostic message will be produced. Otherwise, an
3600/// extra note will be emitted pointing to location of the format string.
3601///
3602/// \param ArgumentExpr the expression that is passed as the format string
3603/// argument in the function call. Used for getting locations when two
3604/// diagnostics are emitted.
3605///
3606/// \param PDiag the callee should already have provided any strings for the
3607/// diagnostic message. This function only adds locations and fixits
3608/// to diagnostics.
3609///
3610/// \param Loc primary location for diagnostic. If two diagnostics are
3611/// required, one will be at Loc and a new SourceLocation will be created for
3612/// the other one.
3613///
3614/// \param IsStringLocation if true, Loc points to the format string should be
3615/// used for the note. Otherwise, Loc points to the argument list and will
3616/// be used with PDiag.
3617///
3618/// \param StringRange some or all of the string to highlight. This is
3619/// templated so it can accept either a CharSourceRange or a SourceRange.
3620///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003621/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003622template<typename Range>
3623void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3624 const Expr *ArgumentExpr,
3625 PartialDiagnostic PDiag,
3626 SourceLocation Loc,
3627 bool IsStringLocation,
3628 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003629 ArrayRef<FixItHint> FixIt) {
3630 if (InFunctionCall) {
3631 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3632 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003633 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00003634 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003635 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3636 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003637
3638 const Sema::SemaDiagnosticBuilder &Note =
3639 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3640 diag::note_format_string_defined);
3641
3642 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003643 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003644 }
3645}
3646
Ted Kremenek02087932010-07-16 02:11:22 +00003647//===--- CHECK: Printf format string checking ------------------------------===//
3648
3649namespace {
3650class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003651 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00003652public:
3653 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3654 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003655 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003656 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003657 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003658 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003659 Sema::VariadicCallType CallType,
3660 llvm::SmallBitVector &CheckedVarArgs)
3661 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3662 numDataArgs, beg, hasVAListArg, Args,
3663 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3664 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003665 {}
3666
Craig Toppere14c0f82014-03-12 04:55:44 +00003667
Ted Kremenek02087932010-07-16 02:11:22 +00003668 bool HandleInvalidPrintfConversionSpecifier(
3669 const analyze_printf::PrintfSpecifier &FS,
3670 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003671 unsigned specifierLen) override;
3672
Ted Kremenek02087932010-07-16 02:11:22 +00003673 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3674 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003675 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003676 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3677 const char *StartSpecifier,
3678 unsigned SpecifierLen,
3679 const Expr *E);
3680
Ted Kremenek02087932010-07-16 02:11:22 +00003681 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3682 const char *startSpecifier, unsigned specifierLen);
3683 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3684 const analyze_printf::OptionalAmount &Amt,
3685 unsigned type,
3686 const char *startSpecifier, unsigned specifierLen);
3687 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3688 const analyze_printf::OptionalFlag &flag,
3689 const char *startSpecifier, unsigned specifierLen);
3690 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3691 const analyze_printf::OptionalFlag &ignoredFlag,
3692 const analyze_printf::OptionalFlag &flag,
3693 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003694 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003695 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00003696
3697 void HandleEmptyObjCModifierFlag(const char *startFlag,
3698 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003699
Ted Kremenek2b417712015-07-02 05:39:16 +00003700 void HandleInvalidObjCModifierFlag(const char *startFlag,
3701 unsigned flagLen) override;
3702
3703 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
3704 const char *flagsEnd,
3705 const char *conversionPosition)
3706 override;
3707};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003708}
Ted Kremenek02087932010-07-16 02:11:22 +00003709
3710bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3711 const analyze_printf::PrintfSpecifier &FS,
3712 const char *startSpecifier,
3713 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003714 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003715 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003716
Ted Kremenekce815422010-07-19 21:25:57 +00003717 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3718 getLocationOfByte(CS.getStart()),
3719 startSpecifier, specifierLen,
3720 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003721}
3722
Ted Kremenek02087932010-07-16 02:11:22 +00003723bool CheckPrintfHandler::HandleAmount(
3724 const analyze_format_string::OptionalAmount &Amt,
3725 unsigned k, const char *startSpecifier,
3726 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003727
3728 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003729 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003730 unsigned argIndex = Amt.getArgIndex();
3731 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003732 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3733 << k,
3734 getLocationOfByte(Amt.getStart()),
3735 /*IsStringLocation*/true,
3736 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003737 // Don't do any more checking. We will just emit
3738 // spurious errors.
3739 return false;
3740 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003741
Ted Kremenek5739de72010-01-29 01:06:55 +00003742 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00003743 // Although not in conformance with C99, we also allow the argument to be
3744 // an 'unsigned int' as that is a reasonably safe case. GCC also
3745 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003746 CoveredArgs.set(argIndex);
3747 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003748 if (!Arg)
3749 return false;
3750
Ted Kremenek5739de72010-01-29 01:06:55 +00003751 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003752
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003753 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3754 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003755
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003756 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003757 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003758 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003759 << T << Arg->getSourceRange(),
3760 getLocationOfByte(Amt.getStart()),
3761 /*IsStringLocation*/true,
3762 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003763 // Don't do any more checking. We will just emit
3764 // spurious errors.
3765 return false;
3766 }
3767 }
3768 }
3769 return true;
3770}
Ted Kremenek5739de72010-01-29 01:06:55 +00003771
Tom Careb49ec692010-06-17 19:00:27 +00003772void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003773 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003774 const analyze_printf::OptionalAmount &Amt,
3775 unsigned type,
3776 const char *startSpecifier,
3777 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003778 const analyze_printf::PrintfConversionSpecifier &CS =
3779 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003780
Richard Trieu03cf7b72011-10-28 00:41:25 +00003781 FixItHint fixit =
3782 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3783 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3784 Amt.getConstantLength()))
3785 : FixItHint();
3786
3787 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3788 << type << CS.toString(),
3789 getLocationOfByte(Amt.getStart()),
3790 /*IsStringLocation*/true,
3791 getSpecifierRange(startSpecifier, specifierLen),
3792 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003793}
3794
Ted Kremenek02087932010-07-16 02:11:22 +00003795void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003796 const analyze_printf::OptionalFlag &flag,
3797 const char *startSpecifier,
3798 unsigned specifierLen) {
3799 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003800 const analyze_printf::PrintfConversionSpecifier &CS =
3801 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003802 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3803 << flag.toString() << CS.toString(),
3804 getLocationOfByte(flag.getPosition()),
3805 /*IsStringLocation*/true,
3806 getSpecifierRange(startSpecifier, specifierLen),
3807 FixItHint::CreateRemoval(
3808 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003809}
3810
3811void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003812 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003813 const analyze_printf::OptionalFlag &ignoredFlag,
3814 const analyze_printf::OptionalFlag &flag,
3815 const char *startSpecifier,
3816 unsigned specifierLen) {
3817 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003818 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3819 << ignoredFlag.toString() << flag.toString(),
3820 getLocationOfByte(ignoredFlag.getPosition()),
3821 /*IsStringLocation*/true,
3822 getSpecifierRange(startSpecifier, specifierLen),
3823 FixItHint::CreateRemoval(
3824 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003825}
3826
Ted Kremenek2b417712015-07-02 05:39:16 +00003827// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3828// bool IsStringLocation, Range StringRange,
3829// ArrayRef<FixItHint> Fixit = None);
3830
3831void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
3832 unsigned flagLen) {
3833 // Warn about an empty flag.
3834 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
3835 getLocationOfByte(startFlag),
3836 /*IsStringLocation*/true,
3837 getSpecifierRange(startFlag, flagLen));
3838}
3839
3840void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
3841 unsigned flagLen) {
3842 // Warn about an invalid flag.
3843 auto Range = getSpecifierRange(startFlag, flagLen);
3844 StringRef flag(startFlag, flagLen);
3845 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
3846 getLocationOfByte(startFlag),
3847 /*IsStringLocation*/true,
3848 Range, FixItHint::CreateRemoval(Range));
3849}
3850
3851void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
3852 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
3853 // Warn about using '[...]' without a '@' conversion.
3854 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
3855 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
3856 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
3857 getLocationOfByte(conversionPosition),
3858 /*IsStringLocation*/true,
3859 Range, FixItHint::CreateRemoval(Range));
3860}
3861
Richard Smith55ce3522012-06-25 20:30:08 +00003862// Determines if the specified is a C++ class or struct containing
3863// a member with the specified name and kind (e.g. a CXXMethodDecl named
3864// "c_str()").
3865template<typename MemberKind>
3866static llvm::SmallPtrSet<MemberKind*, 1>
3867CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3868 const RecordType *RT = Ty->getAs<RecordType>();
3869 llvm::SmallPtrSet<MemberKind*, 1> Results;
3870
3871 if (!RT)
3872 return Results;
3873 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003874 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003875 return Results;
3876
Alp Tokerb6cc5922014-05-03 03:45:55 +00003877 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003878 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003879 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003880
3881 // We just need to include all members of the right kind turned up by the
3882 // filter, at this point.
3883 if (S.LookupQualifiedName(R, RT->getDecl()))
3884 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3885 NamedDecl *decl = (*I)->getUnderlyingDecl();
3886 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3887 Results.insert(FK);
3888 }
3889 return Results;
3890}
3891
Richard Smith2868a732014-02-28 01:36:39 +00003892/// Check if we could call '.c_str()' on an object.
3893///
3894/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3895/// allow the call, or if it would be ambiguous).
3896bool Sema::hasCStrMethod(const Expr *E) {
3897 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3898 MethodSet Results =
3899 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3900 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3901 MI != ME; ++MI)
3902 if ((*MI)->getMinRequiredArguments() == 0)
3903 return true;
3904 return false;
3905}
3906
Richard Smith55ce3522012-06-25 20:30:08 +00003907// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003908// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003909// Returns true when a c_str() conversion method is found.
3910bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003911 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003912 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3913
3914 MethodSet Results =
3915 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3916
3917 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3918 MI != ME; ++MI) {
3919 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003920 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003921 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003922 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003923 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003924 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3925 << "c_str()"
3926 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3927 return true;
3928 }
3929 }
3930
3931 return false;
3932}
3933
Ted Kremenekab278de2010-01-28 23:39:18 +00003934bool
Ted Kremenek02087932010-07-16 02:11:22 +00003935CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003936 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003937 const char *startSpecifier,
3938 unsigned specifierLen) {
3939
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003940 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003941 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003942 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003943
Ted Kremenek6cd69422010-07-19 22:01:06 +00003944 if (FS.consumesDataArgument()) {
3945 if (atFirstArg) {
3946 atFirstArg = false;
3947 usesPositionalArgs = FS.usesPositionalArg();
3948 }
3949 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003950 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3951 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003952 return false;
3953 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003954 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003955
Ted Kremenekd1668192010-02-27 01:41:03 +00003956 // First check if the field width, precision, and conversion specifier
3957 // have matching data arguments.
3958 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3959 startSpecifier, specifierLen)) {
3960 return false;
3961 }
3962
3963 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3964 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003965 return false;
3966 }
3967
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003968 if (!CS.consumesDataArgument()) {
3969 // FIXME: Technically specifying a precision or field width here
3970 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003971 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003972 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003973
Ted Kremenek4a49d982010-02-26 19:18:41 +00003974 // Consume the argument.
3975 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003976 if (argIndex < NumDataArgs) {
3977 // The check to see if the argIndex is valid will come later.
3978 // We set the bit here because we may exit early from this
3979 // function if we encounter some other error.
3980 CoveredArgs.set(argIndex);
3981 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003982
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003983 // FreeBSD kernel extensions.
3984 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
3985 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
3986 // We need at least two arguments.
3987 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
3988 return false;
3989
3990 // Claim the second argument.
3991 CoveredArgs.set(argIndex + 1);
3992
3993 // Type check the first argument (int for %b, pointer for %D)
3994 const Expr *Ex = getDataArg(argIndex);
3995 const analyze_printf::ArgType &AT =
3996 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
3997 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
3998 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
3999 EmitFormatDiagnostic(
4000 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4001 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4002 << false << Ex->getSourceRange(),
4003 Ex->getLocStart(), /*IsStringLocation*/false,
4004 getSpecifierRange(startSpecifier, specifierLen));
4005
4006 // Type check the second argument (char * for both %b and %D)
4007 Ex = getDataArg(argIndex + 1);
4008 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4009 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4010 EmitFormatDiagnostic(
4011 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4012 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4013 << false << Ex->getSourceRange(),
4014 Ex->getLocStart(), /*IsStringLocation*/false,
4015 getSpecifierRange(startSpecifier, specifierLen));
4016
4017 return true;
4018 }
4019
Ted Kremenek4a49d982010-02-26 19:18:41 +00004020 // Check for using an Objective-C specific conversion specifier
4021 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004022 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00004023 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4024 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00004025 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004026
Tom Careb49ec692010-06-17 19:00:27 +00004027 // Check for invalid use of field width
4028 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00004029 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00004030 startSpecifier, specifierLen);
4031 }
4032
4033 // Check for invalid use of precision
4034 if (!FS.hasValidPrecision()) {
4035 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4036 startSpecifier, specifierLen);
4037 }
4038
4039 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00004040 if (!FS.hasValidThousandsGroupingPrefix())
4041 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004042 if (!FS.hasValidLeadingZeros())
4043 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4044 if (!FS.hasValidPlusPrefix())
4045 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00004046 if (!FS.hasValidSpacePrefix())
4047 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004048 if (!FS.hasValidAlternativeForm())
4049 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4050 if (!FS.hasValidLeftJustified())
4051 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4052
4053 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00004054 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4055 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4056 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004057 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4058 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4059 startSpecifier, specifierLen);
4060
4061 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004062 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004063 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4064 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004065 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004066 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004067 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004068 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4069 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00004070
Jordan Rose92303592012-09-08 04:00:03 +00004071 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4072 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4073
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004074 // The remaining checks depend on the data arguments.
4075 if (HasVAListArg)
4076 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004077
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004078 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004079 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004080
Jordan Rose58bbe422012-07-19 18:10:08 +00004081 const Expr *Arg = getDataArg(argIndex);
4082 if (!Arg)
4083 return true;
4084
4085 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00004086}
4087
Jordan Roseaee34382012-09-05 22:56:26 +00004088static bool requiresParensToAddCast(const Expr *E) {
4089 // FIXME: We should have a general way to reason about operator
4090 // precedence and whether parens are actually needed here.
4091 // Take care of a few common cases where they aren't.
4092 const Expr *Inside = E->IgnoreImpCasts();
4093 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
4094 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
4095
4096 switch (Inside->getStmtClass()) {
4097 case Stmt::ArraySubscriptExprClass:
4098 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004099 case Stmt::CharacterLiteralClass:
4100 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004101 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004102 case Stmt::FloatingLiteralClass:
4103 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004104 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004105 case Stmt::ObjCArrayLiteralClass:
4106 case Stmt::ObjCBoolLiteralExprClass:
4107 case Stmt::ObjCBoxedExprClass:
4108 case Stmt::ObjCDictionaryLiteralClass:
4109 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004110 case Stmt::ObjCIvarRefExprClass:
4111 case Stmt::ObjCMessageExprClass:
4112 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004113 case Stmt::ObjCStringLiteralClass:
4114 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004115 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004116 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004117 case Stmt::UnaryOperatorClass:
4118 return false;
4119 default:
4120 return true;
4121 }
4122}
4123
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004124static std::pair<QualType, StringRef>
4125shouldNotPrintDirectly(const ASTContext &Context,
4126 QualType IntendedTy,
4127 const Expr *E) {
4128 // Use a 'while' to peel off layers of typedefs.
4129 QualType TyTy = IntendedTy;
4130 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
4131 StringRef Name = UserTy->getDecl()->getName();
4132 QualType CastTy = llvm::StringSwitch<QualType>(Name)
4133 .Case("NSInteger", Context.LongTy)
4134 .Case("NSUInteger", Context.UnsignedLongTy)
4135 .Case("SInt32", Context.IntTy)
4136 .Case("UInt32", Context.UnsignedIntTy)
4137 .Default(QualType());
4138
4139 if (!CastTy.isNull())
4140 return std::make_pair(CastTy, Name);
4141
4142 TyTy = UserTy->desugar();
4143 }
4144
4145 // Strip parens if necessary.
4146 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4147 return shouldNotPrintDirectly(Context,
4148 PE->getSubExpr()->getType(),
4149 PE->getSubExpr());
4150
4151 // If this is a conditional expression, then its result type is constructed
4152 // via usual arithmetic conversions and thus there might be no necessary
4153 // typedef sugar there. Recurse to operands to check for NSInteger &
4154 // Co. usage condition.
4155 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4156 QualType TrueTy, FalseTy;
4157 StringRef TrueName, FalseName;
4158
4159 std::tie(TrueTy, TrueName) =
4160 shouldNotPrintDirectly(Context,
4161 CO->getTrueExpr()->getType(),
4162 CO->getTrueExpr());
4163 std::tie(FalseTy, FalseName) =
4164 shouldNotPrintDirectly(Context,
4165 CO->getFalseExpr()->getType(),
4166 CO->getFalseExpr());
4167
4168 if (TrueTy == FalseTy)
4169 return std::make_pair(TrueTy, TrueName);
4170 else if (TrueTy.isNull())
4171 return std::make_pair(FalseTy, FalseName);
4172 else if (FalseTy.isNull())
4173 return std::make_pair(TrueTy, TrueName);
4174 }
4175
4176 return std::make_pair(QualType(), StringRef());
4177}
4178
Richard Smith55ce3522012-06-25 20:30:08 +00004179bool
4180CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4181 const char *StartSpecifier,
4182 unsigned SpecifierLen,
4183 const Expr *E) {
4184 using namespace analyze_format_string;
4185 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004186 // Now type check the data expression that matches the
4187 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004188 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4189 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00004190 if (!AT.isValid())
4191 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00004192
Jordan Rose598ec092012-12-05 18:44:40 +00004193 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00004194 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4195 ExprTy = TET->getUnderlyingExpr()->getType();
4196 }
4197
Seth Cantrellb4802962015-03-04 03:12:10 +00004198 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4199
4200 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00004201 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004202 }
Jordan Rose98709982012-06-04 22:48:57 +00004203
Jordan Rose22b74712012-09-05 22:56:19 +00004204 // Look through argument promotions for our error message's reported type.
4205 // This includes the integral and floating promotions, but excludes array
4206 // and function pointer decay; seeing that an argument intended to be a
4207 // string has type 'char [6]' is probably more confusing than 'char *'.
4208 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4209 if (ICE->getCastKind() == CK_IntegralCast ||
4210 ICE->getCastKind() == CK_FloatingCast) {
4211 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00004212 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00004213
4214 // Check if we didn't match because of an implicit cast from a 'char'
4215 // or 'short' to an 'int'. This is done because printf is a varargs
4216 // function.
4217 if (ICE->getType() == S.Context.IntTy ||
4218 ICE->getType() == S.Context.UnsignedIntTy) {
4219 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00004220 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00004221 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00004222 }
Jordan Rose98709982012-06-04 22:48:57 +00004223 }
Jordan Rose598ec092012-12-05 18:44:40 +00004224 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4225 // Special case for 'a', which has type 'int' in C.
4226 // Note, however, that we do /not/ want to treat multibyte constants like
4227 // 'MooV' as characters! This form is deprecated but still exists.
4228 if (ExprTy == S.Context.IntTy)
4229 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4230 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00004231 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004232
Jordan Rosebc53ed12014-05-31 04:12:14 +00004233 // Look through enums to their underlying type.
4234 bool IsEnum = false;
4235 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4236 ExprTy = EnumTy->getDecl()->getIntegerType();
4237 IsEnum = true;
4238 }
4239
Jordan Rose0e5badd2012-12-05 18:44:49 +00004240 // %C in an Objective-C context prints a unichar, not a wchar_t.
4241 // If the argument is an integer of some kind, believe the %C and suggest
4242 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00004243 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004244 if (ObjCContext &&
4245 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4246 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4247 !ExprTy->isCharType()) {
4248 // 'unichar' is defined as a typedef of unsigned short, but we should
4249 // prefer using the typedef if it is visible.
4250 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00004251
4252 // While we are here, check if the value is an IntegerLiteral that happens
4253 // to be within the valid range.
4254 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4255 const llvm::APInt &V = IL->getValue();
4256 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4257 return true;
4258 }
4259
Jordan Rose0e5badd2012-12-05 18:44:49 +00004260 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4261 Sema::LookupOrdinaryName);
4262 if (S.LookupName(Result, S.getCurScope())) {
4263 NamedDecl *ND = Result.getFoundDecl();
4264 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4265 if (TD->getUnderlyingType() == IntendedTy)
4266 IntendedTy = S.Context.getTypedefType(TD);
4267 }
4268 }
4269 }
4270
4271 // Special-case some of Darwin's platform-independence types by suggesting
4272 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004273 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00004274 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004275 QualType CastTy;
4276 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
4277 if (!CastTy.isNull()) {
4278 IntendedTy = CastTy;
4279 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00004280 }
4281 }
4282
Jordan Rose22b74712012-09-05 22:56:19 +00004283 // We may be able to offer a FixItHint if it is a supported type.
4284 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00004285 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00004286 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004287
Jordan Rose22b74712012-09-05 22:56:19 +00004288 if (success) {
4289 // Get the fix string from the fixed format specifier
4290 SmallString<16> buf;
4291 llvm::raw_svector_ostream os(buf);
4292 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004293
Jordan Roseaee34382012-09-05 22:56:26 +00004294 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4295
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004296 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00004297 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4298 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4299 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4300 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00004301 // In this case, the specifier is wrong and should be changed to match
4302 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00004303 EmitFormatDiagnostic(S.PDiag(diag)
4304 << AT.getRepresentativeTypeName(S.Context)
4305 << IntendedTy << IsEnum << E->getSourceRange(),
4306 E->getLocStart(),
4307 /*IsStringLocation*/ false, SpecRange,
4308 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00004309
4310 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00004311 // The canonical type for formatting this value is different from the
4312 // actual type of the expression. (This occurs, for example, with Darwin's
4313 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
4314 // should be printed as 'long' for 64-bit compatibility.)
4315 // Rather than emitting a normal format/argument mismatch, we want to
4316 // add a cast to the recommended type (and correct the format string
4317 // if necessary).
4318 SmallString<16> CastBuf;
4319 llvm::raw_svector_ostream CastFix(CastBuf);
4320 CastFix << "(";
4321 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
4322 CastFix << ")";
4323
4324 SmallVector<FixItHint,4> Hints;
4325 if (!AT.matchesType(S.Context, IntendedTy))
4326 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
4327
4328 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
4329 // If there's already a cast present, just replace it.
4330 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
4331 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
4332
4333 } else if (!requiresParensToAddCast(E)) {
4334 // If the expression has high enough precedence,
4335 // just write the C-style cast.
4336 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4337 CastFix.str()));
4338 } else {
4339 // Otherwise, add parens around the expression as well as the cast.
4340 CastFix << "(";
4341 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4342 CastFix.str()));
4343
Alp Tokerb6cc5922014-05-03 03:45:55 +00004344 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00004345 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
4346 }
4347
Jordan Rose0e5badd2012-12-05 18:44:49 +00004348 if (ShouldNotPrintDirectly) {
4349 // The expression has a type that should not be printed directly.
4350 // We extract the name from the typedef because we don't want to show
4351 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004352 StringRef Name;
4353 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
4354 Name = TypedefTy->getDecl()->getName();
4355 else
4356 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004357 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00004358 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004359 << E->getSourceRange(),
4360 E->getLocStart(), /*IsStringLocation=*/false,
4361 SpecRange, Hints);
4362 } else {
4363 // In this case, the expression could be printed using a different
4364 // specifier, but we've decided that the specifier is probably correct
4365 // and we should cast instead. Just use the normal warning message.
4366 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00004367 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4368 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004369 << E->getSourceRange(),
4370 E->getLocStart(), /*IsStringLocation*/false,
4371 SpecRange, Hints);
4372 }
Jordan Roseaee34382012-09-05 22:56:26 +00004373 }
Jordan Rose22b74712012-09-05 22:56:19 +00004374 } else {
4375 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
4376 SpecifierLen);
4377 // Since the warning for passing non-POD types to variadic functions
4378 // was deferred until now, we emit a warning for non-POD
4379 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00004380 switch (S.isValidVarArgType(ExprTy)) {
4381 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00004382 case Sema::VAK_ValidInCXX11: {
4383 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4384 if (match == analyze_printf::ArgType::NoMatchPedantic) {
4385 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4386 }
Richard Smithd7293d72013-08-05 18:49:43 +00004387
Seth Cantrellb4802962015-03-04 03:12:10 +00004388 EmitFormatDiagnostic(
4389 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4390 << IsEnum << CSR << E->getSourceRange(),
4391 E->getLocStart(), /*IsStringLocation*/ false, CSR);
4392 break;
4393 }
Richard Smithd7293d72013-08-05 18:49:43 +00004394 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00004395 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00004396 EmitFormatDiagnostic(
4397 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004398 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00004399 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00004400 << CallType
4401 << AT.getRepresentativeTypeName(S.Context)
4402 << CSR
4403 << E->getSourceRange(),
4404 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00004405 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00004406 break;
4407
4408 case Sema::VAK_Invalid:
4409 if (ExprTy->isObjCObjectType())
4410 EmitFormatDiagnostic(
4411 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4412 << S.getLangOpts().CPlusPlus11
4413 << ExprTy
4414 << CallType
4415 << AT.getRepresentativeTypeName(S.Context)
4416 << CSR
4417 << E->getSourceRange(),
4418 E->getLocStart(), /*IsStringLocation*/false, CSR);
4419 else
4420 // FIXME: If this is an initializer list, suggest removing the braces
4421 // or inserting a cast to the target type.
4422 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4423 << isa<InitListExpr>(E) << ExprTy << CallType
4424 << AT.getRepresentativeTypeName(S.Context)
4425 << E->getSourceRange();
4426 break;
4427 }
4428
4429 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4430 "format string specifier index out of range");
4431 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004432 }
4433
Ted Kremenekab278de2010-01-28 23:39:18 +00004434 return true;
4435}
4436
Ted Kremenek02087932010-07-16 02:11:22 +00004437//===--- CHECK: Scanf format string checking ------------------------------===//
4438
4439namespace {
4440class CheckScanfHandler : public CheckFormatHandler {
4441public:
4442 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4443 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004444 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004445 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004446 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004447 Sema::VariadicCallType CallType,
4448 llvm::SmallBitVector &CheckedVarArgs)
4449 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4450 numDataArgs, beg, hasVAListArg,
4451 Args, formatIdx, inFunctionCall, CallType,
4452 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004453 {}
Ted Kremenek02087932010-07-16 02:11:22 +00004454
4455 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4456 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004457 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00004458
4459 bool HandleInvalidScanfConversionSpecifier(
4460 const analyze_scanf::ScanfSpecifier &FS,
4461 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004462 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004463
Craig Toppere14c0f82014-03-12 04:55:44 +00004464 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00004465};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004466}
Ted Kremenekab278de2010-01-28 23:39:18 +00004467
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004468void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4469 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004470 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4471 getLocationOfByte(end), /*IsStringLocation*/true,
4472 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004473}
4474
Ted Kremenekce815422010-07-19 21:25:57 +00004475bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4476 const analyze_scanf::ScanfSpecifier &FS,
4477 const char *startSpecifier,
4478 unsigned specifierLen) {
4479
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004480 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004481 FS.getConversionSpecifier();
4482
4483 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4484 getLocationOfByte(CS.getStart()),
4485 startSpecifier, specifierLen,
4486 CS.getStart(), CS.getLength());
4487}
4488
Ted Kremenek02087932010-07-16 02:11:22 +00004489bool CheckScanfHandler::HandleScanfSpecifier(
4490 const analyze_scanf::ScanfSpecifier &FS,
4491 const char *startSpecifier,
4492 unsigned specifierLen) {
4493
4494 using namespace analyze_scanf;
4495 using namespace analyze_format_string;
4496
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004497 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004498
Ted Kremenek6cd69422010-07-19 22:01:06 +00004499 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4500 // be used to decide if we are using positional arguments consistently.
4501 if (FS.consumesDataArgument()) {
4502 if (atFirstArg) {
4503 atFirstArg = false;
4504 usesPositionalArgs = FS.usesPositionalArg();
4505 }
4506 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004507 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4508 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004509 return false;
4510 }
Ted Kremenek02087932010-07-16 02:11:22 +00004511 }
4512
4513 // Check if the field with is non-zero.
4514 const OptionalAmount &Amt = FS.getFieldWidth();
4515 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4516 if (Amt.getConstantAmount() == 0) {
4517 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4518 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00004519 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4520 getLocationOfByte(Amt.getStart()),
4521 /*IsStringLocation*/true, R,
4522 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00004523 }
4524 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004525
Ted Kremenek02087932010-07-16 02:11:22 +00004526 if (!FS.consumesDataArgument()) {
4527 // FIXME: Technically specifying a precision or field width here
4528 // makes no sense. Worth issuing a warning at some point.
4529 return true;
4530 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004531
Ted Kremenek02087932010-07-16 02:11:22 +00004532 // Consume the argument.
4533 unsigned argIndex = FS.getArgIndex();
4534 if (argIndex < NumDataArgs) {
4535 // The check to see if the argIndex is valid will come later.
4536 // We set the bit here because we may exit early from this
4537 // function if we encounter some other error.
4538 CoveredArgs.set(argIndex);
4539 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004540
Ted Kremenek4407ea42010-07-20 20:04:47 +00004541 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004542 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004543 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4544 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004545 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004546 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004547 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004548 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4549 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004550
Jordan Rose92303592012-09-08 04:00:03 +00004551 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4552 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4553
Ted Kremenek02087932010-07-16 02:11:22 +00004554 // The remaining checks depend on the data arguments.
4555 if (HasVAListArg)
4556 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004557
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004558 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004559 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00004560
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004561 // Check that the argument type matches the format specifier.
4562 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004563 if (!Ex)
4564 return true;
4565
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004566 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00004567
4568 if (!AT.isValid()) {
4569 return true;
4570 }
4571
Seth Cantrellb4802962015-03-04 03:12:10 +00004572 analyze_format_string::ArgType::MatchKind match =
4573 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00004574 if (match == analyze_format_string::ArgType::Match) {
4575 return true;
4576 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004577
Seth Cantrell79340072015-03-04 05:58:08 +00004578 ScanfSpecifier fixedFS = FS;
4579 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4580 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004581
Seth Cantrell79340072015-03-04 05:58:08 +00004582 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4583 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4584 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4585 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004586
Seth Cantrell79340072015-03-04 05:58:08 +00004587 if (success) {
4588 // Get the fix string from the fixed format specifier.
4589 SmallString<128> buf;
4590 llvm::raw_svector_ostream os(buf);
4591 fixedFS.toString(os);
4592
4593 EmitFormatDiagnostic(
4594 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4595 << Ex->getType() << false << Ex->getSourceRange(),
4596 Ex->getLocStart(),
4597 /*IsStringLocation*/ false,
4598 getSpecifierRange(startSpecifier, specifierLen),
4599 FixItHint::CreateReplacement(
4600 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4601 } else {
4602 EmitFormatDiagnostic(S.PDiag(diag)
4603 << AT.getRepresentativeTypeName(S.Context)
4604 << Ex->getType() << false << Ex->getSourceRange(),
4605 Ex->getLocStart(),
4606 /*IsStringLocation*/ false,
4607 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004608 }
4609
Ted Kremenek02087932010-07-16 02:11:22 +00004610 return true;
4611}
4612
4613void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00004614 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004615 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004616 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004617 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00004618 bool inFunctionCall, VariadicCallType CallType,
4619 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004620
Ted Kremenekab278de2010-01-28 23:39:18 +00004621 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004622 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004623 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004624 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004625 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4626 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004627 return;
4628 }
Ted Kremenek02087932010-07-16 02:11:22 +00004629
Ted Kremenekab278de2010-01-28 23:39:18 +00004630 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004631 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004632 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004633 // Account for cases where the string literal is truncated in a declaration.
4634 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4635 assert(T && "String literal not of constant array type!");
4636 size_t TypeSize = T->getSize().getZExtValue();
4637 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004638 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004639
4640 // Emit a warning if the string literal is truncated and does not contain an
4641 // embedded null character.
4642 if (TypeSize <= StrRef.size() &&
4643 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4644 CheckFormatHandler::EmitFormatDiagnostic(
4645 *this, inFunctionCall, Args[format_idx],
4646 PDiag(diag::warn_printf_format_string_not_null_terminated),
4647 FExpr->getLocStart(),
4648 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4649 return;
4650 }
4651
Ted Kremenekab278de2010-01-28 23:39:18 +00004652 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004653 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004654 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004655 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004656 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4657 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004658 return;
4659 }
Ted Kremenek02087932010-07-16 02:11:22 +00004660
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004661 if (Type == FST_Printf || Type == FST_NSString ||
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004662 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek02087932010-07-16 02:11:22 +00004663 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004664 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004665 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004666 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004667
Hans Wennborg23926bd2011-12-15 10:25:47 +00004668 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004669 getLangOpts(),
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004670 Context.getTargetInfo(),
4671 Type == FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00004672 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004673 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004674 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004675 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004676 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004677
Hans Wennborg23926bd2011-12-15 10:25:47 +00004678 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004679 getLangOpts(),
4680 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004681 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004682 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004683}
4684
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004685bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4686 // Str - The format string. NOTE: this is NOT null-terminated!
4687 StringRef StrRef = FExpr->getString();
4688 const char *Str = StrRef.data();
4689 // Account for cases where the string literal is truncated in a declaration.
4690 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4691 assert(T && "String literal not of constant array type!");
4692 size_t TypeSize = T->getSize().getZExtValue();
4693 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4694 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4695 getLangOpts(),
4696 Context.getTargetInfo());
4697}
4698
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004699//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4700
4701// Returns the related absolute value function that is larger, of 0 if one
4702// does not exist.
4703static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4704 switch (AbsFunction) {
4705 default:
4706 return 0;
4707
4708 case Builtin::BI__builtin_abs:
4709 return Builtin::BI__builtin_labs;
4710 case Builtin::BI__builtin_labs:
4711 return Builtin::BI__builtin_llabs;
4712 case Builtin::BI__builtin_llabs:
4713 return 0;
4714
4715 case Builtin::BI__builtin_fabsf:
4716 return Builtin::BI__builtin_fabs;
4717 case Builtin::BI__builtin_fabs:
4718 return Builtin::BI__builtin_fabsl;
4719 case Builtin::BI__builtin_fabsl:
4720 return 0;
4721
4722 case Builtin::BI__builtin_cabsf:
4723 return Builtin::BI__builtin_cabs;
4724 case Builtin::BI__builtin_cabs:
4725 return Builtin::BI__builtin_cabsl;
4726 case Builtin::BI__builtin_cabsl:
4727 return 0;
4728
4729 case Builtin::BIabs:
4730 return Builtin::BIlabs;
4731 case Builtin::BIlabs:
4732 return Builtin::BIllabs;
4733 case Builtin::BIllabs:
4734 return 0;
4735
4736 case Builtin::BIfabsf:
4737 return Builtin::BIfabs;
4738 case Builtin::BIfabs:
4739 return Builtin::BIfabsl;
4740 case Builtin::BIfabsl:
4741 return 0;
4742
4743 case Builtin::BIcabsf:
4744 return Builtin::BIcabs;
4745 case Builtin::BIcabs:
4746 return Builtin::BIcabsl;
4747 case Builtin::BIcabsl:
4748 return 0;
4749 }
4750}
4751
4752// Returns the argument type of the absolute value function.
4753static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4754 unsigned AbsType) {
4755 if (AbsType == 0)
4756 return QualType();
4757
4758 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4759 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4760 if (Error != ASTContext::GE_None)
4761 return QualType();
4762
4763 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4764 if (!FT)
4765 return QualType();
4766
4767 if (FT->getNumParams() != 1)
4768 return QualType();
4769
4770 return FT->getParamType(0);
4771}
4772
4773// Returns the best absolute value function, or zero, based on type and
4774// current absolute value function.
4775static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4776 unsigned AbsFunctionKind) {
4777 unsigned BestKind = 0;
4778 uint64_t ArgSize = Context.getTypeSize(ArgType);
4779 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4780 Kind = getLargerAbsoluteValueFunction(Kind)) {
4781 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4782 if (Context.getTypeSize(ParamType) >= ArgSize) {
4783 if (BestKind == 0)
4784 BestKind = Kind;
4785 else if (Context.hasSameType(ParamType, ArgType)) {
4786 BestKind = Kind;
4787 break;
4788 }
4789 }
4790 }
4791 return BestKind;
4792}
4793
4794enum AbsoluteValueKind {
4795 AVK_Integer,
4796 AVK_Floating,
4797 AVK_Complex
4798};
4799
4800static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4801 if (T->isIntegralOrEnumerationType())
4802 return AVK_Integer;
4803 if (T->isRealFloatingType())
4804 return AVK_Floating;
4805 if (T->isAnyComplexType())
4806 return AVK_Complex;
4807
4808 llvm_unreachable("Type not integer, floating, or complex");
4809}
4810
4811// Changes the absolute value function to a different type. Preserves whether
4812// the function is a builtin.
4813static unsigned changeAbsFunction(unsigned AbsKind,
4814 AbsoluteValueKind ValueKind) {
4815 switch (ValueKind) {
4816 case AVK_Integer:
4817 switch (AbsKind) {
4818 default:
4819 return 0;
4820 case Builtin::BI__builtin_fabsf:
4821 case Builtin::BI__builtin_fabs:
4822 case Builtin::BI__builtin_fabsl:
4823 case Builtin::BI__builtin_cabsf:
4824 case Builtin::BI__builtin_cabs:
4825 case Builtin::BI__builtin_cabsl:
4826 return Builtin::BI__builtin_abs;
4827 case Builtin::BIfabsf:
4828 case Builtin::BIfabs:
4829 case Builtin::BIfabsl:
4830 case Builtin::BIcabsf:
4831 case Builtin::BIcabs:
4832 case Builtin::BIcabsl:
4833 return Builtin::BIabs;
4834 }
4835 case AVK_Floating:
4836 switch (AbsKind) {
4837 default:
4838 return 0;
4839 case Builtin::BI__builtin_abs:
4840 case Builtin::BI__builtin_labs:
4841 case Builtin::BI__builtin_llabs:
4842 case Builtin::BI__builtin_cabsf:
4843 case Builtin::BI__builtin_cabs:
4844 case Builtin::BI__builtin_cabsl:
4845 return Builtin::BI__builtin_fabsf;
4846 case Builtin::BIabs:
4847 case Builtin::BIlabs:
4848 case Builtin::BIllabs:
4849 case Builtin::BIcabsf:
4850 case Builtin::BIcabs:
4851 case Builtin::BIcabsl:
4852 return Builtin::BIfabsf;
4853 }
4854 case AVK_Complex:
4855 switch (AbsKind) {
4856 default:
4857 return 0;
4858 case Builtin::BI__builtin_abs:
4859 case Builtin::BI__builtin_labs:
4860 case Builtin::BI__builtin_llabs:
4861 case Builtin::BI__builtin_fabsf:
4862 case Builtin::BI__builtin_fabs:
4863 case Builtin::BI__builtin_fabsl:
4864 return Builtin::BI__builtin_cabsf;
4865 case Builtin::BIabs:
4866 case Builtin::BIlabs:
4867 case Builtin::BIllabs:
4868 case Builtin::BIfabsf:
4869 case Builtin::BIfabs:
4870 case Builtin::BIfabsl:
4871 return Builtin::BIcabsf;
4872 }
4873 }
4874 llvm_unreachable("Unable to convert function");
4875}
4876
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004877static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004878 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4879 if (!FnInfo)
4880 return 0;
4881
4882 switch (FDecl->getBuiltinID()) {
4883 default:
4884 return 0;
4885 case Builtin::BI__builtin_abs:
4886 case Builtin::BI__builtin_fabs:
4887 case Builtin::BI__builtin_fabsf:
4888 case Builtin::BI__builtin_fabsl:
4889 case Builtin::BI__builtin_labs:
4890 case Builtin::BI__builtin_llabs:
4891 case Builtin::BI__builtin_cabs:
4892 case Builtin::BI__builtin_cabsf:
4893 case Builtin::BI__builtin_cabsl:
4894 case Builtin::BIabs:
4895 case Builtin::BIlabs:
4896 case Builtin::BIllabs:
4897 case Builtin::BIfabs:
4898 case Builtin::BIfabsf:
4899 case Builtin::BIfabsl:
4900 case Builtin::BIcabs:
4901 case Builtin::BIcabsf:
4902 case Builtin::BIcabsl:
4903 return FDecl->getBuiltinID();
4904 }
4905 llvm_unreachable("Unknown Builtin type");
4906}
4907
4908// If the replacement is valid, emit a note with replacement function.
4909// Additionally, suggest including the proper header if not already included.
4910static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004911 unsigned AbsKind, QualType ArgType) {
4912 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004913 const char *HeaderName = nullptr;
4914 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004915 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4916 FunctionName = "std::abs";
4917 if (ArgType->isIntegralOrEnumerationType()) {
4918 HeaderName = "cstdlib";
4919 } else if (ArgType->isRealFloatingType()) {
4920 HeaderName = "cmath";
4921 } else {
4922 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004923 }
Richard Trieubeffb832014-04-15 23:47:53 +00004924
4925 // Lookup all std::abs
4926 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004927 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004928 R.suppressDiagnostics();
4929 S.LookupQualifiedName(R, Std);
4930
4931 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004932 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004933 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4934 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4935 } else {
4936 FDecl = dyn_cast<FunctionDecl>(I);
4937 }
4938 if (!FDecl)
4939 continue;
4940
4941 // Found std::abs(), check that they are the right ones.
4942 if (FDecl->getNumParams() != 1)
4943 continue;
4944
4945 // Check that the parameter type can handle the argument.
4946 QualType ParamType = FDecl->getParamDecl(0)->getType();
4947 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4948 S.Context.getTypeSize(ArgType) <=
4949 S.Context.getTypeSize(ParamType)) {
4950 // Found a function, don't need the header hint.
4951 EmitHeaderHint = false;
4952 break;
4953 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004954 }
Richard Trieubeffb832014-04-15 23:47:53 +00004955 }
4956 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00004957 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00004958 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4959
4960 if (HeaderName) {
4961 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4962 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4963 R.suppressDiagnostics();
4964 S.LookupName(R, S.getCurScope());
4965
4966 if (R.isSingleResult()) {
4967 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4968 if (FD && FD->getBuiltinID() == AbsKind) {
4969 EmitHeaderHint = false;
4970 } else {
4971 return;
4972 }
4973 } else if (!R.empty()) {
4974 return;
4975 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004976 }
4977 }
4978
4979 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00004980 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004981
Richard Trieubeffb832014-04-15 23:47:53 +00004982 if (!HeaderName)
4983 return;
4984
4985 if (!EmitHeaderHint)
4986 return;
4987
Alp Toker5d96e0a2014-07-11 20:53:51 +00004988 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4989 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00004990}
4991
4992static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4993 if (!FDecl)
4994 return false;
4995
4996 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4997 return false;
4998
4999 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5000
5001 while (ND && ND->isInlineNamespace()) {
5002 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005003 }
Richard Trieubeffb832014-04-15 23:47:53 +00005004
5005 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5006 return false;
5007
5008 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5009 return false;
5010
5011 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005012}
5013
5014// Warn when using the wrong abs() function.
5015void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5016 const FunctionDecl *FDecl,
5017 IdentifierInfo *FnInfo) {
5018 if (Call->getNumArgs() != 1)
5019 return;
5020
5021 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00005022 bool IsStdAbs = IsFunctionStdAbs(FDecl);
5023 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005024 return;
5025
5026 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5027 QualType ParamType = Call->getArg(0)->getType();
5028
Alp Toker5d96e0a2014-07-11 20:53:51 +00005029 // Unsigned types cannot be negative. Suggest removing the absolute value
5030 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005031 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00005032 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00005033 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005034 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5035 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00005036 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005037 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5038 return;
5039 }
5040
Richard Trieubeffb832014-04-15 23:47:53 +00005041 // std::abs has overloads which prevent most of the absolute value problems
5042 // from occurring.
5043 if (IsStdAbs)
5044 return;
5045
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005046 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5047 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5048
5049 // The argument and parameter are the same kind. Check if they are the right
5050 // size.
5051 if (ArgValueKind == ParamValueKind) {
5052 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
5053 return;
5054
5055 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
5056 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
5057 << FDecl << ArgType << ParamType;
5058
5059 if (NewAbsKind == 0)
5060 return;
5061
5062 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005063 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005064 return;
5065 }
5066
5067 // ArgValueKind != ParamValueKind
5068 // The wrong type of absolute value function was used. Attempt to find the
5069 // proper one.
5070 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
5071 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
5072 if (NewAbsKind == 0)
5073 return;
5074
5075 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
5076 << FDecl << ParamValueKind << ArgValueKind;
5077
5078 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005079 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005080 return;
5081}
5082
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005083//===--- CHECK: Standard memory functions ---------------------------------===//
5084
Nico Weber0e6daef2013-12-26 23:38:39 +00005085/// \brief Takes the expression passed to the size_t parameter of functions
5086/// such as memcmp, strncat, etc and warns if it's a comparison.
5087///
5088/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
5089static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
5090 IdentifierInfo *FnName,
5091 SourceLocation FnLoc,
5092 SourceLocation RParenLoc) {
5093 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
5094 if (!Size)
5095 return false;
5096
5097 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
5098 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
5099 return false;
5100
Nico Weber0e6daef2013-12-26 23:38:39 +00005101 SourceRange SizeRange = Size->getSourceRange();
5102 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
5103 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00005104 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005105 << FnName << FixItHint::CreateInsertion(
5106 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00005107 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00005108 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00005109 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00005110 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
5111 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00005112
5113 return true;
5114}
5115
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005116/// \brief Determine whether the given type is or contains a dynamic class type
5117/// (e.g., whether it has a vtable).
5118static const CXXRecordDecl *getContainedDynamicClass(QualType T,
5119 bool &IsContained) {
5120 // Look through array types while ignoring qualifiers.
5121 const Type *Ty = T->getBaseElementTypeUnsafe();
5122 IsContained = false;
5123
5124 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5125 RD = RD ? RD->getDefinition() : nullptr;
5126 if (!RD)
5127 return nullptr;
5128
5129 if (RD->isDynamicClass())
5130 return RD;
5131
5132 // Check all the fields. If any bases were dynamic, the class is dynamic.
5133 // It's impossible for a class to transitively contain itself by value, so
5134 // infinite recursion is impossible.
5135 for (auto *FD : RD->fields()) {
5136 bool SubContained;
5137 if (const CXXRecordDecl *ContainedRD =
5138 getContainedDynamicClass(FD->getType(), SubContained)) {
5139 IsContained = true;
5140 return ContainedRD;
5141 }
5142 }
5143
5144 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00005145}
5146
Chandler Carruth889ed862011-06-21 23:04:20 +00005147/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005148/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00005149static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00005150 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005151 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5152 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5153 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005154
Craig Topperc3ec1492014-05-26 06:22:03 +00005155 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005156}
5157
Chandler Carruth889ed862011-06-21 23:04:20 +00005158/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00005159static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005160 if (const UnaryExprOrTypeTraitExpr *SizeOf =
5161 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5162 if (SizeOf->getKind() == clang::UETT_SizeOf)
5163 return SizeOf->getTypeOfArgument();
5164
5165 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00005166}
5167
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005168/// \brief Check for dangerous or invalid arguments to memset().
5169///
Chandler Carruthac687262011-06-03 06:23:57 +00005170/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005171/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5172/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005173///
5174/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005175void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00005176 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005177 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00005178 assert(BId != 0);
5179
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005180 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00005181 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00005182 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00005183 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005184 return;
5185
Anna Zaks22122702012-01-17 00:37:07 +00005186 unsigned LastArg = (BId == Builtin::BImemset ||
5187 BId == Builtin::BIstrndup ? 1 : 2);
5188 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00005189 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005190
Nico Weber0e6daef2013-12-26 23:38:39 +00005191 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5192 Call->getLocStart(), Call->getRParenLoc()))
5193 return;
5194
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005195 // We have special checking when the length is a sizeof expression.
5196 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5197 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5198 llvm::FoldingSetNodeID SizeOfArgID;
5199
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005200 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5201 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005202 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005203
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005204 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00005205 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005206 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00005207 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00005208
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005209 // Never warn about void type pointers. This can be used to suppress
5210 // false positives.
5211 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005212 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005213
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005214 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5215 // actually comparing the expressions for equality. Because computing the
5216 // expression IDs can be expensive, we only do this if the diagnostic is
5217 // enabled.
5218 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005219 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5220 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005221 // We only compute IDs for expressions if the warning is enabled, and
5222 // cache the sizeof arg's ID.
5223 if (SizeOfArgID == llvm::FoldingSetNodeID())
5224 SizeOfArg->Profile(SizeOfArgID, Context, true);
5225 llvm::FoldingSetNodeID DestID;
5226 Dest->Profile(DestID, Context, true);
5227 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00005228 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5229 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005230 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00005231 StringRef ReadableName = FnName->getName();
5232
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005233 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00005234 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005235 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00005236 if (!PointeeTy->isIncompleteType() &&
5237 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005238 ActionIdx = 2; // If the pointee's size is sizeof(char),
5239 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00005240
5241 // If the function is defined as a builtin macro, do not show macro
5242 // expansion.
5243 SourceLocation SL = SizeOfArg->getExprLoc();
5244 SourceRange DSR = Dest->getSourceRange();
5245 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005246 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00005247
5248 if (SM.isMacroArgExpansion(SL)) {
5249 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5250 SL = SM.getSpellingLoc(SL);
5251 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5252 SM.getSpellingLoc(DSR.getEnd()));
5253 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5254 SM.getSpellingLoc(SSR.getEnd()));
5255 }
5256
Anna Zaksd08d9152012-05-30 23:14:52 +00005257 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005258 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00005259 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00005260 << PointeeTy
5261 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00005262 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00005263 << SSR);
5264 DiagRuntimeBehavior(SL, SizeOfArg,
5265 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5266 << ActionIdx
5267 << SSR);
5268
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005269 break;
5270 }
5271 }
5272
5273 // Also check for cases where the sizeof argument is the exact same
5274 // type as the memory argument, and where it points to a user-defined
5275 // record type.
5276 if (SizeOfArgTy != QualType()) {
5277 if (PointeeTy->isRecordType() &&
5278 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
5279 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
5280 PDiag(diag::warn_sizeof_pointer_type_memaccess)
5281 << FnName << SizeOfArgTy << ArgIdx
5282 << PointeeTy << Dest->getSourceRange()
5283 << LenExpr->getSourceRange());
5284 break;
5285 }
Nico Weberc5e73862011-06-14 16:14:58 +00005286 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00005287 } else if (DestTy->isArrayType()) {
5288 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00005289 }
Nico Weberc5e73862011-06-14 16:14:58 +00005290
Nico Weberc44b35e2015-03-21 17:37:46 +00005291 if (PointeeTy == QualType())
5292 continue;
Anna Zaks22122702012-01-17 00:37:07 +00005293
Nico Weberc44b35e2015-03-21 17:37:46 +00005294 // Always complain about dynamic classes.
5295 bool IsContained;
5296 if (const CXXRecordDecl *ContainedRD =
5297 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00005298
Nico Weberc44b35e2015-03-21 17:37:46 +00005299 unsigned OperationType = 0;
5300 // "overwritten" if we're warning about the destination for any call
5301 // but memcmp; otherwise a verb appropriate to the call.
5302 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
5303 if (BId == Builtin::BImemcpy)
5304 OperationType = 1;
5305 else if(BId == Builtin::BImemmove)
5306 OperationType = 2;
5307 else if (BId == Builtin::BImemcmp)
5308 OperationType = 3;
5309 }
5310
John McCall31168b02011-06-15 23:02:42 +00005311 DiagRuntimeBehavior(
5312 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00005313 PDiag(diag::warn_dyn_class_memaccess)
5314 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
5315 << FnName << IsContained << ContainedRD << OperationType
5316 << Call->getCallee()->getSourceRange());
5317 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
5318 BId != Builtin::BImemset)
5319 DiagRuntimeBehavior(
5320 Dest->getExprLoc(), Dest,
5321 PDiag(diag::warn_arc_object_memaccess)
5322 << ArgIdx << FnName << PointeeTy
5323 << Call->getCallee()->getSourceRange());
5324 else
5325 continue;
5326
5327 DiagRuntimeBehavior(
5328 Dest->getExprLoc(), Dest,
5329 PDiag(diag::note_bad_memaccess_silence)
5330 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
5331 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005332 }
Nico Weberc44b35e2015-03-21 17:37:46 +00005333
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005334}
5335
Ted Kremenek6865f772011-08-18 20:55:45 +00005336// A little helper routine: ignore addition and subtraction of integer literals.
5337// This intentionally does not ignore all integer constant expressions because
5338// we don't want to remove sizeof().
5339static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
5340 Ex = Ex->IgnoreParenCasts();
5341
5342 for (;;) {
5343 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
5344 if (!BO || !BO->isAdditiveOp())
5345 break;
5346
5347 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
5348 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
5349
5350 if (isa<IntegerLiteral>(RHS))
5351 Ex = LHS;
5352 else if (isa<IntegerLiteral>(LHS))
5353 Ex = RHS;
5354 else
5355 break;
5356 }
5357
5358 return Ex;
5359}
5360
Anna Zaks13b08572012-08-08 21:42:23 +00005361static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
5362 ASTContext &Context) {
5363 // Only handle constant-sized or VLAs, but not flexible members.
5364 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
5365 // Only issue the FIXIT for arrays of size > 1.
5366 if (CAT->getSize().getSExtValue() <= 1)
5367 return false;
5368 } else if (!Ty->isVariableArrayType()) {
5369 return false;
5370 }
5371 return true;
5372}
5373
Ted Kremenek6865f772011-08-18 20:55:45 +00005374// Warn if the user has made the 'size' argument to strlcpy or strlcat
5375// be the size of the source, instead of the destination.
5376void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
5377 IdentifierInfo *FnName) {
5378
5379 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00005380 unsigned NumArgs = Call->getNumArgs();
5381 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00005382 return;
5383
5384 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5385 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00005386 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00005387
5388 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5389 Call->getLocStart(), Call->getRParenLoc()))
5390 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00005391
5392 // Look for 'strlcpy(dst, x, sizeof(x))'
5393 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5394 CompareWithSrc = Ex;
5395 else {
5396 // Look for 'strlcpy(dst, x, strlen(x))'
5397 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00005398 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5399 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00005400 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5401 }
5402 }
5403
5404 if (!CompareWithSrc)
5405 return;
5406
5407 // Determine if the argument to sizeof/strlen is equal to the source
5408 // argument. In principle there's all kinds of things you could do
5409 // here, for instance creating an == expression and evaluating it with
5410 // EvaluateAsBooleanCondition, but this uses a more direct technique:
5411 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5412 if (!SrcArgDRE)
5413 return;
5414
5415 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5416 if (!CompareWithSrcDRE ||
5417 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5418 return;
5419
5420 const Expr *OriginalSizeArg = Call->getArg(2);
5421 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5422 << OriginalSizeArg->getSourceRange() << FnName;
5423
5424 // Output a FIXIT hint if the destination is an array (rather than a
5425 // pointer to an array). This could be enhanced to handle some
5426 // pointers if we know the actual size, like if DstArg is 'array+2'
5427 // we could say 'sizeof(array)-2'.
5428 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00005429 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00005430 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005431
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005432 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005433 llvm::raw_svector_ostream OS(sizeString);
5434 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005435 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00005436 OS << ")";
5437
5438 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5439 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5440 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00005441}
5442
Anna Zaks314cd092012-02-01 19:08:57 +00005443/// Check if two expressions refer to the same declaration.
5444static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5445 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5446 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5447 return D1->getDecl() == D2->getDecl();
5448 return false;
5449}
5450
5451static const Expr *getStrlenExprArg(const Expr *E) {
5452 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5453 const FunctionDecl *FD = CE->getDirectCallee();
5454 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00005455 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005456 return CE->getArg(0)->IgnoreParenCasts();
5457 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005458 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005459}
5460
5461// Warn on anti-patterns as the 'size' argument to strncat.
5462// The correct size argument should look like following:
5463// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5464void Sema::CheckStrncatArguments(const CallExpr *CE,
5465 IdentifierInfo *FnName) {
5466 // Don't crash if the user has the wrong number of arguments.
5467 if (CE->getNumArgs() < 3)
5468 return;
5469 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5470 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5471 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5472
Nico Weber0e6daef2013-12-26 23:38:39 +00005473 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5474 CE->getRParenLoc()))
5475 return;
5476
Anna Zaks314cd092012-02-01 19:08:57 +00005477 // Identify common expressions, which are wrongly used as the size argument
5478 // to strncat and may lead to buffer overflows.
5479 unsigned PatternType = 0;
5480 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5481 // - sizeof(dst)
5482 if (referToTheSameDecl(SizeOfArg, DstArg))
5483 PatternType = 1;
5484 // - sizeof(src)
5485 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5486 PatternType = 2;
5487 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5488 if (BE->getOpcode() == BO_Sub) {
5489 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5490 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5491 // - sizeof(dst) - strlen(dst)
5492 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5493 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5494 PatternType = 1;
5495 // - sizeof(src) - (anything)
5496 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5497 PatternType = 2;
5498 }
5499 }
5500
5501 if (PatternType == 0)
5502 return;
5503
Anna Zaks5069aa32012-02-03 01:27:37 +00005504 // Generate the diagnostic.
5505 SourceLocation SL = LenArg->getLocStart();
5506 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005507 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00005508
5509 // If the function is defined as a builtin macro, do not show macro expansion.
5510 if (SM.isMacroArgExpansion(SL)) {
5511 SL = SM.getSpellingLoc(SL);
5512 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5513 SM.getSpellingLoc(SR.getEnd()));
5514 }
5515
Anna Zaks13b08572012-08-08 21:42:23 +00005516 // Check if the destination is an array (rather than a pointer to an array).
5517 QualType DstTy = DstArg->getType();
5518 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5519 Context);
5520 if (!isKnownSizeArray) {
5521 if (PatternType == 1)
5522 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5523 else
5524 Diag(SL, diag::warn_strncat_src_size) << SR;
5525 return;
5526 }
5527
Anna Zaks314cd092012-02-01 19:08:57 +00005528 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00005529 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005530 else
Anna Zaks5069aa32012-02-03 01:27:37 +00005531 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005532
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005533 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00005534 llvm::raw_svector_ostream OS(sizeString);
5535 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005536 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005537 OS << ") - ";
5538 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005539 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005540 OS << ") - 1";
5541
Anna Zaks5069aa32012-02-03 01:27:37 +00005542 Diag(SL, diag::note_strncat_wrong_size)
5543 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005544}
5545
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005546//===--- CHECK: Return Address of Stack Variable --------------------------===//
5547
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005548static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5549 Decl *ParentDecl);
5550static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5551 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005552
5553/// CheckReturnStackAddr - Check if a return statement returns the address
5554/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005555static void
5556CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5557 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005558
Craig Topperc3ec1492014-05-26 06:22:03 +00005559 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005560 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005561
5562 // Perform checking for returned stack addresses, local blocks,
5563 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005564 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005565 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005566 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005567 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005568 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005569 }
5570
Craig Topperc3ec1492014-05-26 06:22:03 +00005571 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005572 return; // Nothing suspicious was found.
5573
5574 SourceLocation diagLoc;
5575 SourceRange diagRange;
5576 if (refVars.empty()) {
5577 diagLoc = stackE->getLocStart();
5578 diagRange = stackE->getSourceRange();
5579 } else {
5580 // We followed through a reference variable. 'stackE' contains the
5581 // problematic expression but we will warn at the return statement pointing
5582 // at the reference variable. We will later display the "trail" of
5583 // reference variables using notes.
5584 diagLoc = refVars[0]->getLocStart();
5585 diagRange = refVars[0]->getSourceRange();
5586 }
5587
5588 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005589 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005590 : diag::warn_ret_stack_addr)
5591 << DR->getDecl()->getDeclName() << diagRange;
5592 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005593 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005594 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005595 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005596 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005597 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
5598 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005599 << diagRange;
5600 }
5601
5602 // Display the "trail" of reference variables that we followed until we
5603 // found the problematic expression using notes.
5604 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5605 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5606 // If this var binds to another reference var, show the range of the next
5607 // var, otherwise the var binds to the problematic expression, in which case
5608 // show the range of the expression.
5609 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5610 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005611 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5612 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005613 }
5614}
5615
5616/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5617/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005618/// to a location on the stack, a local block, an address of a label, or a
5619/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005620/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005621/// encounter a subexpression that (1) clearly does not lead to one of the
5622/// above problematic expressions (2) is something we cannot determine leads to
5623/// a problematic expression based on such local checking.
5624///
5625/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5626/// the expression that they point to. Such variables are added to the
5627/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005628///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005629/// EvalAddr processes expressions that are pointers that are used as
5630/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005631/// At the base case of the recursion is a check for the above problematic
5632/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005633///
5634/// This implementation handles:
5635///
5636/// * pointer-to-pointer casts
5637/// * implicit conversions from array references to pointers
5638/// * taking the address of fields
5639/// * arbitrary interplay between "&" and "*" operators
5640/// * pointer arithmetic from an address of a stack variable
5641/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005642static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5643 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005644 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005645 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005646
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005647 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005648 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005649 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005650 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005651 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005652
Peter Collingbourne91147592011-04-15 00:35:48 +00005653 E = E->IgnoreParens();
5654
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005655 // Our "symbolic interpreter" is just a dispatch off the currently
5656 // viewed AST node. We then recursively traverse the AST by calling
5657 // EvalAddr and EvalVal appropriately.
5658 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005659 case Stmt::DeclRefExprClass: {
5660 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5661
Richard Smith40f08eb2014-01-30 22:05:38 +00005662 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005663 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005664 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005665
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005666 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5667 // If this is a reference variable, follow through to the expression that
5668 // it points to.
5669 if (V->hasLocalStorage() &&
5670 V->getType()->isReferenceType() && V->hasInit()) {
5671 // Add the reference variable to the "trail".
5672 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005673 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005674 }
5675
Craig Topperc3ec1492014-05-26 06:22:03 +00005676 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005677 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005678
Chris Lattner934edb22007-12-28 05:31:15 +00005679 case Stmt::UnaryOperatorClass: {
5680 // The only unary operator that make sense to handle here
5681 // is AddrOf. All others don't make sense as pointers.
5682 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005683
John McCalle3027922010-08-25 11:45:40 +00005684 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005685 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005686 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005687 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005688 }
Mike Stump11289f42009-09-09 15:08:12 +00005689
Chris Lattner934edb22007-12-28 05:31:15 +00005690 case Stmt::BinaryOperatorClass: {
5691 // Handle pointer arithmetic. All other binary operators are not valid
5692 // in this context.
5693 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005694 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005695
John McCalle3027922010-08-25 11:45:40 +00005696 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005697 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005698
Chris Lattner934edb22007-12-28 05:31:15 +00005699 Expr *Base = B->getLHS();
5700
5701 // Determine which argument is the real pointer base. It could be
5702 // the RHS argument instead of the LHS.
5703 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005704
Chris Lattner934edb22007-12-28 05:31:15 +00005705 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005706 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005707 }
Steve Naroff2752a172008-09-10 19:17:48 +00005708
Chris Lattner934edb22007-12-28 05:31:15 +00005709 // For conditional operators we need to see if either the LHS or RHS are
5710 // valid DeclRefExpr*s. If one of them is valid, we return it.
5711 case Stmt::ConditionalOperatorClass: {
5712 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005713
Chris Lattner934edb22007-12-28 05:31:15 +00005714 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005715 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5716 if (Expr *LHSExpr = C->getLHS()) {
5717 // In C++, we can have a throw-expression, which has 'void' type.
5718 if (!LHSExpr->getType()->isVoidType())
5719 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005720 return LHS;
5721 }
Chris Lattner934edb22007-12-28 05:31:15 +00005722
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005723 // In C++, we can have a throw-expression, which has 'void' type.
5724 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005725 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005726
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005727 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005728 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005729
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005730 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00005731 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005732 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00005733 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005734
5735 case Stmt::AddrLabelExprClass:
5736 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00005737
John McCall28fc7092011-11-10 05:35:25 +00005738 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005739 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5740 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005741
Ted Kremenekc3b4c522008-08-07 00:49:01 +00005742 // For casts, we need to handle conversions from arrays to
5743 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00005744 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00005745 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005746 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00005747 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00005748 case Stmt::CXXStaticCastExprClass:
5749 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00005750 case Stmt::CXXConstCastExprClass:
5751 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00005752 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5753 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00005754 case CK_LValueToRValue:
5755 case CK_NoOp:
5756 case CK_BaseToDerived:
5757 case CK_DerivedToBase:
5758 case CK_UncheckedDerivedToBase:
5759 case CK_Dynamic:
5760 case CK_CPointerToObjCPointerCast:
5761 case CK_BlockPointerToObjCPointerCast:
5762 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005763 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005764
5765 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005766 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005767
Richard Trieudadefde2014-07-02 04:39:38 +00005768 case CK_BitCast:
5769 if (SubExpr->getType()->isAnyPointerType() ||
5770 SubExpr->getType()->isBlockPointerType() ||
5771 SubExpr->getType()->isObjCQualifiedIdType())
5772 return EvalAddr(SubExpr, refVars, ParentDecl);
5773 else
5774 return nullptr;
5775
Eli Friedman8195ad72012-02-23 23:04:32 +00005776 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005777 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00005778 }
Chris Lattner934edb22007-12-28 05:31:15 +00005779 }
Mike Stump11289f42009-09-09 15:08:12 +00005780
Douglas Gregorfe314812011-06-21 17:03:29 +00005781 case Stmt::MaterializeTemporaryExprClass:
5782 if (Expr *Result = EvalAddr(
5783 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005784 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005785 return Result;
5786
5787 return E;
5788
Chris Lattner934edb22007-12-28 05:31:15 +00005789 // Everything else: we simply don't reason about them.
5790 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005791 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00005792 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005793}
Mike Stump11289f42009-09-09 15:08:12 +00005794
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005795
5796/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5797/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005798static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5799 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005800do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005801 // We should only be called for evaluating non-pointer expressions, or
5802 // expressions with a pointer type that are not used as references but instead
5803 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00005804
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005805 // Our "symbolic interpreter" is just a dispatch off the currently
5806 // viewed AST node. We then recursively traverse the AST by calling
5807 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00005808
5809 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005810 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005811 case Stmt::ImplicitCastExprClass: {
5812 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00005813 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005814 E = IE->getSubExpr();
5815 continue;
5816 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005817 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00005818 }
5819
John McCall28fc7092011-11-10 05:35:25 +00005820 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005821 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005822
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005823 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005824 // When we hit a DeclRefExpr we are looking at code that refers to a
5825 // variable's name. If it's not a reference variable we check if it has
5826 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005827 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005828
Richard Smith40f08eb2014-01-30 22:05:38 +00005829 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005830 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005831 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005832
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005833 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5834 // Check if it refers to itself, e.g. "int& i = i;".
5835 if (V == ParentDecl)
5836 return DR;
5837
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005838 if (V->hasLocalStorage()) {
5839 if (!V->getType()->isReferenceType())
5840 return DR;
5841
5842 // Reference variable, follow through to the expression that
5843 // it points to.
5844 if (V->hasInit()) {
5845 // Add the reference variable to the "trail".
5846 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005847 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005848 }
5849 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005850 }
Mike Stump11289f42009-09-09 15:08:12 +00005851
Craig Topperc3ec1492014-05-26 06:22:03 +00005852 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005853 }
Mike Stump11289f42009-09-09 15:08:12 +00005854
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005855 case Stmt::UnaryOperatorClass: {
5856 // The only unary operator that make sense to handle here
5857 // is Deref. All others don't resolve to a "name." This includes
5858 // handling all sorts of rvalues passed to a unary operator.
5859 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005860
John McCalle3027922010-08-25 11:45:40 +00005861 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005862 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005863
Craig Topperc3ec1492014-05-26 06:22:03 +00005864 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005865 }
Mike Stump11289f42009-09-09 15:08:12 +00005866
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005867 case Stmt::ArraySubscriptExprClass: {
5868 // Array subscripts are potential references to data on the stack. We
5869 // retrieve the DeclRefExpr* for the array variable if it indeed
5870 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005871 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005872 }
Mike Stump11289f42009-09-09 15:08:12 +00005873
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005874 case Stmt::OMPArraySectionExprClass: {
5875 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
5876 ParentDecl);
5877 }
5878
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005879 case Stmt::ConditionalOperatorClass: {
5880 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005881 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005882 ConditionalOperator *C = cast<ConditionalOperator>(E);
5883
Anders Carlsson801c5c72007-11-30 19:04:31 +00005884 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005885 if (Expr *LHSExpr = C->getLHS()) {
5886 // In C++, we can have a throw-expression, which has 'void' type.
5887 if (!LHSExpr->getType()->isVoidType())
5888 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5889 return LHS;
5890 }
5891
5892 // In C++, we can have a throw-expression, which has 'void' type.
5893 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005894 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005895
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005896 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005897 }
Mike Stump11289f42009-09-09 15:08:12 +00005898
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005899 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005900 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005901 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005902
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005903 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005904 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005905 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005906
5907 // Check whether the member type is itself a reference, in which case
5908 // we're not going to refer to the member, but to what the member refers to.
5909 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005910 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005911
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005912 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005913 }
Mike Stump11289f42009-09-09 15:08:12 +00005914
Douglas Gregorfe314812011-06-21 17:03:29 +00005915 case Stmt::MaterializeTemporaryExprClass:
5916 if (Expr *Result = EvalVal(
5917 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005918 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005919 return Result;
5920
5921 return E;
5922
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005923 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005924 // Check that we don't return or take the address of a reference to a
5925 // temporary. This is only useful in C++.
5926 if (!E->isTypeDependent() && E->isRValue())
5927 return E;
5928
5929 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005930 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005931 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005932} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005933}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005934
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005935void
5936Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5937 SourceLocation ReturnLoc,
5938 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005939 const AttrVec *Attrs,
5940 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005941 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5942
5943 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00005944 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
5945 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00005946 CheckNonNullExpr(*this, RetValExp))
5947 Diag(ReturnLoc, diag::warn_null_ret)
5948 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00005949
5950 // C++11 [basic.stc.dynamic.allocation]p4:
5951 // If an allocation function declared with a non-throwing
5952 // exception-specification fails to allocate storage, it shall return
5953 // a null pointer. Any other allocation function that fails to allocate
5954 // storage shall indicate failure only by throwing an exception [...]
5955 if (FD) {
5956 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5957 if (Op == OO_New || Op == OO_Array_New) {
5958 const FunctionProtoType *Proto
5959 = FD->getType()->castAs<FunctionProtoType>();
5960 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5961 CheckNonNullExpr(*this, RetValExp))
5962 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5963 << FD << getLangOpts().CPlusPlus11;
5964 }
5965 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005966}
5967
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005968//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5969
5970/// Check for comparisons of floating point operands using != and ==.
5971/// Issue a warning if these are no self-comparisons, as they are not likely
5972/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00005973void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00005974 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5975 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005976
5977 // Special case: check for x == x (which is OK).
5978 // Do not emit warnings for such cases.
5979 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5980 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5981 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00005982 return;
Mike Stump11289f42009-09-09 15:08:12 +00005983
5984
Ted Kremenekeda40e22007-11-29 00:59:04 +00005985 // Special case: check for comparisons against literals that can be exactly
5986 // represented by APFloat. In such cases, do not emit a warning. This
5987 // is a heuristic: often comparison against such literals are used to
5988 // detect if a value in a variable has not changed. This clearly can
5989 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00005990 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5991 if (FLL->isExact())
5992 return;
5993 } else
5994 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5995 if (FLR->isExact())
5996 return;
Mike Stump11289f42009-09-09 15:08:12 +00005997
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005998 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00005999 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006000 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006001 return;
Mike Stump11289f42009-09-09 15:08:12 +00006002
David Blaikie1f4ff152012-07-16 20:47:22 +00006003 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006004 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006005 return;
Mike Stump11289f42009-09-09 15:08:12 +00006006
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006007 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00006008 Diag(Loc, diag::warn_floatingpoint_eq)
6009 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006010}
John McCallca01b222010-01-04 23:21:16 +00006011
John McCall70aa5392010-01-06 05:24:50 +00006012//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6013//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00006014
John McCall70aa5392010-01-06 05:24:50 +00006015namespace {
John McCallca01b222010-01-04 23:21:16 +00006016
John McCall70aa5392010-01-06 05:24:50 +00006017/// Structure recording the 'active' range of an integer-valued
6018/// expression.
6019struct IntRange {
6020 /// The number of bits active in the int.
6021 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00006022
John McCall70aa5392010-01-06 05:24:50 +00006023 /// True if the int is known not to have negative values.
6024 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00006025
John McCall70aa5392010-01-06 05:24:50 +00006026 IntRange(unsigned Width, bool NonNegative)
6027 : Width(Width), NonNegative(NonNegative)
6028 {}
John McCallca01b222010-01-04 23:21:16 +00006029
John McCall817d4af2010-11-10 23:38:19 +00006030 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00006031 static IntRange forBoolType() {
6032 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00006033 }
6034
John McCall817d4af2010-11-10 23:38:19 +00006035 /// Returns the range of an opaque value of the given integral type.
6036 static IntRange forValueOfType(ASTContext &C, QualType T) {
6037 return forValueOfCanonicalType(C,
6038 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00006039 }
6040
John McCall817d4af2010-11-10 23:38:19 +00006041 /// Returns the range of an opaque value of a canonical integral type.
6042 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00006043 assert(T->isCanonicalUnqualified());
6044
6045 if (const VectorType *VT = dyn_cast<VectorType>(T))
6046 T = VT->getElementType().getTypePtr();
6047 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6048 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006049 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6050 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00006051
David Majnemer6a426652013-06-07 22:07:20 +00006052 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00006053 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00006054 EnumDecl *Enum = ET->getDecl();
6055 if (!Enum->isCompleteDefinition())
6056 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00006057
David Majnemer6a426652013-06-07 22:07:20 +00006058 unsigned NumPositive = Enum->getNumPositiveBits();
6059 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00006060
David Majnemer6a426652013-06-07 22:07:20 +00006061 if (NumNegative == 0)
6062 return IntRange(NumPositive, true/*NonNegative*/);
6063 else
6064 return IntRange(std::max(NumPositive + 1, NumNegative),
6065 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00006066 }
John McCall70aa5392010-01-06 05:24:50 +00006067
6068 const BuiltinType *BT = cast<BuiltinType>(T);
6069 assert(BT->isInteger());
6070
6071 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6072 }
6073
John McCall817d4af2010-11-10 23:38:19 +00006074 /// Returns the "target" range of a canonical integral type, i.e.
6075 /// the range of values expressible in the type.
6076 ///
6077 /// This matches forValueOfCanonicalType except that enums have the
6078 /// full range of their type, not the range of their enumerators.
6079 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
6080 assert(T->isCanonicalUnqualified());
6081
6082 if (const VectorType *VT = dyn_cast<VectorType>(T))
6083 T = VT->getElementType().getTypePtr();
6084 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6085 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006086 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6087 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006088 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00006089 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006090
6091 const BuiltinType *BT = cast<BuiltinType>(T);
6092 assert(BT->isInteger());
6093
6094 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6095 }
6096
6097 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00006098 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00006099 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00006100 L.NonNegative && R.NonNegative);
6101 }
6102
John McCall817d4af2010-11-10 23:38:19 +00006103 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00006104 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00006105 return IntRange(std::min(L.Width, R.Width),
6106 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00006107 }
6108};
6109
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006110static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
6111 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006112 if (value.isSigned() && value.isNegative())
6113 return IntRange(value.getMinSignedBits(), false);
6114
6115 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006116 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006117
6118 // isNonNegative() just checks the sign bit without considering
6119 // signedness.
6120 return IntRange(value.getActiveBits(), true);
6121}
6122
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006123static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
6124 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006125 if (result.isInt())
6126 return GetValueRange(C, result.getInt(), MaxWidth);
6127
6128 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00006129 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6130 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6131 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6132 R = IntRange::join(R, El);
6133 }
John McCall70aa5392010-01-06 05:24:50 +00006134 return R;
6135 }
6136
6137 if (result.isComplexInt()) {
6138 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6139 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6140 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00006141 }
6142
6143 // This can happen with lossless casts to intptr_t of "based" lvalues.
6144 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00006145 // FIXME: The only reason we need to pass the type in here is to get
6146 // the sign right on this one case. It would be nice if APValue
6147 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006148 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00006149 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00006150}
John McCall70aa5392010-01-06 05:24:50 +00006151
Eli Friedmane6d33952013-07-08 20:20:06 +00006152static QualType GetExprType(Expr *E) {
6153 QualType Ty = E->getType();
6154 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6155 Ty = AtomicRHS->getValueType();
6156 return Ty;
6157}
6158
John McCall70aa5392010-01-06 05:24:50 +00006159/// Pseudo-evaluate the given integer expression, estimating the
6160/// range of values it might take.
6161///
6162/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006163static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006164 E = E->IgnoreParens();
6165
6166 // Try a full evaluation first.
6167 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006168 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00006169 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006170
6171 // I think we only want to look through implicit casts here; if the
6172 // user has an explicit widening cast, we should treat the value as
6173 // being of the new, wider type.
6174 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00006175 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00006176 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6177
Eli Friedmane6d33952013-07-08 20:20:06 +00006178 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00006179
John McCalle3027922010-08-25 11:45:40 +00006180 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00006181
John McCall70aa5392010-01-06 05:24:50 +00006182 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00006183 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00006184 return OutputTypeRange;
6185
6186 IntRange SubRange
6187 = GetExprRange(C, CE->getSubExpr(),
6188 std::min(MaxWidth, OutputTypeRange.Width));
6189
6190 // Bail out if the subexpr's range is as wide as the cast type.
6191 if (SubRange.Width >= OutputTypeRange.Width)
6192 return OutputTypeRange;
6193
6194 // Otherwise, we take the smaller width, and we're non-negative if
6195 // either the output type or the subexpr is.
6196 return IntRange(SubRange.Width,
6197 SubRange.NonNegative || OutputTypeRange.NonNegative);
6198 }
6199
6200 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6201 // If we can fold the condition, just take that operand.
6202 bool CondResult;
6203 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6204 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6205 : CO->getFalseExpr(),
6206 MaxWidth);
6207
6208 // Otherwise, conservatively merge.
6209 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6210 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6211 return IntRange::join(L, R);
6212 }
6213
6214 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6215 switch (BO->getOpcode()) {
6216
6217 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00006218 case BO_LAnd:
6219 case BO_LOr:
6220 case BO_LT:
6221 case BO_GT:
6222 case BO_LE:
6223 case BO_GE:
6224 case BO_EQ:
6225 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00006226 return IntRange::forBoolType();
6227
John McCallc3688382011-07-13 06:35:24 +00006228 // The type of the assignments is the type of the LHS, so the RHS
6229 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00006230 case BO_MulAssign:
6231 case BO_DivAssign:
6232 case BO_RemAssign:
6233 case BO_AddAssign:
6234 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00006235 case BO_XorAssign:
6236 case BO_OrAssign:
6237 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00006238 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00006239
John McCallc3688382011-07-13 06:35:24 +00006240 // Simple assignments just pass through the RHS, which will have
6241 // been coerced to the LHS type.
6242 case BO_Assign:
6243 // TODO: bitfields?
6244 return GetExprRange(C, BO->getRHS(), MaxWidth);
6245
John McCall70aa5392010-01-06 05:24:50 +00006246 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006247 case BO_PtrMemD:
6248 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00006249 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006250
John McCall2ce81ad2010-01-06 22:07:33 +00006251 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00006252 case BO_And:
6253 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00006254 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6255 GetExprRange(C, BO->getRHS(), MaxWidth));
6256
John McCall70aa5392010-01-06 05:24:50 +00006257 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00006258 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00006259 // ...except that we want to treat '1 << (blah)' as logically
6260 // positive. It's an important idiom.
6261 if (IntegerLiteral *I
6262 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6263 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006264 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00006265 return IntRange(R.Width, /*NonNegative*/ true);
6266 }
6267 }
6268 // fallthrough
6269
John McCalle3027922010-08-25 11:45:40 +00006270 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00006271 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006272
John McCall2ce81ad2010-01-06 22:07:33 +00006273 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00006274 case BO_Shr:
6275 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00006276 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6277
6278 // If the shift amount is a positive constant, drop the width by
6279 // that much.
6280 llvm::APSInt shift;
6281 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6282 shift.isNonNegative()) {
6283 unsigned zext = shift.getZExtValue();
6284 if (zext >= L.Width)
6285 L.Width = (L.NonNegative ? 0 : 1);
6286 else
6287 L.Width -= zext;
6288 }
6289
6290 return L;
6291 }
6292
6293 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00006294 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00006295 return GetExprRange(C, BO->getRHS(), MaxWidth);
6296
John McCall2ce81ad2010-01-06 22:07:33 +00006297 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00006298 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00006299 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00006300 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006301 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006302
John McCall51431812011-07-14 22:39:48 +00006303 // The width of a division result is mostly determined by the size
6304 // of the LHS.
6305 case BO_Div: {
6306 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006307 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006308 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6309
6310 // If the divisor is constant, use that.
6311 llvm::APSInt divisor;
6312 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
6313 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
6314 if (log2 >= L.Width)
6315 L.Width = (L.NonNegative ? 0 : 1);
6316 else
6317 L.Width = std::min(L.Width - log2, MaxWidth);
6318 return L;
6319 }
6320
6321 // Otherwise, just use the LHS's width.
6322 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6323 return IntRange(L.Width, L.NonNegative && R.NonNegative);
6324 }
6325
6326 // The result of a remainder can't be larger than the result of
6327 // either side.
6328 case BO_Rem: {
6329 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006330 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006331 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6332 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6333
6334 IntRange meet = IntRange::meet(L, R);
6335 meet.Width = std::min(meet.Width, MaxWidth);
6336 return meet;
6337 }
6338
6339 // The default behavior is okay for these.
6340 case BO_Mul:
6341 case BO_Add:
6342 case BO_Xor:
6343 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00006344 break;
6345 }
6346
John McCall51431812011-07-14 22:39:48 +00006347 // The default case is to treat the operation as if it were closed
6348 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00006349 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6350 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
6351 return IntRange::join(L, R);
6352 }
6353
6354 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6355 switch (UO->getOpcode()) {
6356 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00006357 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00006358 return IntRange::forBoolType();
6359
6360 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006361 case UO_Deref:
6362 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00006363 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006364
6365 default:
6366 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
6367 }
6368 }
6369
Ted Kremeneka553fbf2013-10-14 18:55:27 +00006370 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6371 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
6372
John McCalld25db7e2013-05-06 21:39:12 +00006373 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00006374 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00006375 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00006376
Eli Friedmane6d33952013-07-08 20:20:06 +00006377 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006378}
John McCall263a48b2010-01-04 23:31:57 +00006379
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006380static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006381 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00006382}
6383
John McCall263a48b2010-01-04 23:31:57 +00006384/// Checks whether the given value, which currently has the given
6385/// source semantics, has the same value when coerced through the
6386/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006387static bool IsSameFloatAfterCast(const llvm::APFloat &value,
6388 const llvm::fltSemantics &Src,
6389 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006390 llvm::APFloat truncated = value;
6391
6392 bool ignored;
6393 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6394 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6395
6396 return truncated.bitwiseIsEqual(value);
6397}
6398
6399/// Checks whether the given value, which currently has the given
6400/// source semantics, has the same value when coerced through the
6401/// target semantics.
6402///
6403/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006404static bool IsSameFloatAfterCast(const APValue &value,
6405 const llvm::fltSemantics &Src,
6406 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006407 if (value.isFloat())
6408 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6409
6410 if (value.isVector()) {
6411 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6412 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6413 return false;
6414 return true;
6415 }
6416
6417 assert(value.isComplexFloat());
6418 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6419 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6420}
6421
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006422static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006423
Ted Kremenek6274be42010-09-23 21:43:44 +00006424static bool IsZero(Sema &S, Expr *E) {
6425 // Suppress cases where we are comparing against an enum constant.
6426 if (const DeclRefExpr *DR =
6427 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6428 if (isa<EnumConstantDecl>(DR->getDecl()))
6429 return false;
6430
6431 // Suppress cases where the '0' value is expanded from a macro.
6432 if (E->getLocStart().isMacroID())
6433 return false;
6434
John McCallcc7e5bf2010-05-06 08:58:33 +00006435 llvm::APSInt Value;
6436 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6437}
6438
John McCall2551c1b2010-10-06 00:25:24 +00006439static bool HasEnumType(Expr *E) {
6440 // Strip off implicit integral promotions.
6441 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006442 if (ICE->getCastKind() != CK_IntegralCast &&
6443 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00006444 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006445 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00006446 }
6447
6448 return E->getType()->isEnumeralType();
6449}
6450
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006451static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00006452 // Disable warning in template instantiations.
6453 if (!S.ActiveTemplateInstantiations.empty())
6454 return;
6455
John McCalle3027922010-08-25 11:45:40 +00006456 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00006457 if (E->isValueDependent())
6458 return;
6459
John McCalle3027922010-08-25 11:45:40 +00006460 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006461 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006462 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006463 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006464 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006465 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006466 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006467 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006468 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006469 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006470 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006471 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006472 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006473 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006474 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006475 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6476 }
6477}
6478
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006479static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006480 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006481 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006482 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00006483 // Disable warning in template instantiations.
6484 if (!S.ActiveTemplateInstantiations.empty())
6485 return;
6486
Richard Trieu0f097742014-04-04 04:13:47 +00006487 // TODO: Investigate using GetExprRange() to get tighter bounds
6488 // on the bit ranges.
6489 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00006490 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00006491 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00006492 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6493 unsigned OtherWidth = OtherRange.Width;
6494
6495 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6496
Richard Trieu560910c2012-11-14 22:50:24 +00006497 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00006498 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00006499 return;
6500
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006501 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00006502 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006503
Richard Trieu0f097742014-04-04 04:13:47 +00006504 // Used for diagnostic printout.
6505 enum {
6506 LiteralConstant = 0,
6507 CXXBoolLiteralTrue,
6508 CXXBoolLiteralFalse
6509 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006510
Richard Trieu0f097742014-04-04 04:13:47 +00006511 if (!OtherIsBooleanType) {
6512 QualType ConstantT = Constant->getType();
6513 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00006514
Richard Trieu0f097742014-04-04 04:13:47 +00006515 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6516 return;
6517 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6518 "comparison with non-integer type");
6519
6520 bool ConstantSigned = ConstantT->isSignedIntegerType();
6521 bool CommonSigned = CommonT->isSignedIntegerType();
6522
6523 bool EqualityOnly = false;
6524
6525 if (CommonSigned) {
6526 // The common type is signed, therefore no signed to unsigned conversion.
6527 if (!OtherRange.NonNegative) {
6528 // Check that the constant is representable in type OtherT.
6529 if (ConstantSigned) {
6530 if (OtherWidth >= Value.getMinSignedBits())
6531 return;
6532 } else { // !ConstantSigned
6533 if (OtherWidth >= Value.getActiveBits() + 1)
6534 return;
6535 }
6536 } else { // !OtherSigned
6537 // Check that the constant is representable in type OtherT.
6538 // Negative values are out of range.
6539 if (ConstantSigned) {
6540 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6541 return;
6542 } else { // !ConstantSigned
6543 if (OtherWidth >= Value.getActiveBits())
6544 return;
6545 }
Richard Trieu560910c2012-11-14 22:50:24 +00006546 }
Richard Trieu0f097742014-04-04 04:13:47 +00006547 } else { // !CommonSigned
6548 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006549 if (OtherWidth >= Value.getActiveBits())
6550 return;
Craig Toppercf360162014-06-18 05:13:11 +00006551 } else { // OtherSigned
6552 assert(!ConstantSigned &&
6553 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006554 // Check to see if the constant is representable in OtherT.
6555 if (OtherWidth > Value.getActiveBits())
6556 return;
6557 // Check to see if the constant is equivalent to a negative value
6558 // cast to CommonT.
6559 if (S.Context.getIntWidth(ConstantT) ==
6560 S.Context.getIntWidth(CommonT) &&
6561 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6562 return;
6563 // The constant value rests between values that OtherT can represent
6564 // after conversion. Relational comparison still works, but equality
6565 // comparisons will be tautological.
6566 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006567 }
6568 }
Richard Trieu0f097742014-04-04 04:13:47 +00006569
6570 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6571
6572 if (op == BO_EQ || op == BO_NE) {
6573 IsTrue = op == BO_NE;
6574 } else if (EqualityOnly) {
6575 return;
6576 } else if (RhsConstant) {
6577 if (op == BO_GT || op == BO_GE)
6578 IsTrue = !PositiveConstant;
6579 else // op == BO_LT || op == BO_LE
6580 IsTrue = PositiveConstant;
6581 } else {
6582 if (op == BO_LT || op == BO_LE)
6583 IsTrue = !PositiveConstant;
6584 else // op == BO_GT || op == BO_GE
6585 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006586 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006587 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00006588 // Other isKnownToHaveBooleanValue
6589 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6590 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6591 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6592
6593 static const struct LinkedConditions {
6594 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6595 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6596 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6597 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6598 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6599 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6600
6601 } TruthTable = {
6602 // Constant on LHS. | Constant on RHS. |
6603 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6604 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6605 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6606 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6607 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6608 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6609 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6610 };
6611
6612 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6613
6614 enum ConstantValue ConstVal = Zero;
6615 if (Value.isUnsigned() || Value.isNonNegative()) {
6616 if (Value == 0) {
6617 LiteralOrBoolConstant =
6618 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6619 ConstVal = Zero;
6620 } else if (Value == 1) {
6621 LiteralOrBoolConstant =
6622 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6623 ConstVal = One;
6624 } else {
6625 LiteralOrBoolConstant = LiteralConstant;
6626 ConstVal = GT_One;
6627 }
6628 } else {
6629 ConstVal = LT_Zero;
6630 }
6631
6632 CompareBoolWithConstantResult CmpRes;
6633
6634 switch (op) {
6635 case BO_LT:
6636 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6637 break;
6638 case BO_GT:
6639 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6640 break;
6641 case BO_LE:
6642 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6643 break;
6644 case BO_GE:
6645 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6646 break;
6647 case BO_EQ:
6648 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6649 break;
6650 case BO_NE:
6651 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6652 break;
6653 default:
6654 CmpRes = Unkwn;
6655 break;
6656 }
6657
6658 if (CmpRes == AFals) {
6659 IsTrue = false;
6660 } else if (CmpRes == ATrue) {
6661 IsTrue = true;
6662 } else {
6663 return;
6664 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006665 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006666
6667 // If this is a comparison to an enum constant, include that
6668 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006669 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006670 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6671 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6672
6673 SmallString<64> PrettySourceValue;
6674 llvm::raw_svector_ostream OS(PrettySourceValue);
6675 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00006676 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006677 else
6678 OS << Value;
6679
Richard Trieu0f097742014-04-04 04:13:47 +00006680 S.DiagRuntimeBehavior(
6681 E->getOperatorLoc(), E,
6682 S.PDiag(diag::warn_out_of_range_compare)
6683 << OS.str() << LiteralOrBoolConstant
6684 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6685 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006686}
6687
John McCallcc7e5bf2010-05-06 08:58:33 +00006688/// Analyze the operands of the given comparison. Implements the
6689/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006690static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00006691 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6692 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006693}
John McCall263a48b2010-01-04 23:31:57 +00006694
John McCallca01b222010-01-04 23:21:16 +00006695/// \brief Implements -Wsign-compare.
6696///
Richard Trieu82402a02011-09-15 21:56:47 +00006697/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006698static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006699 // The type the comparison is being performed in.
6700 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006701
6702 // Only analyze comparison operators where both sides have been converted to
6703 // the same type.
6704 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6705 return AnalyzeImpConvsInComparison(S, E);
6706
6707 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006708 if (E->isValueDependent())
6709 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006710
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006711 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6712 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006713
6714 bool IsComparisonConstant = false;
6715
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006716 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006717 // of 'true' or 'false'.
6718 if (T->isIntegralType(S.Context)) {
6719 llvm::APSInt RHSValue;
6720 bool IsRHSIntegralLiteral =
6721 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6722 llvm::APSInt LHSValue;
6723 bool IsLHSIntegralLiteral =
6724 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6725 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6726 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6727 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6728 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6729 else
6730 IsComparisonConstant =
6731 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006732 } else if (!T->hasUnsignedIntegerRepresentation())
6733 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006734
John McCallcc7e5bf2010-05-06 08:58:33 +00006735 // We don't do anything special if this isn't an unsigned integral
6736 // comparison: we're only interested in integral comparisons, and
6737 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00006738 //
6739 // We also don't care about value-dependent expressions or expressions
6740 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006741 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00006742 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006743
John McCallcc7e5bf2010-05-06 08:58:33 +00006744 // Check to see if one of the (unmodified) operands is of different
6745 // signedness.
6746 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00006747 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6748 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00006749 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00006750 signedOperand = LHS;
6751 unsignedOperand = RHS;
6752 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6753 signedOperand = RHS;
6754 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00006755 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00006756 CheckTrivialUnsignedComparison(S, E);
6757 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006758 }
6759
John McCallcc7e5bf2010-05-06 08:58:33 +00006760 // Otherwise, calculate the effective range of the signed operand.
6761 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00006762
John McCallcc7e5bf2010-05-06 08:58:33 +00006763 // Go ahead and analyze implicit conversions in the operands. Note
6764 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00006765 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6766 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00006767
John McCallcc7e5bf2010-05-06 08:58:33 +00006768 // If the signed range is non-negative, -Wsign-compare won't fire,
6769 // but we should still check for comparisons which are always true
6770 // or false.
6771 if (signedRange.NonNegative)
6772 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006773
6774 // For (in)equality comparisons, if the unsigned operand is a
6775 // constant which cannot collide with a overflowed signed operand,
6776 // then reinterpreting the signed operand as unsigned will not
6777 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00006778 if (E->isEqualityOp()) {
6779 unsigned comparisonWidth = S.Context.getIntWidth(T);
6780 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00006781
John McCallcc7e5bf2010-05-06 08:58:33 +00006782 // We should never be unable to prove that the unsigned operand is
6783 // non-negative.
6784 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6785
6786 if (unsignedRange.Width < comparisonWidth)
6787 return;
6788 }
6789
Douglas Gregorbfb4a212012-05-01 01:53:49 +00006790 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6791 S.PDiag(diag::warn_mixed_sign_comparison)
6792 << LHS->getType() << RHS->getType()
6793 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00006794}
6795
John McCall1f425642010-11-11 03:21:53 +00006796/// Analyzes an attempt to assign the given value to a bitfield.
6797///
6798/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006799static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6800 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00006801 assert(Bitfield->isBitField());
6802 if (Bitfield->isInvalidDecl())
6803 return false;
6804
John McCalldeebbcf2010-11-11 05:33:51 +00006805 // White-list bool bitfields.
6806 if (Bitfield->getType()->isBooleanType())
6807 return false;
6808
Douglas Gregor789adec2011-02-04 13:09:01 +00006809 // Ignore value- or type-dependent expressions.
6810 if (Bitfield->getBitWidth()->isValueDependent() ||
6811 Bitfield->getBitWidth()->isTypeDependent() ||
6812 Init->isValueDependent() ||
6813 Init->isTypeDependent())
6814 return false;
6815
John McCall1f425642010-11-11 03:21:53 +00006816 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6817
Richard Smith5fab0c92011-12-28 19:48:30 +00006818 llvm::APSInt Value;
6819 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00006820 return false;
6821
John McCall1f425642010-11-11 03:21:53 +00006822 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00006823 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00006824
6825 if (OriginalWidth <= FieldWidth)
6826 return false;
6827
Eli Friedmanc267a322012-01-26 23:11:39 +00006828 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006829 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00006830 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00006831
Eli Friedmanc267a322012-01-26 23:11:39 +00006832 // Check whether the stored value is equal to the original value.
6833 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00006834 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00006835 return false;
6836
Eli Friedmanc267a322012-01-26 23:11:39 +00006837 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00006838 // therefore don't strictly fit into a signed bitfield of width 1.
6839 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00006840 return false;
6841
John McCall1f425642010-11-11 03:21:53 +00006842 std::string PrettyValue = Value.toString(10);
6843 std::string PrettyTrunc = TruncatedValue.toString(10);
6844
6845 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6846 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6847 << Init->getSourceRange();
6848
6849 return true;
6850}
6851
John McCalld2a53122010-11-09 23:24:47 +00006852/// Analyze the given simple or compound assignment for warning-worthy
6853/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006854static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006855 // Just recurse on the LHS.
6856 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6857
6858 // We want to recurse on the RHS as normal unless we're assigning to
6859 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006860 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006861 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006862 E->getOperatorLoc())) {
6863 // Recurse, ignoring any implicit conversions on the RHS.
6864 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6865 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006866 }
6867 }
6868
6869 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6870}
6871
John McCall263a48b2010-01-04 23:31:57 +00006872/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006873static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006874 SourceLocation CContext, unsigned diag,
6875 bool pruneControlFlow = false) {
6876 if (pruneControlFlow) {
6877 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6878 S.PDiag(diag)
6879 << SourceType << T << E->getSourceRange()
6880 << SourceRange(CContext));
6881 return;
6882 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006883 S.Diag(E->getExprLoc(), diag)
6884 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6885}
6886
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006887/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006888static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006889 SourceLocation CContext, unsigned diag,
6890 bool pruneControlFlow = false) {
6891 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006892}
6893
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006894/// Diagnose an implicit cast from a literal expression. Does not warn when the
6895/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006896void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6897 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006898 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006899 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006900 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006901 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6902 T->hasUnsignedIntegerRepresentation());
6903 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006904 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006905 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006906 return;
6907
Eli Friedman07185912013-08-29 23:44:43 +00006908 // FIXME: Force the precision of the source value down so we don't print
6909 // digits which are usually useless (we don't really care here if we
6910 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6911 // would automatically print the shortest representation, but it's a bit
6912 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006913 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006914 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6915 precision = (precision * 59 + 195) / 196;
6916 Value.toString(PrettySourceValue, precision);
6917
David Blaikie9b88cc02012-05-15 17:18:27 +00006918 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006919 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6920 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6921 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006922 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006923
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006924 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006925 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6926 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006927}
6928
John McCall18a2c2c2010-11-09 22:22:12 +00006929std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6930 if (!Range.Width) return "0";
6931
6932 llvm::APSInt ValueInRange = Value;
6933 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006934 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006935 return ValueInRange.toString(10);
6936}
6937
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006938static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6939 if (!isa<ImplicitCastExpr>(Ex))
6940 return false;
6941
6942 Expr *InnerE = Ex->IgnoreParenImpCasts();
6943 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6944 const Type *Source =
6945 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6946 if (Target->isDependentType())
6947 return false;
6948
6949 const BuiltinType *FloatCandidateBT =
6950 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6951 const Type *BoolCandidateType = ToBool ? Target : Source;
6952
6953 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6954 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6955}
6956
6957void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6958 SourceLocation CC) {
6959 unsigned NumArgs = TheCall->getNumArgs();
6960 for (unsigned i = 0; i < NumArgs; ++i) {
6961 Expr *CurrA = TheCall->getArg(i);
6962 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6963 continue;
6964
6965 bool IsSwapped = ((i > 0) &&
6966 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6967 IsSwapped |= ((i < (NumArgs - 1)) &&
6968 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6969 if (IsSwapped) {
6970 // Warn on this floating-point to bool conversion.
6971 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6972 CurrA->getType(), CC,
6973 diag::warn_impcast_floating_point_to_bool);
6974 }
6975 }
6976}
6977
Richard Trieu5b993502014-10-15 03:42:06 +00006978static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6979 SourceLocation CC) {
6980 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6981 E->getExprLoc()))
6982 return;
6983
6984 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6985 const Expr::NullPointerConstantKind NullKind =
6986 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6987 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6988 return;
6989
6990 // Return if target type is a safe conversion.
6991 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6992 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6993 return;
6994
6995 SourceLocation Loc = E->getSourceRange().getBegin();
6996
6997 // __null is usually wrapped in a macro. Go up a macro if that is the case.
6998 if (NullKind == Expr::NPCK_GNUNull) {
6999 if (Loc.isMacroID())
7000 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
7001 }
7002
7003 // Only warn if the null and context location are in the same macro expansion.
7004 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
7005 return;
7006
7007 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
7008 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
7009 << FixItHint::CreateReplacement(Loc,
7010 S.getFixItZeroLiteralForType(T, Loc));
7011}
7012
Douglas Gregor5054cb02015-07-07 03:58:22 +00007013static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7014 ObjCArrayLiteral *ArrayLiteral);
7015static void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7016 ObjCDictionaryLiteral *DictionaryLiteral);
7017
7018/// Check a single element within a collection literal against the
7019/// target element type.
7020static void checkObjCCollectionLiteralElement(Sema &S,
7021 QualType TargetElementType,
7022 Expr *Element,
7023 unsigned ElementKind) {
7024 // Skip a bitcast to 'id' or qualified 'id'.
7025 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
7026 if (ICE->getCastKind() == CK_BitCast &&
7027 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
7028 Element = ICE->getSubExpr();
7029 }
7030
7031 QualType ElementType = Element->getType();
7032 ExprResult ElementResult(Element);
7033 if (ElementType->getAs<ObjCObjectPointerType>() &&
7034 S.CheckSingleAssignmentConstraints(TargetElementType,
7035 ElementResult,
7036 false, false)
7037 != Sema::Compatible) {
7038 S.Diag(Element->getLocStart(),
7039 diag::warn_objc_collection_literal_element)
7040 << ElementType << ElementKind << TargetElementType
7041 << Element->getSourceRange();
7042 }
7043
7044 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7045 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7046 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7047 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7048}
7049
7050/// Check an Objective-C array literal being converted to the given
7051/// target type.
7052static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7053 ObjCArrayLiteral *ArrayLiteral) {
7054 if (!S.NSArrayDecl)
7055 return;
7056
7057 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7058 if (!TargetObjCPtr)
7059 return;
7060
7061 if (TargetObjCPtr->isUnspecialized() ||
7062 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7063 != S.NSArrayDecl->getCanonicalDecl())
7064 return;
7065
7066 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7067 if (TypeArgs.size() != 1)
7068 return;
7069
7070 QualType TargetElementType = TypeArgs[0];
7071 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
7072 checkObjCCollectionLiteralElement(S, TargetElementType,
7073 ArrayLiteral->getElement(I),
7074 0);
7075 }
7076}
7077
7078/// Check an Objective-C dictionary literal being converted to the given
7079/// target type.
7080static void checkObjCDictionaryLiteral(
7081 Sema &S, QualType TargetType,
7082 ObjCDictionaryLiteral *DictionaryLiteral) {
7083 if (!S.NSDictionaryDecl)
7084 return;
7085
7086 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7087 if (!TargetObjCPtr)
7088 return;
7089
7090 if (TargetObjCPtr->isUnspecialized() ||
7091 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7092 != S.NSDictionaryDecl->getCanonicalDecl())
7093 return;
7094
7095 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7096 if (TypeArgs.size() != 2)
7097 return;
7098
7099 QualType TargetKeyType = TypeArgs[0];
7100 QualType TargetObjectType = TypeArgs[1];
7101 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
7102 auto Element = DictionaryLiteral->getKeyValueElement(I);
7103 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7104 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7105 }
7106}
7107
John McCallcc7e5bf2010-05-06 08:58:33 +00007108void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00007109 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007110 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00007111
John McCallcc7e5bf2010-05-06 08:58:33 +00007112 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
7113 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
7114 if (Source == Target) return;
7115 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00007116
Chandler Carruthc22845a2011-07-26 05:40:03 +00007117 // If the conversion context location is invalid don't complain. We also
7118 // don't want to emit a warning if the issue occurs from the expansion of
7119 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
7120 // delay this check as long as possible. Once we detect we are in that
7121 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007122 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00007123 return;
7124
Richard Trieu021baa32011-09-23 20:10:00 +00007125 // Diagnose implicit casts to bool.
7126 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
7127 if (isa<StringLiteral>(E))
7128 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00007129 // and expressions, for instance, assert(0 && "error here"), are
7130 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00007131 return DiagnoseImpCast(S, E, T, CC,
7132 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00007133 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7134 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7135 // This covers the literal expressions that evaluate to Objective-C
7136 // objects.
7137 return DiagnoseImpCast(S, E, T, CC,
7138 diag::warn_impcast_objective_c_literal_to_bool);
7139 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007140 if (Source->isPointerType() || Source->canDecayToPointerType()) {
7141 // Warn on pointer to bool conversion that is always true.
7142 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
7143 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00007144 }
Richard Trieu021baa32011-09-23 20:10:00 +00007145 }
John McCall263a48b2010-01-04 23:31:57 +00007146
Douglas Gregor5054cb02015-07-07 03:58:22 +00007147 // Check implicit casts from Objective-C collection literals to specialized
7148 // collection types, e.g., NSArray<NSString *> *.
7149 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7150 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
7151 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7152 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
7153
John McCall263a48b2010-01-04 23:31:57 +00007154 // Strip vector types.
7155 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007156 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007157 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007158 return;
John McCallacf0ee52010-10-08 02:01:28 +00007159 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007160 }
Chris Lattneree7286f2011-06-14 04:51:15 +00007161
7162 // If the vector cast is cast between two vectors of the same size, it is
7163 // a bitcast, not a conversion.
7164 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
7165 return;
John McCall263a48b2010-01-04 23:31:57 +00007166
7167 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
7168 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
7169 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00007170 if (auto VecTy = dyn_cast<VectorType>(Target))
7171 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00007172
7173 // Strip complex types.
7174 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007175 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007176 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007177 return;
7178
John McCallacf0ee52010-10-08 02:01:28 +00007179 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007180 }
John McCall263a48b2010-01-04 23:31:57 +00007181
7182 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
7183 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
7184 }
7185
7186 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
7187 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
7188
7189 // If the source is floating point...
7190 if (SourceBT && SourceBT->isFloatingPoint()) {
7191 // ...and the target is floating point...
7192 if (TargetBT && TargetBT->isFloatingPoint()) {
7193 // ...then warn if we're dropping FP rank.
7194
7195 // Builtin FP kinds are ordered by increasing FP rank.
7196 if (SourceBT->getKind() > TargetBT->getKind()) {
7197 // Don't warn about float constants that are precisely
7198 // representable in the target type.
7199 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007200 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00007201 // Value might be a float, a float vector, or a float complex.
7202 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00007203 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
7204 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00007205 return;
7206 }
7207
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007208 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007209 return;
7210
John McCallacf0ee52010-10-08 02:01:28 +00007211 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00007212 }
7213 return;
7214 }
7215
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007216 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00007217 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007218 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007219 return;
7220
Chandler Carruth22c7a792011-02-17 11:05:49 +00007221 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00007222 // We also want to warn on, e.g., "int i = -1.234"
7223 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7224 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7225 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7226
Chandler Carruth016ef402011-04-10 08:36:24 +00007227 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
7228 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00007229 } else {
7230 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
7231 }
7232 }
John McCall263a48b2010-01-04 23:31:57 +00007233
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007234 // If the target is bool, warn if expr is a function or method call.
7235 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
7236 isa<CallExpr>(E)) {
7237 // Check last argument of function call to see if it is an
7238 // implicit cast from a type matching the type the result
7239 // is being cast to.
7240 CallExpr *CEx = cast<CallExpr>(E);
7241 unsigned NumArgs = CEx->getNumArgs();
7242 if (NumArgs > 0) {
7243 Expr *LastA = CEx->getArg(NumArgs - 1);
7244 Expr *InnerE = LastA->IgnoreParenImpCasts();
7245 const Type *InnerType =
7246 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7247 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
7248 // Warn on this floating-point to bool conversion
7249 DiagnoseImpCast(S, E, T, CC,
7250 diag::warn_impcast_floating_point_to_bool);
7251 }
7252 }
7253 }
John McCall263a48b2010-01-04 23:31:57 +00007254 return;
7255 }
7256
Richard Trieu5b993502014-10-15 03:42:06 +00007257 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00007258
David Blaikie9366d2b2012-06-19 21:19:06 +00007259 if (!Source->isIntegerType() || !Target->isIntegerType())
7260 return;
7261
David Blaikie7555b6a2012-05-15 16:56:36 +00007262 // TODO: remove this early return once the false positives for constant->bool
7263 // in templates, macros, etc, are reduced or removed.
7264 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
7265 return;
7266
John McCallcc7e5bf2010-05-06 08:58:33 +00007267 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00007268 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00007269
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007270 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00007271 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007272 // TODO: this should happen for bitfield stores, too.
7273 llvm::APSInt Value(32);
7274 if (E->isIntegerConstantExpr(Value, S.Context)) {
7275 if (S.SourceMgr.isInSystemMacro(CC))
7276 return;
7277
John McCall18a2c2c2010-11-09 22:22:12 +00007278 std::string PrettySourceValue = Value.toString(10);
7279 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007280
Ted Kremenek33ba9952011-10-22 02:37:33 +00007281 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7282 S.PDiag(diag::warn_impcast_integer_precision_constant)
7283 << PrettySourceValue << PrettyTargetValue
7284 << E->getType() << T << E->getSourceRange()
7285 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00007286 return;
7287 }
7288
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007289 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
7290 if (S.SourceMgr.isInSystemMacro(CC))
7291 return;
7292
David Blaikie9455da02012-04-12 22:40:54 +00007293 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00007294 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
7295 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00007296 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00007297 }
7298
7299 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
7300 (!TargetRange.NonNegative && SourceRange.NonNegative &&
7301 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007302
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007303 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007304 return;
7305
John McCallcc7e5bf2010-05-06 08:58:33 +00007306 unsigned DiagID = diag::warn_impcast_integer_sign;
7307
7308 // Traditionally, gcc has warned about this under -Wsign-compare.
7309 // We also want to warn about it in -Wconversion.
7310 // So if -Wconversion is off, use a completely identical diagnostic
7311 // in the sign-compare group.
7312 // The conditional-checking code will
7313 if (ICContext) {
7314 DiagID = diag::warn_impcast_integer_sign_conditional;
7315 *ICContext = true;
7316 }
7317
John McCallacf0ee52010-10-08 02:01:28 +00007318 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00007319 }
7320
Douglas Gregora78f1932011-02-22 02:45:07 +00007321 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00007322 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
7323 // type, to give us better diagnostics.
7324 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007325 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00007326 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7327 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
7328 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
7329 SourceType = S.Context.getTypeDeclType(Enum);
7330 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
7331 }
7332 }
7333
Douglas Gregora78f1932011-02-22 02:45:07 +00007334 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
7335 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00007336 if (SourceEnum->getDecl()->hasNameForLinkage() &&
7337 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007338 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007339 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007340 return;
7341
Douglas Gregor364f7db2011-03-12 00:14:31 +00007342 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00007343 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007344 }
Douglas Gregora78f1932011-02-22 02:45:07 +00007345
John McCall263a48b2010-01-04 23:31:57 +00007346 return;
7347}
7348
David Blaikie18e9ac72012-05-15 21:57:38 +00007349void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7350 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007351
7352void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00007353 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007354 E = E->IgnoreParenImpCasts();
7355
7356 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00007357 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007358
John McCallacf0ee52010-10-08 02:01:28 +00007359 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007360 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007361 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00007362 return;
7363}
7364
David Blaikie18e9ac72012-05-15 21:57:38 +00007365void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7366 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00007367 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007368
7369 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00007370 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
7371 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007372
7373 // If -Wconversion would have warned about either of the candidates
7374 // for a signedness conversion to the context type...
7375 if (!Suspicious) return;
7376
7377 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007378 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00007379 return;
7380
John McCallcc7e5bf2010-05-06 08:58:33 +00007381 // ...then check whether it would have warned about either of the
7382 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00007383 if (E->getType() == T) return;
7384
7385 Suspicious = false;
7386 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
7387 E->getType(), CC, &Suspicious);
7388 if (!Suspicious)
7389 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00007390 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007391}
7392
Richard Trieu65724892014-11-15 06:37:39 +00007393/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7394/// Input argument E is a logical expression.
7395static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
7396 if (S.getLangOpts().Bool)
7397 return;
7398 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
7399}
7400
John McCallcc7e5bf2010-05-06 08:58:33 +00007401/// AnalyzeImplicitConversions - Find and report any interesting
7402/// implicit conversions in the given expression. There are a couple
7403/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007404void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00007405 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00007406 Expr *E = OrigE->IgnoreParenImpCasts();
7407
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00007408 if (E->isTypeDependent() || E->isValueDependent())
7409 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00007410
John McCallcc7e5bf2010-05-06 08:58:33 +00007411 // For conditional operators, we analyze the arguments as if they
7412 // were being fed directly into the output.
7413 if (isa<ConditionalOperator>(E)) {
7414 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00007415 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007416 return;
7417 }
7418
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007419 // Check implicit argument conversions for function calls.
7420 if (CallExpr *Call = dyn_cast<CallExpr>(E))
7421 CheckImplicitArgumentConversions(S, Call, CC);
7422
John McCallcc7e5bf2010-05-06 08:58:33 +00007423 // Go ahead and check any implicit conversions we might have skipped.
7424 // The non-canonical typecheck is just an optimization;
7425 // CheckImplicitConversion will filter out dead implicit conversions.
7426 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007427 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007428
7429 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00007430
7431 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00007432 if (POE->getResultExpr())
7433 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00007434 }
7435
Fariborz Jahanian947efbc2015-02-26 17:59:54 +00007436 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
7437 if (OVE->getSourceExpr())
7438 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
7439 return;
7440 }
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00007441
John McCallcc7e5bf2010-05-06 08:58:33 +00007442 // Skip past explicit casts.
7443 if (isa<ExplicitCastExpr>(E)) {
7444 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00007445 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007446 }
7447
John McCalld2a53122010-11-09 23:24:47 +00007448 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7449 // Do a somewhat different check with comparison operators.
7450 if (BO->isComparisonOp())
7451 return AnalyzeComparison(S, BO);
7452
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007453 // And with simple assignments.
7454 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00007455 return AnalyzeAssignment(S, BO);
7456 }
John McCallcc7e5bf2010-05-06 08:58:33 +00007457
7458 // These break the otherwise-useful invariant below. Fortunately,
7459 // we don't really need to recurse into them, because any internal
7460 // expressions should have been analyzed already when they were
7461 // built into statements.
7462 if (isa<StmtExpr>(E)) return;
7463
7464 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00007465 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00007466
7467 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00007468 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00007469 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00007470 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00007471 for (Stmt *SubStmt : E->children()) {
7472 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00007473 if (!ChildExpr)
7474 continue;
7475
Richard Trieu955231d2014-01-25 01:10:35 +00007476 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00007477 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00007478 // Ignore checking string literals that are in logical and operators.
7479 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00007480 continue;
7481 AnalyzeImplicitConversions(S, ChildExpr, CC);
7482 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007483
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007484 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00007485 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
7486 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007487 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00007488
7489 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
7490 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007491 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007492 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007493
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007494 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
7495 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00007496 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007497}
7498
7499} // end anonymous namespace
7500
Richard Trieu3bb8b562014-02-26 02:36:06 +00007501enum {
7502 AddressOf,
7503 FunctionPointer,
7504 ArrayPointer
7505};
7506
Richard Trieuc1888e02014-06-28 23:25:37 +00007507// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
7508// Returns true when emitting a warning about taking the address of a reference.
7509static bool CheckForReference(Sema &SemaRef, const Expr *E,
7510 PartialDiagnostic PD) {
7511 E = E->IgnoreParenImpCasts();
7512
7513 const FunctionDecl *FD = nullptr;
7514
7515 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7516 if (!DRE->getDecl()->getType()->isReferenceType())
7517 return false;
7518 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7519 if (!M->getMemberDecl()->getType()->isReferenceType())
7520 return false;
7521 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00007522 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00007523 return false;
7524 FD = Call->getDirectCallee();
7525 } else {
7526 return false;
7527 }
7528
7529 SemaRef.Diag(E->getExprLoc(), PD);
7530
7531 // If possible, point to location of function.
7532 if (FD) {
7533 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
7534 }
7535
7536 return true;
7537}
7538
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007539// Returns true if the SourceLocation is expanded from any macro body.
7540// Returns false if the SourceLocation is invalid, is from not in a macro
7541// expansion, or is from expanded from a top-level macro argument.
7542static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
7543 if (Loc.isInvalid())
7544 return false;
7545
7546 while (Loc.isMacroID()) {
7547 if (SM.isMacroBodyExpansion(Loc))
7548 return true;
7549 Loc = SM.getImmediateMacroCallerLoc(Loc);
7550 }
7551
7552 return false;
7553}
7554
Richard Trieu3bb8b562014-02-26 02:36:06 +00007555/// \brief Diagnose pointers that are always non-null.
7556/// \param E the expression containing the pointer
7557/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
7558/// compared to a null pointer
7559/// \param IsEqual True when the comparison is equal to a null pointer
7560/// \param Range Extra SourceRange to highlight in the diagnostic
7561void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
7562 Expr::NullPointerConstantKind NullKind,
7563 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00007564 if (!E)
7565 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007566
7567 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007568 if (E->getExprLoc().isMacroID()) {
7569 const SourceManager &SM = getSourceManager();
7570 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
7571 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00007572 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007573 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007574 E = E->IgnoreImpCasts();
7575
7576 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
7577
Richard Trieuf7432752014-06-06 21:39:26 +00007578 if (isa<CXXThisExpr>(E)) {
7579 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
7580 : diag::warn_this_bool_conversion;
7581 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
7582 return;
7583 }
7584
Richard Trieu3bb8b562014-02-26 02:36:06 +00007585 bool IsAddressOf = false;
7586
7587 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7588 if (UO->getOpcode() != UO_AddrOf)
7589 return;
7590 IsAddressOf = true;
7591 E = UO->getSubExpr();
7592 }
7593
Richard Trieuc1888e02014-06-28 23:25:37 +00007594 if (IsAddressOf) {
7595 unsigned DiagID = IsCompare
7596 ? diag::warn_address_of_reference_null_compare
7597 : diag::warn_address_of_reference_bool_conversion;
7598 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
7599 << IsEqual;
7600 if (CheckForReference(*this, E, PD)) {
7601 return;
7602 }
7603 }
7604
Richard Trieu3bb8b562014-02-26 02:36:06 +00007605 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00007606 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007607 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
7608 D = R->getDecl();
7609 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7610 D = M->getMemberDecl();
7611 }
7612
7613 // Weak Decls can be null.
7614 if (!D || D->isWeak())
7615 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007616
7617 // Check for parameter decl with nonnull attribute
7618 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
7619 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
7620 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
7621 unsigned NumArgs = FD->getNumParams();
7622 llvm::SmallBitVector AttrNonNull(NumArgs);
7623 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
7624 if (!NonNull->args_size()) {
7625 AttrNonNull.set(0, NumArgs);
7626 break;
7627 }
7628 for (unsigned Val : NonNull->args()) {
7629 if (Val >= NumArgs)
7630 continue;
7631 AttrNonNull.set(Val);
7632 }
7633 }
7634 if (!AttrNonNull.empty())
7635 for (unsigned i = 0; i < NumArgs; ++i)
Aaron Ballman2521f362014-12-11 19:35:42 +00007636 if (FD->getParamDecl(i) == PV &&
7637 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007638 std::string Str;
7639 llvm::raw_string_ostream S(Str);
7640 E->printPretty(S, nullptr, getPrintingPolicy());
7641 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
7642 : diag::warn_cast_nonnull_to_bool;
7643 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
7644 << Range << IsEqual;
7645 return;
7646 }
7647 }
7648 }
7649
Richard Trieu3bb8b562014-02-26 02:36:06 +00007650 QualType T = D->getType();
7651 const bool IsArray = T->isArrayType();
7652 const bool IsFunction = T->isFunctionType();
7653
Richard Trieuc1888e02014-06-28 23:25:37 +00007654 // Address of function is used to silence the function warning.
7655 if (IsAddressOf && IsFunction) {
7656 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007657 }
7658
7659 // Found nothing.
7660 if (!IsAddressOf && !IsFunction && !IsArray)
7661 return;
7662
7663 // Pretty print the expression for the diagnostic.
7664 std::string Str;
7665 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00007666 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00007667
7668 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7669 : diag::warn_impcast_pointer_to_bool;
7670 unsigned DiagType;
7671 if (IsAddressOf)
7672 DiagType = AddressOf;
7673 else if (IsFunction)
7674 DiagType = FunctionPointer;
7675 else if (IsArray)
7676 DiagType = ArrayPointer;
7677 else
7678 llvm_unreachable("Could not determine diagnostic.");
7679 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7680 << Range << IsEqual;
7681
7682 if (!IsFunction)
7683 return;
7684
7685 // Suggest '&' to silence the function warning.
7686 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7687 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7688
7689 // Check to see if '()' fixit should be emitted.
7690 QualType ReturnType;
7691 UnresolvedSet<4> NonTemplateOverloads;
7692 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7693 if (ReturnType.isNull())
7694 return;
7695
7696 if (IsCompare) {
7697 // There are two cases here. If there is null constant, the only suggest
7698 // for a pointer return type. If the null is 0, then suggest if the return
7699 // type is a pointer or an integer type.
7700 if (!ReturnType->isPointerType()) {
7701 if (NullKind == Expr::NPCK_ZeroExpression ||
7702 NullKind == Expr::NPCK_ZeroLiteral) {
7703 if (!ReturnType->isIntegerType())
7704 return;
7705 } else {
7706 return;
7707 }
7708 }
7709 } else { // !IsCompare
7710 // For function to bool, only suggest if the function pointer has bool
7711 // return type.
7712 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7713 return;
7714 }
7715 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007716 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00007717}
7718
7719
John McCallcc7e5bf2010-05-06 08:58:33 +00007720/// Diagnoses "dangerous" implicit conversions within the given
7721/// expression (which is a full expression). Implements -Wconversion
7722/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007723///
7724/// \param CC the "context" location of the implicit conversion, i.e.
7725/// the most location of the syntactic entity requiring the implicit
7726/// conversion
7727void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007728 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00007729 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00007730 return;
7731
7732 // Don't diagnose for value- or type-dependent expressions.
7733 if (E->isTypeDependent() || E->isValueDependent())
7734 return;
7735
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007736 // Check for array bounds violations in cases where the check isn't triggered
7737 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7738 // ArraySubscriptExpr is on the RHS of a variable initialization.
7739 CheckArrayAccess(E);
7740
John McCallacf0ee52010-10-08 02:01:28 +00007741 // This is not the right CC for (e.g.) a variable initialization.
7742 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007743}
7744
Richard Trieu65724892014-11-15 06:37:39 +00007745/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7746/// Input argument E is a logical expression.
7747void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7748 ::CheckBoolLikeConversion(*this, E, CC);
7749}
7750
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007751/// Diagnose when expression is an integer constant expression and its evaluation
7752/// results in integer overflow
7753void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00007754 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7755 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007756}
7757
Richard Smithc406cb72013-01-17 01:17:56 +00007758namespace {
7759/// \brief Visitor for expressions which looks for unsequenced operations on the
7760/// same object.
7761class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007762 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7763
Richard Smithc406cb72013-01-17 01:17:56 +00007764 /// \brief A tree of sequenced regions within an expression. Two regions are
7765 /// unsequenced if one is an ancestor or a descendent of the other. When we
7766 /// finish processing an expression with sequencing, such as a comma
7767 /// expression, we fold its tree nodes into its parent, since they are
7768 /// unsequenced with respect to nodes we will visit later.
7769 class SequenceTree {
7770 struct Value {
7771 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7772 unsigned Parent : 31;
7773 bool Merged : 1;
7774 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007775 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00007776
7777 public:
7778 /// \brief A region within an expression which may be sequenced with respect
7779 /// to some other region.
7780 class Seq {
7781 explicit Seq(unsigned N) : Index(N) {}
7782 unsigned Index;
7783 friend class SequenceTree;
7784 public:
7785 Seq() : Index(0) {}
7786 };
7787
7788 SequenceTree() { Values.push_back(Value(0)); }
7789 Seq root() const { return Seq(0); }
7790
7791 /// \brief Create a new sequence of operations, which is an unsequenced
7792 /// subset of \p Parent. This sequence of operations is sequenced with
7793 /// respect to other children of \p Parent.
7794 Seq allocate(Seq Parent) {
7795 Values.push_back(Value(Parent.Index));
7796 return Seq(Values.size() - 1);
7797 }
7798
7799 /// \brief Merge a sequence of operations into its parent.
7800 void merge(Seq S) {
7801 Values[S.Index].Merged = true;
7802 }
7803
7804 /// \brief Determine whether two operations are unsequenced. This operation
7805 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7806 /// should have been merged into its parent as appropriate.
7807 bool isUnsequenced(Seq Cur, Seq Old) {
7808 unsigned C = representative(Cur.Index);
7809 unsigned Target = representative(Old.Index);
7810 while (C >= Target) {
7811 if (C == Target)
7812 return true;
7813 C = Values[C].Parent;
7814 }
7815 return false;
7816 }
7817
7818 private:
7819 /// \brief Pick a representative for a sequence.
7820 unsigned representative(unsigned K) {
7821 if (Values[K].Merged)
7822 // Perform path compression as we go.
7823 return Values[K].Parent = representative(Values[K].Parent);
7824 return K;
7825 }
7826 };
7827
7828 /// An object for which we can track unsequenced uses.
7829 typedef NamedDecl *Object;
7830
7831 /// Different flavors of object usage which we track. We only track the
7832 /// least-sequenced usage of each kind.
7833 enum UsageKind {
7834 /// A read of an object. Multiple unsequenced reads are OK.
7835 UK_Use,
7836 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00007837 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00007838 UK_ModAsValue,
7839 /// A modification of an object which is not sequenced before the value
7840 /// computation of the expression, such as n++.
7841 UK_ModAsSideEffect,
7842
7843 UK_Count = UK_ModAsSideEffect + 1
7844 };
7845
7846 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00007847 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00007848 Expr *Use;
7849 SequenceTree::Seq Seq;
7850 };
7851
7852 struct UsageInfo {
7853 UsageInfo() : Diagnosed(false) {}
7854 Usage Uses[UK_Count];
7855 /// Have we issued a diagnostic for this variable already?
7856 bool Diagnosed;
7857 };
7858 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7859
7860 Sema &SemaRef;
7861 /// Sequenced regions within the expression.
7862 SequenceTree Tree;
7863 /// Declaration modifications and references which we have seen.
7864 UsageInfoMap UsageMap;
7865 /// The region we are currently within.
7866 SequenceTree::Seq Region;
7867 /// Filled in with declarations which were modified as a side-effect
7868 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007869 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00007870 /// Expressions to check later. We defer checking these to reduce
7871 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007872 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00007873
7874 /// RAII object wrapping the visitation of a sequenced subexpression of an
7875 /// expression. At the end of this process, the side-effects of the evaluation
7876 /// become sequenced with respect to the value computation of the result, so
7877 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7878 /// UK_ModAsValue.
7879 struct SequencedSubexpression {
7880 SequencedSubexpression(SequenceChecker &Self)
7881 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7882 Self.ModAsSideEffect = &ModAsSideEffect;
7883 }
7884 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00007885 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7886 MI != ME; ++MI) {
7887 UsageInfo &U = Self.UsageMap[MI->first];
7888 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7889 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7890 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00007891 }
7892 Self.ModAsSideEffect = OldModAsSideEffect;
7893 }
7894
7895 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007896 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7897 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00007898 };
7899
Richard Smith40238f02013-06-20 22:21:56 +00007900 /// RAII object wrapping the visitation of a subexpression which we might
7901 /// choose to evaluate as a constant. If any subexpression is evaluated and
7902 /// found to be non-constant, this allows us to suppress the evaluation of
7903 /// the outer expression.
7904 class EvaluationTracker {
7905 public:
7906 EvaluationTracker(SequenceChecker &Self)
7907 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7908 Self.EvalTracker = this;
7909 }
7910 ~EvaluationTracker() {
7911 Self.EvalTracker = Prev;
7912 if (Prev)
7913 Prev->EvalOK &= EvalOK;
7914 }
7915
7916 bool evaluate(const Expr *E, bool &Result) {
7917 if (!EvalOK || E->isValueDependent())
7918 return false;
7919 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7920 return EvalOK;
7921 }
7922
7923 private:
7924 SequenceChecker &Self;
7925 EvaluationTracker *Prev;
7926 bool EvalOK;
7927 } *EvalTracker;
7928
Richard Smithc406cb72013-01-17 01:17:56 +00007929 /// \brief Find the object which is produced by the specified expression,
7930 /// if any.
7931 Object getObject(Expr *E, bool Mod) const {
7932 E = E->IgnoreParenCasts();
7933 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7934 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7935 return getObject(UO->getSubExpr(), Mod);
7936 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7937 if (BO->getOpcode() == BO_Comma)
7938 return getObject(BO->getRHS(), Mod);
7939 if (Mod && BO->isAssignmentOp())
7940 return getObject(BO->getLHS(), Mod);
7941 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7942 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7943 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7944 return ME->getMemberDecl();
7945 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7946 // FIXME: If this is a reference, map through to its value.
7947 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00007948 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00007949 }
7950
7951 /// \brief Note that an object was modified or used by an expression.
7952 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7953 Usage &U = UI.Uses[UK];
7954 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7955 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7956 ModAsSideEffect->push_back(std::make_pair(O, U));
7957 U.Use = Ref;
7958 U.Seq = Region;
7959 }
7960 }
7961 /// \brief Check whether a modification or use conflicts with a prior usage.
7962 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7963 bool IsModMod) {
7964 if (UI.Diagnosed)
7965 return;
7966
7967 const Usage &U = UI.Uses[OtherKind];
7968 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7969 return;
7970
7971 Expr *Mod = U.Use;
7972 Expr *ModOrUse = Ref;
7973 if (OtherKind == UK_Use)
7974 std::swap(Mod, ModOrUse);
7975
7976 SemaRef.Diag(Mod->getExprLoc(),
7977 IsModMod ? diag::warn_unsequenced_mod_mod
7978 : diag::warn_unsequenced_mod_use)
7979 << O << SourceRange(ModOrUse->getExprLoc());
7980 UI.Diagnosed = true;
7981 }
7982
7983 void notePreUse(Object O, Expr *Use) {
7984 UsageInfo &U = UsageMap[O];
7985 // Uses conflict with other modifications.
7986 checkUsage(O, U, Use, UK_ModAsValue, false);
7987 }
7988 void notePostUse(Object O, Expr *Use) {
7989 UsageInfo &U = UsageMap[O];
7990 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7991 addUsage(U, O, Use, UK_Use);
7992 }
7993
7994 void notePreMod(Object O, Expr *Mod) {
7995 UsageInfo &U = UsageMap[O];
7996 // Modifications conflict with other modifications and with uses.
7997 checkUsage(O, U, Mod, UK_ModAsValue, true);
7998 checkUsage(O, U, Mod, UK_Use, false);
7999 }
8000 void notePostMod(Object O, Expr *Use, UsageKind UK) {
8001 UsageInfo &U = UsageMap[O];
8002 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
8003 addUsage(U, O, Use, UK);
8004 }
8005
8006public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008007 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00008008 : Base(S.Context), SemaRef(S), Region(Tree.root()),
8009 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008010 Visit(E);
8011 }
8012
8013 void VisitStmt(Stmt *S) {
8014 // Skip all statements which aren't expressions for now.
8015 }
8016
8017 void VisitExpr(Expr *E) {
8018 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00008019 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008020 }
8021
8022 void VisitCastExpr(CastExpr *E) {
8023 Object O = Object();
8024 if (E->getCastKind() == CK_LValueToRValue)
8025 O = getObject(E->getSubExpr(), false);
8026
8027 if (O)
8028 notePreUse(O, E);
8029 VisitExpr(E);
8030 if (O)
8031 notePostUse(O, E);
8032 }
8033
8034 void VisitBinComma(BinaryOperator *BO) {
8035 // C++11 [expr.comma]p1:
8036 // Every value computation and side effect associated with the left
8037 // expression is sequenced before every value computation and side
8038 // effect associated with the right expression.
8039 SequenceTree::Seq LHS = Tree.allocate(Region);
8040 SequenceTree::Seq RHS = Tree.allocate(Region);
8041 SequenceTree::Seq OldRegion = Region;
8042
8043 {
8044 SequencedSubexpression SeqLHS(*this);
8045 Region = LHS;
8046 Visit(BO->getLHS());
8047 }
8048
8049 Region = RHS;
8050 Visit(BO->getRHS());
8051
8052 Region = OldRegion;
8053
8054 // Forget that LHS and RHS are sequenced. They are both unsequenced
8055 // with respect to other stuff.
8056 Tree.merge(LHS);
8057 Tree.merge(RHS);
8058 }
8059
8060 void VisitBinAssign(BinaryOperator *BO) {
8061 // The modification is sequenced after the value computation of the LHS
8062 // and RHS, so check it before inspecting the operands and update the
8063 // map afterwards.
8064 Object O = getObject(BO->getLHS(), true);
8065 if (!O)
8066 return VisitExpr(BO);
8067
8068 notePreMod(O, BO);
8069
8070 // C++11 [expr.ass]p7:
8071 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
8072 // only once.
8073 //
8074 // Therefore, for a compound assignment operator, O is considered used
8075 // everywhere except within the evaluation of E1 itself.
8076 if (isa<CompoundAssignOperator>(BO))
8077 notePreUse(O, BO);
8078
8079 Visit(BO->getLHS());
8080
8081 if (isa<CompoundAssignOperator>(BO))
8082 notePostUse(O, BO);
8083
8084 Visit(BO->getRHS());
8085
Richard Smith83e37bee2013-06-26 23:16:51 +00008086 // C++11 [expr.ass]p1:
8087 // the assignment is sequenced [...] before the value computation of the
8088 // assignment expression.
8089 // C11 6.5.16/3 has no such rule.
8090 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8091 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008092 }
8093 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
8094 VisitBinAssign(CAO);
8095 }
8096
8097 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8098 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8099 void VisitUnaryPreIncDec(UnaryOperator *UO) {
8100 Object O = getObject(UO->getSubExpr(), true);
8101 if (!O)
8102 return VisitExpr(UO);
8103
8104 notePreMod(O, UO);
8105 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00008106 // C++11 [expr.pre.incr]p1:
8107 // the expression ++x is equivalent to x+=1
8108 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8109 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008110 }
8111
8112 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8113 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8114 void VisitUnaryPostIncDec(UnaryOperator *UO) {
8115 Object O = getObject(UO->getSubExpr(), true);
8116 if (!O)
8117 return VisitExpr(UO);
8118
8119 notePreMod(O, UO);
8120 Visit(UO->getSubExpr());
8121 notePostMod(O, UO, UK_ModAsSideEffect);
8122 }
8123
8124 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
8125 void VisitBinLOr(BinaryOperator *BO) {
8126 // The side-effects of the LHS of an '&&' are sequenced before the
8127 // value computation of the RHS, and hence before the value computation
8128 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
8129 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00008130 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008131 {
8132 SequencedSubexpression Sequenced(*this);
8133 Visit(BO->getLHS());
8134 }
8135
8136 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008137 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008138 if (!Result)
8139 Visit(BO->getRHS());
8140 } else {
8141 // Check for unsequenced operations in the RHS, treating it as an
8142 // entirely separate evaluation.
8143 //
8144 // FIXME: If there are operations in the RHS which are unsequenced
8145 // with respect to operations outside the RHS, and those operations
8146 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00008147 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008148 }
Richard Smithc406cb72013-01-17 01:17:56 +00008149 }
8150 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00008151 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008152 {
8153 SequencedSubexpression Sequenced(*this);
8154 Visit(BO->getLHS());
8155 }
8156
8157 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008158 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008159 if (Result)
8160 Visit(BO->getRHS());
8161 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00008162 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008163 }
Richard Smithc406cb72013-01-17 01:17:56 +00008164 }
8165
8166 // Only visit the condition, unless we can be sure which subexpression will
8167 // be chosen.
8168 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00008169 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00008170 {
8171 SequencedSubexpression Sequenced(*this);
8172 Visit(CO->getCond());
8173 }
Richard Smithc406cb72013-01-17 01:17:56 +00008174
8175 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008176 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00008177 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008178 else {
Richard Smithd33f5202013-01-17 23:18:09 +00008179 WorkList.push_back(CO->getTrueExpr());
8180 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008181 }
Richard Smithc406cb72013-01-17 01:17:56 +00008182 }
8183
Richard Smithe3dbfe02013-06-30 10:40:20 +00008184 void VisitCallExpr(CallExpr *CE) {
8185 // C++11 [intro.execution]p15:
8186 // When calling a function [...], every value computation and side effect
8187 // associated with any argument expression, or with the postfix expression
8188 // designating the called function, is sequenced before execution of every
8189 // expression or statement in the body of the function [and thus before
8190 // the value computation of its result].
8191 SequencedSubexpression Sequenced(*this);
8192 Base::VisitCallExpr(CE);
8193
8194 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
8195 }
8196
Richard Smithc406cb72013-01-17 01:17:56 +00008197 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008198 // This is a call, so all subexpressions are sequenced before the result.
8199 SequencedSubexpression Sequenced(*this);
8200
Richard Smithc406cb72013-01-17 01:17:56 +00008201 if (!CCE->isListInitialization())
8202 return VisitExpr(CCE);
8203
8204 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008205 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008206 SequenceTree::Seq Parent = Region;
8207 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
8208 E = CCE->arg_end();
8209 I != E; ++I) {
8210 Region = Tree.allocate(Parent);
8211 Elts.push_back(Region);
8212 Visit(*I);
8213 }
8214
8215 // Forget that the initializers are sequenced.
8216 Region = Parent;
8217 for (unsigned I = 0; I < Elts.size(); ++I)
8218 Tree.merge(Elts[I]);
8219 }
8220
8221 void VisitInitListExpr(InitListExpr *ILE) {
8222 if (!SemaRef.getLangOpts().CPlusPlus11)
8223 return VisitExpr(ILE);
8224
8225 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008226 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008227 SequenceTree::Seq Parent = Region;
8228 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
8229 Expr *E = ILE->getInit(I);
8230 if (!E) continue;
8231 Region = Tree.allocate(Parent);
8232 Elts.push_back(Region);
8233 Visit(E);
8234 }
8235
8236 // Forget that the initializers are sequenced.
8237 Region = Parent;
8238 for (unsigned I = 0; I < Elts.size(); ++I)
8239 Tree.merge(Elts[I]);
8240 }
8241};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008242}
Richard Smithc406cb72013-01-17 01:17:56 +00008243
8244void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008245 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00008246 WorkList.push_back(E);
8247 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00008248 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00008249 SequenceChecker(*this, Item, WorkList);
8250 }
Richard Smithc406cb72013-01-17 01:17:56 +00008251}
8252
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008253void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
8254 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008255 CheckImplicitConversions(E, CheckLoc);
8256 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008257 if (!IsConstexpr && !E->isValueDependent())
8258 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008259}
8260
John McCall1f425642010-11-11 03:21:53 +00008261void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
8262 FieldDecl *BitField,
8263 Expr *Init) {
8264 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
8265}
8266
David Majnemer61a5bbf2015-04-07 22:08:51 +00008267static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
8268 SourceLocation Loc) {
8269 if (!PType->isVariablyModifiedType())
8270 return;
8271 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
8272 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
8273 return;
8274 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00008275 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
8276 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
8277 return;
8278 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00008279 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
8280 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
8281 return;
8282 }
8283
8284 const ArrayType *AT = S.Context.getAsArrayType(PType);
8285 if (!AT)
8286 return;
8287
8288 if (AT->getSizeModifier() != ArrayType::Star) {
8289 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
8290 return;
8291 }
8292
8293 S.Diag(Loc, diag::err_array_star_in_function_definition);
8294}
8295
Mike Stump0c2ec772010-01-21 03:59:47 +00008296/// CheckParmsForFunctionDef - Check that the parameters of the given
8297/// function are appropriate for the definition of a function. This
8298/// takes care of any checks that cannot be performed on the
8299/// declaration itself, e.g., that the types of each of the function
8300/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00008301bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
8302 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00008303 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008304 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00008305 for (; P != PEnd; ++P) {
8306 ParmVarDecl *Param = *P;
8307
Mike Stump0c2ec772010-01-21 03:59:47 +00008308 // C99 6.7.5.3p4: the parameters in a parameter type list in a
8309 // function declarator that is part of a function definition of
8310 // that function shall not have incomplete type.
8311 //
8312 // This is also C++ [dcl.fct]p6.
8313 if (!Param->isInvalidDecl() &&
8314 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008315 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008316 Param->setInvalidDecl();
8317 HasInvalidParm = true;
8318 }
8319
8320 // C99 6.9.1p5: If the declarator includes a parameter type list, the
8321 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00008322 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00008323 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00008324 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008325 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00008326 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00008327
8328 // C99 6.7.5.3p12:
8329 // If the function declarator is not part of a definition of that
8330 // function, parameters may have incomplete type and may use the [*]
8331 // notation in their sequences of declarator specifiers to specify
8332 // variable length array types.
8333 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00008334 // FIXME: This diagnostic should point the '[*]' if source-location
8335 // information is added for it.
8336 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008337
8338 // MSVC destroys objects passed by value in the callee. Therefore a
8339 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008340 // object's destructor. However, we don't perform any direct access check
8341 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00008342 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
8343 .getCXXABI()
8344 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00008345 if (!Param->isInvalidDecl()) {
8346 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
8347 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
8348 if (!ClassDecl->isInvalidDecl() &&
8349 !ClassDecl->hasIrrelevantDestructor() &&
8350 !ClassDecl->isDependentContext()) {
8351 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8352 MarkFunctionReferenced(Param->getLocation(), Destructor);
8353 DiagnoseUseOfDecl(Destructor, Param->getLocation());
8354 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008355 }
8356 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008357 }
Mike Stump0c2ec772010-01-21 03:59:47 +00008358 }
8359
8360 return HasInvalidParm;
8361}
John McCall2b5c1b22010-08-12 21:44:57 +00008362
8363/// CheckCastAlign - Implements -Wcast-align, which warns when a
8364/// pointer cast increases the alignment requirements.
8365void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
8366 // This is actually a lot of work to potentially be doing on every
8367 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008368 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00008369 return;
8370
8371 // Ignore dependent types.
8372 if (T->isDependentType() || Op->getType()->isDependentType())
8373 return;
8374
8375 // Require that the destination be a pointer type.
8376 const PointerType *DestPtr = T->getAs<PointerType>();
8377 if (!DestPtr) return;
8378
8379 // If the destination has alignment 1, we're done.
8380 QualType DestPointee = DestPtr->getPointeeType();
8381 if (DestPointee->isIncompleteType()) return;
8382 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
8383 if (DestAlign.isOne()) return;
8384
8385 // Require that the source be a pointer type.
8386 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
8387 if (!SrcPtr) return;
8388 QualType SrcPointee = SrcPtr->getPointeeType();
8389
8390 // Whitelist casts from cv void*. We already implicitly
8391 // whitelisted casts to cv void*, since they have alignment 1.
8392 // Also whitelist casts involving incomplete types, which implicitly
8393 // includes 'void'.
8394 if (SrcPointee->isIncompleteType()) return;
8395
8396 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
8397 if (SrcAlign >= DestAlign) return;
8398
8399 Diag(TRange.getBegin(), diag::warn_cast_align)
8400 << Op->getType() << T
8401 << static_cast<unsigned>(SrcAlign.getQuantity())
8402 << static_cast<unsigned>(DestAlign.getQuantity())
8403 << TRange << Op->getSourceRange();
8404}
8405
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008406static const Type* getElementType(const Expr *BaseExpr) {
8407 const Type* EltType = BaseExpr->getType().getTypePtr();
8408 if (EltType->isAnyPointerType())
8409 return EltType->getPointeeType().getTypePtr();
8410 else if (EltType->isArrayType())
8411 return EltType->getBaseElementTypeUnsafe();
8412 return EltType;
8413}
8414
Chandler Carruth28389f02011-08-05 09:10:50 +00008415/// \brief Check whether this array fits the idiom of a size-one tail padded
8416/// array member of a struct.
8417///
8418/// We avoid emitting out-of-bounds access warnings for such arrays as they are
8419/// commonly used to emulate flexible arrays in C89 code.
8420static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
8421 const NamedDecl *ND) {
8422 if (Size != 1 || !ND) return false;
8423
8424 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
8425 if (!FD) return false;
8426
8427 // Don't consider sizes resulting from macro expansions or template argument
8428 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00008429
8430 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008431 while (TInfo) {
8432 TypeLoc TL = TInfo->getTypeLoc();
8433 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00008434 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
8435 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008436 TInfo = TDL->getTypeSourceInfo();
8437 continue;
8438 }
David Blaikie6adc78e2013-02-18 22:06:02 +00008439 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
8440 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00008441 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
8442 return false;
8443 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008444 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00008445 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008446
8447 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00008448 if (!RD) return false;
8449 if (RD->isUnion()) return false;
8450 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8451 if (!CRD->isStandardLayout()) return false;
8452 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008453
Benjamin Kramer8c543672011-08-06 03:04:42 +00008454 // See if this is the last field decl in the record.
8455 const Decl *D = FD;
8456 while ((D = D->getNextDeclInContext()))
8457 if (isa<FieldDecl>(D))
8458 return false;
8459 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00008460}
8461
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008462void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008463 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00008464 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008465 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008466 if (IndexExpr->isValueDependent())
8467 return;
8468
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00008469 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008470 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008471 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008472 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008473 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00008474 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00008475
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008476 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008477 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00008478 return;
Richard Smith13f67182011-12-16 19:31:14 +00008479 if (IndexNegated)
8480 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00008481
Craig Topperc3ec1492014-05-26 06:22:03 +00008482 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00008483 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8484 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00008485 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00008486 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00008487
Ted Kremeneke4b316c2011-02-23 23:06:04 +00008488 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008489 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00008490 if (!size.isStrictlyPositive())
8491 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008492
8493 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00008494 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008495 // Make sure we're comparing apples to apples when comparing index to size
8496 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
8497 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00008498 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00008499 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008500 if (ptrarith_typesize != array_typesize) {
8501 // There's a cast to a different size type involved
8502 uint64_t ratio = array_typesize / ptrarith_typesize;
8503 // TODO: Be smarter about handling cases where array_typesize is not a
8504 // multiple of ptrarith_typesize
8505 if (ptrarith_typesize * ratio == array_typesize)
8506 size *= llvm::APInt(size.getBitWidth(), ratio);
8507 }
8508 }
8509
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008510 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008511 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008512 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008513 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008514
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008515 // For array subscripting the index must be less than size, but for pointer
8516 // arithmetic also allow the index (offset) to be equal to size since
8517 // computing the next address after the end of the array is legal and
8518 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008519 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00008520 return;
8521
8522 // Also don't warn for arrays of size 1 which are members of some
8523 // structure. These are often used to approximate flexible arrays in C89
8524 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008525 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00008526 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008527
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008528 // Suppress the warning if the subscript expression (as identified by the
8529 // ']' location) and the index expression are both from macro expansions
8530 // within a system header.
8531 if (ASE) {
8532 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
8533 ASE->getRBracketLoc());
8534 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
8535 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
8536 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00008537 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008538 return;
8539 }
8540 }
8541
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008542 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008543 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008544 DiagID = diag::warn_array_index_exceeds_bounds;
8545
8546 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8547 PDiag(DiagID) << index.toString(10, true)
8548 << size.toString(10, true)
8549 << (unsigned)size.getLimitedValue(~0U)
8550 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008551 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008552 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008553 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008554 DiagID = diag::warn_ptr_arith_precedes_bounds;
8555 if (index.isNegative()) index = -index;
8556 }
8557
8558 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8559 PDiag(DiagID) << index.toString(10, true)
8560 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00008561 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00008562
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00008563 if (!ND) {
8564 // Try harder to find a NamedDecl to point at in the note.
8565 while (const ArraySubscriptExpr *ASE =
8566 dyn_cast<ArraySubscriptExpr>(BaseExpr))
8567 BaseExpr = ASE->getBase()->IgnoreParenCasts();
8568 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8569 ND = dyn_cast<NamedDecl>(DRE->getDecl());
8570 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8571 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8572 }
8573
Chandler Carruth1af88f12011-02-17 21:10:52 +00008574 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008575 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
8576 PDiag(diag::note_array_index_out_of_bounds)
8577 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00008578}
8579
Ted Kremenekdf26df72011-03-01 18:41:00 +00008580void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008581 int AllowOnePastEnd = 0;
8582 while (expr) {
8583 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00008584 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008585 case Stmt::ArraySubscriptExprClass: {
8586 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008587 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008588 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00008589 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008590 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008591 case Stmt::OMPArraySectionExprClass: {
8592 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
8593 if (ASE->getLowerBound())
8594 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
8595 /*ASE=*/nullptr, AllowOnePastEnd > 0);
8596 return;
8597 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008598 case Stmt::UnaryOperatorClass: {
8599 // Only unwrap the * and & unary operators
8600 const UnaryOperator *UO = cast<UnaryOperator>(expr);
8601 expr = UO->getSubExpr();
8602 switch (UO->getOpcode()) {
8603 case UO_AddrOf:
8604 AllowOnePastEnd++;
8605 break;
8606 case UO_Deref:
8607 AllowOnePastEnd--;
8608 break;
8609 default:
8610 return;
8611 }
8612 break;
8613 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008614 case Stmt::ConditionalOperatorClass: {
8615 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
8616 if (const Expr *lhs = cond->getLHS())
8617 CheckArrayAccess(lhs);
8618 if (const Expr *rhs = cond->getRHS())
8619 CheckArrayAccess(rhs);
8620 return;
8621 }
8622 default:
8623 return;
8624 }
Peter Collingbourne91147592011-04-15 00:35:48 +00008625 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008626}
John McCall31168b02011-06-15 23:02:42 +00008627
8628//===--- CHECK: Objective-C retain cycles ----------------------------------//
8629
8630namespace {
8631 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00008632 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00008633 VarDecl *Variable;
8634 SourceRange Range;
8635 SourceLocation Loc;
8636 bool Indirect;
8637
8638 void setLocsFrom(Expr *e) {
8639 Loc = e->getExprLoc();
8640 Range = e->getSourceRange();
8641 }
8642 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008643}
John McCall31168b02011-06-15 23:02:42 +00008644
8645/// Consider whether capturing the given variable can possibly lead to
8646/// a retain cycle.
8647static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00008648 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00008649 // lifetime. In MRR, it's captured strongly if the variable is
8650 // __block and has an appropriate type.
8651 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8652 return false;
8653
8654 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008655 if (ref)
8656 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00008657 return true;
8658}
8659
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008660static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00008661 while (true) {
8662 e = e->IgnoreParens();
8663 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
8664 switch (cast->getCastKind()) {
8665 case CK_BitCast:
8666 case CK_LValueBitCast:
8667 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00008668 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00008669 e = cast->getSubExpr();
8670 continue;
8671
John McCall31168b02011-06-15 23:02:42 +00008672 default:
8673 return false;
8674 }
8675 }
8676
8677 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
8678 ObjCIvarDecl *ivar = ref->getDecl();
8679 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8680 return false;
8681
8682 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008683 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00008684 return false;
8685
8686 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8687 owner.Indirect = true;
8688 return true;
8689 }
8690
8691 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8692 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8693 if (!var) return false;
8694 return considerVariable(var, ref, owner);
8695 }
8696
John McCall31168b02011-06-15 23:02:42 +00008697 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8698 if (member->isArrow()) return false;
8699
8700 // Don't count this as an indirect ownership.
8701 e = member->getBase();
8702 continue;
8703 }
8704
John McCallfe96e0b2011-11-06 09:01:30 +00008705 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8706 // Only pay attention to pseudo-objects on property references.
8707 ObjCPropertyRefExpr *pre
8708 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8709 ->IgnoreParens());
8710 if (!pre) return false;
8711 if (pre->isImplicitProperty()) return false;
8712 ObjCPropertyDecl *property = pre->getExplicitProperty();
8713 if (!property->isRetaining() &&
8714 !(property->getPropertyIvarDecl() &&
8715 property->getPropertyIvarDecl()->getType()
8716 .getObjCLifetime() == Qualifiers::OCL_Strong))
8717 return false;
8718
8719 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008720 if (pre->isSuperReceiver()) {
8721 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8722 if (!owner.Variable)
8723 return false;
8724 owner.Loc = pre->getLocation();
8725 owner.Range = pre->getSourceRange();
8726 return true;
8727 }
John McCallfe96e0b2011-11-06 09:01:30 +00008728 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8729 ->getSourceExpr());
8730 continue;
8731 }
8732
John McCall31168b02011-06-15 23:02:42 +00008733 // Array ivars?
8734
8735 return false;
8736 }
8737}
8738
8739namespace {
8740 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8741 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8742 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008743 Context(Context), Variable(variable), Capturer(nullptr),
8744 VarWillBeReased(false) {}
8745 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00008746 VarDecl *Variable;
8747 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008748 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00008749
8750 void VisitDeclRefExpr(DeclRefExpr *ref) {
8751 if (ref->getDecl() == Variable && !Capturer)
8752 Capturer = ref;
8753 }
8754
John McCall31168b02011-06-15 23:02:42 +00008755 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8756 if (Capturer) return;
8757 Visit(ref->getBase());
8758 if (Capturer && ref->isFreeIvar())
8759 Capturer = ref;
8760 }
8761
8762 void VisitBlockExpr(BlockExpr *block) {
8763 // Look inside nested blocks
8764 if (block->getBlockDecl()->capturesVariable(Variable))
8765 Visit(block->getBlockDecl()->getBody());
8766 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00008767
8768 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8769 if (Capturer) return;
8770 if (OVE->getSourceExpr())
8771 Visit(OVE->getSourceExpr());
8772 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008773 void VisitBinaryOperator(BinaryOperator *BinOp) {
8774 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8775 return;
8776 Expr *LHS = BinOp->getLHS();
8777 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8778 if (DRE->getDecl() != Variable)
8779 return;
8780 if (Expr *RHS = BinOp->getRHS()) {
8781 RHS = RHS->IgnoreParenCasts();
8782 llvm::APSInt Value;
8783 VarWillBeReased =
8784 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8785 }
8786 }
8787 }
John McCall31168b02011-06-15 23:02:42 +00008788 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008789}
John McCall31168b02011-06-15 23:02:42 +00008790
8791/// Check whether the given argument is a block which captures a
8792/// variable.
8793static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8794 assert(owner.Variable && owner.Loc.isValid());
8795
8796 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00008797
8798 // Look through [^{...} copy] and Block_copy(^{...}).
8799 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8800 Selector Cmd = ME->getSelector();
8801 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8802 e = ME->getInstanceReceiver();
8803 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00008804 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00008805 e = e->IgnoreParenCasts();
8806 }
8807 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8808 if (CE->getNumArgs() == 1) {
8809 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00008810 if (Fn) {
8811 const IdentifierInfo *FnI = Fn->getIdentifier();
8812 if (FnI && FnI->isStr("_Block_copy")) {
8813 e = CE->getArg(0)->IgnoreParenCasts();
8814 }
8815 }
Jordan Rose67e887c2012-09-17 17:54:30 +00008816 }
8817 }
8818
John McCall31168b02011-06-15 23:02:42 +00008819 BlockExpr *block = dyn_cast<BlockExpr>(e);
8820 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00008821 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00008822
8823 FindCaptureVisitor visitor(S.Context, owner.Variable);
8824 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008825 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00008826}
8827
8828static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8829 RetainCycleOwner &owner) {
8830 assert(capturer);
8831 assert(owner.Variable && owner.Loc.isValid());
8832
8833 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8834 << owner.Variable << capturer->getSourceRange();
8835 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8836 << owner.Indirect << owner.Range;
8837}
8838
8839/// Check for a keyword selector that starts with the word 'add' or
8840/// 'set'.
8841static bool isSetterLikeSelector(Selector sel) {
8842 if (sel.isUnarySelector()) return false;
8843
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008844 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00008845 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008846 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00008847 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008848 else if (str.startswith("add")) {
8849 // Specially whitelist 'addOperationWithBlock:'.
8850 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8851 return false;
8852 str = str.substr(3);
8853 }
John McCall31168b02011-06-15 23:02:42 +00008854 else
8855 return false;
8856
8857 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00008858 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00008859}
8860
Benjamin Kramer3a743452015-03-09 15:03:32 +00008861static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
8862 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00008863 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
8864 Message->getReceiverInterface(),
8865 NSAPI::ClassId_NSMutableArray);
8866 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008867 return None;
8868 }
8869
8870 Selector Sel = Message->getSelector();
8871
8872 Optional<NSAPI::NSArrayMethodKind> MKOpt =
8873 S.NSAPIObj->getNSArrayMethodKind(Sel);
8874 if (!MKOpt) {
8875 return None;
8876 }
8877
8878 NSAPI::NSArrayMethodKind MK = *MKOpt;
8879
8880 switch (MK) {
8881 case NSAPI::NSMutableArr_addObject:
8882 case NSAPI::NSMutableArr_insertObjectAtIndex:
8883 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
8884 return 0;
8885 case NSAPI::NSMutableArr_replaceObjectAtIndex:
8886 return 1;
8887
8888 default:
8889 return None;
8890 }
8891
8892 return None;
8893}
8894
8895static
8896Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
8897 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00008898 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
8899 Message->getReceiverInterface(),
8900 NSAPI::ClassId_NSMutableDictionary);
8901 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008902 return None;
8903 }
8904
8905 Selector Sel = Message->getSelector();
8906
8907 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
8908 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
8909 if (!MKOpt) {
8910 return None;
8911 }
8912
8913 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
8914
8915 switch (MK) {
8916 case NSAPI::NSMutableDict_setObjectForKey:
8917 case NSAPI::NSMutableDict_setValueForKey:
8918 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
8919 return 0;
8920
8921 default:
8922 return None;
8923 }
8924
8925 return None;
8926}
8927
8928static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00008929 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
8930 Message->getReceiverInterface(),
8931 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +00008932
Alex Denisov5dfac812015-08-06 04:51:14 +00008933 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
8934 Message->getReceiverInterface(),
8935 NSAPI::ClassId_NSMutableOrderedSet);
8936 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008937 return None;
8938 }
8939
8940 Selector Sel = Message->getSelector();
8941
8942 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
8943 if (!MKOpt) {
8944 return None;
8945 }
8946
8947 NSAPI::NSSetMethodKind MK = *MKOpt;
8948
8949 switch (MK) {
8950 case NSAPI::NSMutableSet_addObject:
8951 case NSAPI::NSOrderedSet_setObjectAtIndex:
8952 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
8953 case NSAPI::NSOrderedSet_insertObjectAtIndex:
8954 return 0;
8955 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
8956 return 1;
8957 }
8958
8959 return None;
8960}
8961
8962void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
8963 if (!Message->isInstanceMessage()) {
8964 return;
8965 }
8966
8967 Optional<int> ArgOpt;
8968
8969 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
8970 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
8971 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
8972 return;
8973 }
8974
8975 int ArgIndex = *ArgOpt;
8976
Alex Denisove1d882c2015-03-04 17:55:52 +00008977 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
8978 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
8979 Arg = OE->getSourceExpr()->IgnoreImpCasts();
8980 }
8981
Alex Denisov5dfac812015-08-06 04:51:14 +00008982 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008983 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +00008984 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008985 Diag(Message->getSourceRange().getBegin(),
8986 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +00008987 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +00008988 }
8989 }
Alex Denisov5dfac812015-08-06 04:51:14 +00008990 } else {
8991 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
8992
8993 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
8994 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
8995 }
8996
8997 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
8998 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
8999 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
9000 ValueDecl *Decl = ReceiverRE->getDecl();
9001 Diag(Message->getSourceRange().getBegin(),
9002 diag::warn_objc_circular_container)
9003 << Decl->getName() << Decl->getName();
9004 if (!ArgRE->isObjCSelfExpr()) {
9005 Diag(Decl->getLocation(),
9006 diag::note_objc_circular_container_declared_here)
9007 << Decl->getName();
9008 }
9009 }
9010 }
9011 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
9012 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
9013 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
9014 ObjCIvarDecl *Decl = IvarRE->getDecl();
9015 Diag(Message->getSourceRange().getBegin(),
9016 diag::warn_objc_circular_container)
9017 << Decl->getName() << Decl->getName();
9018 Diag(Decl->getLocation(),
9019 diag::note_objc_circular_container_declared_here)
9020 << Decl->getName();
9021 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009022 }
9023 }
9024 }
9025
9026}
9027
John McCall31168b02011-06-15 23:02:42 +00009028/// Check a message send to see if it's likely to cause a retain cycle.
9029void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
9030 // Only check instance methods whose selector looks like a setter.
9031 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
9032 return;
9033
9034 // Try to find a variable that the receiver is strongly owned by.
9035 RetainCycleOwner owner;
9036 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009037 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00009038 return;
9039 } else {
9040 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
9041 owner.Variable = getCurMethodDecl()->getSelfDecl();
9042 owner.Loc = msg->getSuperLoc();
9043 owner.Range = msg->getSuperLoc();
9044 }
9045
9046 // Check whether the receiver is captured by any of the arguments.
9047 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
9048 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
9049 return diagnoseRetainCycle(*this, capturer, owner);
9050}
9051
9052/// Check a property assign to see if it's likely to cause a retain cycle.
9053void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
9054 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009055 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00009056 return;
9057
9058 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
9059 diagnoseRetainCycle(*this, capturer, owner);
9060}
9061
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009062void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
9063 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00009064 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009065 return;
9066
9067 // Because we don't have an expression for the variable, we have to set the
9068 // location explicitly here.
9069 Owner.Loc = Var->getLocation();
9070 Owner.Range = Var->getSourceRange();
9071
9072 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
9073 diagnoseRetainCycle(*this, Capturer, Owner);
9074}
9075
Ted Kremenek9304da92012-12-21 08:04:28 +00009076static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
9077 Expr *RHS, bool isProperty) {
9078 // Check if RHS is an Objective-C object literal, which also can get
9079 // immediately zapped in a weak reference. Note that we explicitly
9080 // allow ObjCStringLiterals, since those are designed to never really die.
9081 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009082
Ted Kremenek64873352012-12-21 22:46:35 +00009083 // This enum needs to match with the 'select' in
9084 // warn_objc_arc_literal_assign (off-by-1).
9085 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
9086 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
9087 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009088
9089 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00009090 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00009091 << (isProperty ? 0 : 1)
9092 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009093
9094 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00009095}
9096
Ted Kremenekc1f014a2012-12-21 19:45:30 +00009097static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
9098 Qualifiers::ObjCLifetime LT,
9099 Expr *RHS, bool isProperty) {
9100 // Strip off any implicit cast added to get to the one ARC-specific.
9101 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9102 if (cast->getCastKind() == CK_ARCConsumeObject) {
9103 S.Diag(Loc, diag::warn_arc_retained_assign)
9104 << (LT == Qualifiers::OCL_ExplicitNone)
9105 << (isProperty ? 0 : 1)
9106 << RHS->getSourceRange();
9107 return true;
9108 }
9109 RHS = cast->getSubExpr();
9110 }
9111
9112 if (LT == Qualifiers::OCL_Weak &&
9113 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
9114 return true;
9115
9116 return false;
9117}
9118
Ted Kremenekb36234d2012-12-21 08:04:20 +00009119bool Sema::checkUnsafeAssigns(SourceLocation Loc,
9120 QualType LHS, Expr *RHS) {
9121 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
9122
9123 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
9124 return false;
9125
9126 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
9127 return true;
9128
9129 return false;
9130}
9131
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009132void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
9133 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009134 QualType LHSType;
9135 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00009136 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009137 ObjCPropertyRefExpr *PRE
9138 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
9139 if (PRE && !PRE->isImplicitProperty()) {
9140 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9141 if (PD)
9142 LHSType = PD->getType();
9143 }
9144
9145 if (LHSType.isNull())
9146 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00009147
9148 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
9149
9150 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009151 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00009152 getCurFunction()->markSafeWeakUse(LHS);
9153 }
9154
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009155 if (checkUnsafeAssigns(Loc, LHSType, RHS))
9156 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00009157
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009158 // FIXME. Check for other life times.
9159 if (LT != Qualifiers::OCL_None)
9160 return;
9161
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009162 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009163 if (PRE->isImplicitProperty())
9164 return;
9165 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9166 if (!PD)
9167 return;
9168
Bill Wendling44426052012-12-20 19:22:21 +00009169 unsigned Attributes = PD->getPropertyAttributes();
9170 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009171 // when 'assign' attribute was not explicitly specified
9172 // by user, ignore it and rely on property type itself
9173 // for lifetime info.
9174 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
9175 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
9176 LHSType->isObjCRetainableType())
9177 return;
9178
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009179 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00009180 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009181 Diag(Loc, diag::warn_arc_retained_property_assign)
9182 << RHS->getSourceRange();
9183 return;
9184 }
9185 RHS = cast->getSubExpr();
9186 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009187 }
Bill Wendling44426052012-12-20 19:22:21 +00009188 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00009189 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
9190 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00009191 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009192 }
9193}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009194
9195//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
9196
9197namespace {
9198bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
9199 SourceLocation StmtLoc,
9200 const NullStmt *Body) {
9201 // Do not warn if the body is a macro that expands to nothing, e.g:
9202 //
9203 // #define CALL(x)
9204 // if (condition)
9205 // CALL(0);
9206 //
9207 if (Body->hasLeadingEmptyMacro())
9208 return false;
9209
9210 // Get line numbers of statement and body.
9211 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +00009212 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009213 &StmtLineInvalid);
9214 if (StmtLineInvalid)
9215 return false;
9216
9217 bool BodyLineInvalid;
9218 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
9219 &BodyLineInvalid);
9220 if (BodyLineInvalid)
9221 return false;
9222
9223 // Warn if null statement and body are on the same line.
9224 if (StmtLine != BodyLine)
9225 return false;
9226
9227 return true;
9228}
9229} // Unnamed namespace
9230
9231void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
9232 const Stmt *Body,
9233 unsigned DiagID) {
9234 // Since this is a syntactic check, don't emit diagnostic for template
9235 // instantiations, this just adds noise.
9236 if (CurrentInstantiationScope)
9237 return;
9238
9239 // The body should be a null statement.
9240 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9241 if (!NBody)
9242 return;
9243
9244 // Do the usual checks.
9245 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9246 return;
9247
9248 Diag(NBody->getSemiLoc(), DiagID);
9249 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9250}
9251
9252void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
9253 const Stmt *PossibleBody) {
9254 assert(!CurrentInstantiationScope); // Ensured by caller
9255
9256 SourceLocation StmtLoc;
9257 const Stmt *Body;
9258 unsigned DiagID;
9259 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
9260 StmtLoc = FS->getRParenLoc();
9261 Body = FS->getBody();
9262 DiagID = diag::warn_empty_for_body;
9263 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
9264 StmtLoc = WS->getCond()->getSourceRange().getEnd();
9265 Body = WS->getBody();
9266 DiagID = diag::warn_empty_while_body;
9267 } else
9268 return; // Neither `for' nor `while'.
9269
9270 // The body should be a null statement.
9271 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9272 if (!NBody)
9273 return;
9274
9275 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009276 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009277 return;
9278
9279 // Do the usual checks.
9280 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9281 return;
9282
9283 // `for(...);' and `while(...);' are popular idioms, so in order to keep
9284 // noise level low, emit diagnostics only if for/while is followed by a
9285 // CompoundStmt, e.g.:
9286 // for (int i = 0; i < n; i++);
9287 // {
9288 // a(i);
9289 // }
9290 // or if for/while is followed by a statement with more indentation
9291 // than for/while itself:
9292 // for (int i = 0; i < n; i++);
9293 // a(i);
9294 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
9295 if (!ProbableTypo) {
9296 bool BodyColInvalid;
9297 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
9298 PossibleBody->getLocStart(),
9299 &BodyColInvalid);
9300 if (BodyColInvalid)
9301 return;
9302
9303 bool StmtColInvalid;
9304 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
9305 S->getLocStart(),
9306 &StmtColInvalid);
9307 if (StmtColInvalid)
9308 return;
9309
9310 if (BodyCol > StmtCol)
9311 ProbableTypo = true;
9312 }
9313
9314 if (ProbableTypo) {
9315 Diag(NBody->getSemiLoc(), DiagID);
9316 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9317 }
9318}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009319
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009320//===--- CHECK: Warn on self move with std::move. -------------------------===//
9321
9322/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
9323void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
9324 SourceLocation OpLoc) {
9325
9326 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
9327 return;
9328
9329 if (!ActiveTemplateInstantiations.empty())
9330 return;
9331
9332 // Strip parens and casts away.
9333 LHSExpr = LHSExpr->IgnoreParenImpCasts();
9334 RHSExpr = RHSExpr->IgnoreParenImpCasts();
9335
9336 // Check for a call expression
9337 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
9338 if (!CE || CE->getNumArgs() != 1)
9339 return;
9340
9341 // Check for a call to std::move
9342 const FunctionDecl *FD = CE->getDirectCallee();
9343 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
9344 !FD->getIdentifier()->isStr("move"))
9345 return;
9346
9347 // Get argument from std::move
9348 RHSExpr = CE->getArg(0);
9349
9350 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9351 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9352
9353 // Two DeclRefExpr's, check that the decls are the same.
9354 if (LHSDeclRef && RHSDeclRef) {
9355 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9356 return;
9357 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9358 RHSDeclRef->getDecl()->getCanonicalDecl())
9359 return;
9360
9361 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9362 << LHSExpr->getSourceRange()
9363 << RHSExpr->getSourceRange();
9364 return;
9365 }
9366
9367 // Member variables require a different approach to check for self moves.
9368 // MemberExpr's are the same if every nested MemberExpr refers to the same
9369 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
9370 // the base Expr's are CXXThisExpr's.
9371 const Expr *LHSBase = LHSExpr;
9372 const Expr *RHSBase = RHSExpr;
9373 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
9374 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
9375 if (!LHSME || !RHSME)
9376 return;
9377
9378 while (LHSME && RHSME) {
9379 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
9380 RHSME->getMemberDecl()->getCanonicalDecl())
9381 return;
9382
9383 LHSBase = LHSME->getBase();
9384 RHSBase = RHSME->getBase();
9385 LHSME = dyn_cast<MemberExpr>(LHSBase);
9386 RHSME = dyn_cast<MemberExpr>(RHSBase);
9387 }
9388
9389 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
9390 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
9391 if (LHSDeclRef && RHSDeclRef) {
9392 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9393 return;
9394 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9395 RHSDeclRef->getDecl()->getCanonicalDecl())
9396 return;
9397
9398 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9399 << LHSExpr->getSourceRange()
9400 << RHSExpr->getSourceRange();
9401 return;
9402 }
9403
9404 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
9405 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9406 << LHSExpr->getSourceRange()
9407 << RHSExpr->getSourceRange();
9408}
9409
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009410//===--- Layout compatibility ----------------------------------------------//
9411
9412namespace {
9413
9414bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
9415
9416/// \brief Check if two enumeration types are layout-compatible.
9417bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
9418 // C++11 [dcl.enum] p8:
9419 // Two enumeration types are layout-compatible if they have the same
9420 // underlying type.
9421 return ED1->isComplete() && ED2->isComplete() &&
9422 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
9423}
9424
9425/// \brief Check if two fields are layout-compatible.
9426bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
9427 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
9428 return false;
9429
9430 if (Field1->isBitField() != Field2->isBitField())
9431 return false;
9432
9433 if (Field1->isBitField()) {
9434 // Make sure that the bit-fields are the same length.
9435 unsigned Bits1 = Field1->getBitWidthValue(C);
9436 unsigned Bits2 = Field2->getBitWidthValue(C);
9437
9438 if (Bits1 != Bits2)
9439 return false;
9440 }
9441
9442 return true;
9443}
9444
9445/// \brief Check if two standard-layout structs are layout-compatible.
9446/// (C++11 [class.mem] p17)
9447bool isLayoutCompatibleStruct(ASTContext &C,
9448 RecordDecl *RD1,
9449 RecordDecl *RD2) {
9450 // If both records are C++ classes, check that base classes match.
9451 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
9452 // If one of records is a CXXRecordDecl we are in C++ mode,
9453 // thus the other one is a CXXRecordDecl, too.
9454 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
9455 // Check number of base classes.
9456 if (D1CXX->getNumBases() != D2CXX->getNumBases())
9457 return false;
9458
9459 // Check the base classes.
9460 for (CXXRecordDecl::base_class_const_iterator
9461 Base1 = D1CXX->bases_begin(),
9462 BaseEnd1 = D1CXX->bases_end(),
9463 Base2 = D2CXX->bases_begin();
9464 Base1 != BaseEnd1;
9465 ++Base1, ++Base2) {
9466 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
9467 return false;
9468 }
9469 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
9470 // If only RD2 is a C++ class, it should have zero base classes.
9471 if (D2CXX->getNumBases() > 0)
9472 return false;
9473 }
9474
9475 // Check the fields.
9476 RecordDecl::field_iterator Field2 = RD2->field_begin(),
9477 Field2End = RD2->field_end(),
9478 Field1 = RD1->field_begin(),
9479 Field1End = RD1->field_end();
9480 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
9481 if (!isLayoutCompatible(C, *Field1, *Field2))
9482 return false;
9483 }
9484 if (Field1 != Field1End || Field2 != Field2End)
9485 return false;
9486
9487 return true;
9488}
9489
9490/// \brief Check if two standard-layout unions are layout-compatible.
9491/// (C++11 [class.mem] p18)
9492bool isLayoutCompatibleUnion(ASTContext &C,
9493 RecordDecl *RD1,
9494 RecordDecl *RD2) {
9495 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009496 for (auto *Field2 : RD2->fields())
9497 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009498
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009499 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009500 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
9501 I = UnmatchedFields.begin(),
9502 E = UnmatchedFields.end();
9503
9504 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009505 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009506 bool Result = UnmatchedFields.erase(*I);
9507 (void) Result;
9508 assert(Result);
9509 break;
9510 }
9511 }
9512 if (I == E)
9513 return false;
9514 }
9515
9516 return UnmatchedFields.empty();
9517}
9518
9519bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
9520 if (RD1->isUnion() != RD2->isUnion())
9521 return false;
9522
9523 if (RD1->isUnion())
9524 return isLayoutCompatibleUnion(C, RD1, RD2);
9525 else
9526 return isLayoutCompatibleStruct(C, RD1, RD2);
9527}
9528
9529/// \brief Check if two types are layout-compatible in C++11 sense.
9530bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
9531 if (T1.isNull() || T2.isNull())
9532 return false;
9533
9534 // C++11 [basic.types] p11:
9535 // If two types T1 and T2 are the same type, then T1 and T2 are
9536 // layout-compatible types.
9537 if (C.hasSameType(T1, T2))
9538 return true;
9539
9540 T1 = T1.getCanonicalType().getUnqualifiedType();
9541 T2 = T2.getCanonicalType().getUnqualifiedType();
9542
9543 const Type::TypeClass TC1 = T1->getTypeClass();
9544 const Type::TypeClass TC2 = T2->getTypeClass();
9545
9546 if (TC1 != TC2)
9547 return false;
9548
9549 if (TC1 == Type::Enum) {
9550 return isLayoutCompatible(C,
9551 cast<EnumType>(T1)->getDecl(),
9552 cast<EnumType>(T2)->getDecl());
9553 } else if (TC1 == Type::Record) {
9554 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
9555 return false;
9556
9557 return isLayoutCompatible(C,
9558 cast<RecordType>(T1)->getDecl(),
9559 cast<RecordType>(T2)->getDecl());
9560 }
9561
9562 return false;
9563}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009564}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009565
9566//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
9567
9568namespace {
9569/// \brief Given a type tag expression find the type tag itself.
9570///
9571/// \param TypeExpr Type tag expression, as it appears in user's code.
9572///
9573/// \param VD Declaration of an identifier that appears in a type tag.
9574///
9575/// \param MagicValue Type tag magic value.
9576bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
9577 const ValueDecl **VD, uint64_t *MagicValue) {
9578 while(true) {
9579 if (!TypeExpr)
9580 return false;
9581
9582 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
9583
9584 switch (TypeExpr->getStmtClass()) {
9585 case Stmt::UnaryOperatorClass: {
9586 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
9587 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
9588 TypeExpr = UO->getSubExpr();
9589 continue;
9590 }
9591 return false;
9592 }
9593
9594 case Stmt::DeclRefExprClass: {
9595 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
9596 *VD = DRE->getDecl();
9597 return true;
9598 }
9599
9600 case Stmt::IntegerLiteralClass: {
9601 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
9602 llvm::APInt MagicValueAPInt = IL->getValue();
9603 if (MagicValueAPInt.getActiveBits() <= 64) {
9604 *MagicValue = MagicValueAPInt.getZExtValue();
9605 return true;
9606 } else
9607 return false;
9608 }
9609
9610 case Stmt::BinaryConditionalOperatorClass:
9611 case Stmt::ConditionalOperatorClass: {
9612 const AbstractConditionalOperator *ACO =
9613 cast<AbstractConditionalOperator>(TypeExpr);
9614 bool Result;
9615 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
9616 if (Result)
9617 TypeExpr = ACO->getTrueExpr();
9618 else
9619 TypeExpr = ACO->getFalseExpr();
9620 continue;
9621 }
9622 return false;
9623 }
9624
9625 case Stmt::BinaryOperatorClass: {
9626 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
9627 if (BO->getOpcode() == BO_Comma) {
9628 TypeExpr = BO->getRHS();
9629 continue;
9630 }
9631 return false;
9632 }
9633
9634 default:
9635 return false;
9636 }
9637 }
9638}
9639
9640/// \brief Retrieve the C type corresponding to type tag TypeExpr.
9641///
9642/// \param TypeExpr Expression that specifies a type tag.
9643///
9644/// \param MagicValues Registered magic values.
9645///
9646/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
9647/// kind.
9648///
9649/// \param TypeInfo Information about the corresponding C type.
9650///
9651/// \returns true if the corresponding C type was found.
9652bool GetMatchingCType(
9653 const IdentifierInfo *ArgumentKind,
9654 const Expr *TypeExpr, const ASTContext &Ctx,
9655 const llvm::DenseMap<Sema::TypeTagMagicValue,
9656 Sema::TypeTagData> *MagicValues,
9657 bool &FoundWrongKind,
9658 Sema::TypeTagData &TypeInfo) {
9659 FoundWrongKind = false;
9660
9661 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00009662 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009663
9664 uint64_t MagicValue;
9665
9666 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
9667 return false;
9668
9669 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00009670 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009671 if (I->getArgumentKind() != ArgumentKind) {
9672 FoundWrongKind = true;
9673 return false;
9674 }
9675 TypeInfo.Type = I->getMatchingCType();
9676 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
9677 TypeInfo.MustBeNull = I->getMustBeNull();
9678 return true;
9679 }
9680 return false;
9681 }
9682
9683 if (!MagicValues)
9684 return false;
9685
9686 llvm::DenseMap<Sema::TypeTagMagicValue,
9687 Sema::TypeTagData>::const_iterator I =
9688 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
9689 if (I == MagicValues->end())
9690 return false;
9691
9692 TypeInfo = I->second;
9693 return true;
9694}
9695} // unnamed namespace
9696
9697void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9698 uint64_t MagicValue, QualType Type,
9699 bool LayoutCompatible,
9700 bool MustBeNull) {
9701 if (!TypeTagForDatatypeMagicValues)
9702 TypeTagForDatatypeMagicValues.reset(
9703 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
9704
9705 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
9706 (*TypeTagForDatatypeMagicValues)[Magic] =
9707 TypeTagData(Type, LayoutCompatible, MustBeNull);
9708}
9709
9710namespace {
9711bool IsSameCharType(QualType T1, QualType T2) {
9712 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
9713 if (!BT1)
9714 return false;
9715
9716 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
9717 if (!BT2)
9718 return false;
9719
9720 BuiltinType::Kind T1Kind = BT1->getKind();
9721 BuiltinType::Kind T2Kind = BT2->getKind();
9722
9723 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
9724 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
9725 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
9726 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
9727}
9728} // unnamed namespace
9729
9730void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9731 const Expr * const *ExprArgs) {
9732 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
9733 bool IsPointerAttr = Attr->getIsPointer();
9734
9735 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
9736 bool FoundWrongKind;
9737 TypeTagData TypeInfo;
9738 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
9739 TypeTagForDatatypeMagicValues.get(),
9740 FoundWrongKind, TypeInfo)) {
9741 if (FoundWrongKind)
9742 Diag(TypeTagExpr->getExprLoc(),
9743 diag::warn_type_tag_for_datatype_wrong_kind)
9744 << TypeTagExpr->getSourceRange();
9745 return;
9746 }
9747
9748 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
9749 if (IsPointerAttr) {
9750 // Skip implicit cast of pointer to `void *' (as a function argument).
9751 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00009752 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00009753 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009754 ArgumentExpr = ICE->getSubExpr();
9755 }
9756 QualType ArgumentType = ArgumentExpr->getType();
9757
9758 // Passing a `void*' pointer shouldn't trigger a warning.
9759 if (IsPointerAttr && ArgumentType->isVoidPointerType())
9760 return;
9761
9762 if (TypeInfo.MustBeNull) {
9763 // Type tag with matching void type requires a null pointer.
9764 if (!ArgumentExpr->isNullPointerConstant(Context,
9765 Expr::NPC_ValueDependentIsNotNull)) {
9766 Diag(ArgumentExpr->getExprLoc(),
9767 diag::warn_type_safety_null_pointer_required)
9768 << ArgumentKind->getName()
9769 << ArgumentExpr->getSourceRange()
9770 << TypeTagExpr->getSourceRange();
9771 }
9772 return;
9773 }
9774
9775 QualType RequiredType = TypeInfo.Type;
9776 if (IsPointerAttr)
9777 RequiredType = Context.getPointerType(RequiredType);
9778
9779 bool mismatch = false;
9780 if (!TypeInfo.LayoutCompatible) {
9781 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
9782
9783 // C++11 [basic.fundamental] p1:
9784 // Plain char, signed char, and unsigned char are three distinct types.
9785 //
9786 // But we treat plain `char' as equivalent to `signed char' or `unsigned
9787 // char' depending on the current char signedness mode.
9788 if (mismatch)
9789 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
9790 RequiredType->getPointeeType())) ||
9791 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
9792 mismatch = false;
9793 } else
9794 if (IsPointerAttr)
9795 mismatch = !isLayoutCompatible(Context,
9796 ArgumentType->getPointeeType(),
9797 RequiredType->getPointeeType());
9798 else
9799 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
9800
9801 if (mismatch)
9802 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00009803 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009804 << TypeInfo.LayoutCompatible << RequiredType
9805 << ArgumentExpr->getSourceRange()
9806 << TypeTagExpr->getSourceRange();
9807}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009808