blob: c6a00b1dad14cf6a3f60fd9985428b01eb658e16 [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);
Craig Topperdd84ec52014-12-27 07:00:08 +00001040 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
Craig Topper16015252015-01-31 06:31:23 +00001041 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001042 case X86::BI__builtin_ia32_vpermil2pd:
1043 case X86::BI__builtin_ia32_vpermil2pd256:
1044 case X86::BI__builtin_ia32_vpermil2ps:
1045 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
Craig Topper95b0d732015-01-25 23:30:05 +00001046 case X86::BI__builtin_ia32_cmpb128_mask:
1047 case X86::BI__builtin_ia32_cmpw128_mask:
1048 case X86::BI__builtin_ia32_cmpd128_mask:
1049 case X86::BI__builtin_ia32_cmpq128_mask:
1050 case X86::BI__builtin_ia32_cmpb256_mask:
1051 case X86::BI__builtin_ia32_cmpw256_mask:
1052 case X86::BI__builtin_ia32_cmpd256_mask:
1053 case X86::BI__builtin_ia32_cmpq256_mask:
1054 case X86::BI__builtin_ia32_cmpb512_mask:
1055 case X86::BI__builtin_ia32_cmpw512_mask:
1056 case X86::BI__builtin_ia32_cmpd512_mask:
1057 case X86::BI__builtin_ia32_cmpq512_mask:
1058 case X86::BI__builtin_ia32_ucmpb128_mask:
1059 case X86::BI__builtin_ia32_ucmpw128_mask:
1060 case X86::BI__builtin_ia32_ucmpd128_mask:
1061 case X86::BI__builtin_ia32_ucmpq128_mask:
1062 case X86::BI__builtin_ia32_ucmpb256_mask:
1063 case X86::BI__builtin_ia32_ucmpw256_mask:
1064 case X86::BI__builtin_ia32_ucmpd256_mask:
1065 case X86::BI__builtin_ia32_ucmpq256_mask:
1066 case X86::BI__builtin_ia32_ucmpb512_mask:
1067 case X86::BI__builtin_ia32_ucmpw512_mask:
1068 case X86::BI__builtin_ia32_ucmpd512_mask:
1069 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
Craig Topper16015252015-01-31 06:31:23 +00001070 case X86::BI__builtin_ia32_roundps:
1071 case X86::BI__builtin_ia32_roundpd:
1072 case X86::BI__builtin_ia32_roundps256:
1073 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
1074 case X86::BI__builtin_ia32_roundss:
1075 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
1076 case X86::BI__builtin_ia32_cmpps:
1077 case X86::BI__builtin_ia32_cmpss:
1078 case X86::BI__builtin_ia32_cmppd:
1079 case X86::BI__builtin_ia32_cmpsd:
1080 case X86::BI__builtin_ia32_cmpps256:
1081 case X86::BI__builtin_ia32_cmppd256:
1082 case X86::BI__builtin_ia32_cmpps512_mask:
1083 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001084 case X86::BI__builtin_ia32_vpcomub:
1085 case X86::BI__builtin_ia32_vpcomuw:
1086 case X86::BI__builtin_ia32_vpcomud:
1087 case X86::BI__builtin_ia32_vpcomuq:
1088 case X86::BI__builtin_ia32_vpcomb:
1089 case X86::BI__builtin_ia32_vpcomw:
1090 case X86::BI__builtin_ia32_vpcomd:
1091 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001092 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001093 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001094}
1095
Richard Smith55ce3522012-06-25 20:30:08 +00001096/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1097/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1098/// Returns true when the format fits the function and the FormatStringInfo has
1099/// been populated.
1100bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1101 FormatStringInfo *FSI) {
1102 FSI->HasVAListArg = Format->getFirstArg() == 0;
1103 FSI->FormatIdx = Format->getFormatIdx() - 1;
1104 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001105
Richard Smith55ce3522012-06-25 20:30:08 +00001106 // The way the format attribute works in GCC, the implicit this argument
1107 // of member functions is counted. However, it doesn't appear in our own
1108 // lists, so decrement format_idx in that case.
1109 if (IsCXXMember) {
1110 if(FSI->FormatIdx == 0)
1111 return false;
1112 --FSI->FormatIdx;
1113 if (FSI->FirstDataArg != 0)
1114 --FSI->FirstDataArg;
1115 }
1116 return true;
1117}
Mike Stump11289f42009-09-09 15:08:12 +00001118
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001119/// Checks if a the given expression evaluates to null.
1120///
1121/// \brief Returns true if the value evaluates to null.
1122static bool CheckNonNullExpr(Sema &S,
1123 const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001124 // If the expression has non-null type, it doesn't evaluate to null.
1125 if (auto nullability
1126 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1127 if (*nullability == NullabilityKind::NonNull)
1128 return false;
1129 }
1130
Ted Kremeneka146db32014-01-17 06:24:47 +00001131 // As a special case, transparent unions initialized with zero are
1132 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001133 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001134 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1135 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001136 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001137 if (const InitListExpr *ILE =
1138 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001139 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001140 }
1141
1142 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001143 return (!Expr->isValueDependent() &&
1144 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1145 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001146}
1147
1148static void CheckNonNullArgument(Sema &S,
1149 const Expr *ArgExpr,
1150 SourceLocation CallSiteLoc) {
1151 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001152 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
1153}
1154
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001155bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1156 FormatStringInfo FSI;
1157 if ((GetFormatStringType(Format) == FST_NSString) &&
1158 getFormatStringInfo(Format, false, &FSI)) {
1159 Idx = FSI.FormatIdx;
1160 return true;
1161 }
1162 return false;
1163}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001164/// \brief Diagnose use of %s directive in an NSString which is being passed
1165/// as formatting string to formatting method.
1166static void
1167DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1168 const NamedDecl *FDecl,
1169 Expr **Args,
1170 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001171 unsigned Idx = 0;
1172 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001173 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1174 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001175 Idx = 2;
1176 Format = true;
1177 }
1178 else
1179 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1180 if (S.GetFormatNSStringIdx(I, Idx)) {
1181 Format = true;
1182 break;
1183 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001184 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001185 if (!Format || NumArgs <= Idx)
1186 return;
1187 const Expr *FormatExpr = Args[Idx];
1188 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1189 FormatExpr = CSCE->getSubExpr();
1190 const StringLiteral *FormatString;
1191 if (const ObjCStringLiteral *OSL =
1192 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1193 FormatString = OSL->getString();
1194 else
1195 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1196 if (!FormatString)
1197 return;
1198 if (S.FormatStringHasSArg(FormatString)) {
1199 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1200 << "%s" << 1 << 1;
1201 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1202 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001203 }
1204}
1205
Douglas Gregorb4866e82015-06-19 18:13:19 +00001206/// Determine whether the given type has a non-null nullability annotation.
1207static bool isNonNullType(ASTContext &ctx, QualType type) {
1208 if (auto nullability = type->getNullability(ctx))
1209 return *nullability == NullabilityKind::NonNull;
1210
1211 return false;
1212}
1213
Ted Kremenek2bc73332014-01-17 06:24:43 +00001214static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001215 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00001216 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00001217 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001218 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001219 assert((FDecl || Proto) && "Need a function declaration or prototype");
1220
Ted Kremenek9aedc152014-01-17 06:24:56 +00001221 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001222 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001223 if (FDecl) {
1224 // Handle the nonnull attribute on the function/method declaration itself.
1225 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1226 if (!NonNull->args_size()) {
1227 // Easy case: all pointer arguments are nonnull.
1228 for (const auto *Arg : Args)
1229 if (S.isValidPointerAttrType(Arg->getType()))
1230 CheckNonNullArgument(S, Arg, CallSiteLoc);
1231 return;
1232 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001233
Douglas Gregorb4866e82015-06-19 18:13:19 +00001234 for (unsigned Val : NonNull->args()) {
1235 if (Val >= Args.size())
1236 continue;
1237 if (NonNullArgs.empty())
1238 NonNullArgs.resize(Args.size());
1239 NonNullArgs.set(Val);
1240 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001241 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001242 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001243
Douglas Gregorb4866e82015-06-19 18:13:19 +00001244 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1245 // Handle the nonnull attribute on the parameters of the
1246 // function/method.
1247 ArrayRef<ParmVarDecl*> parms;
1248 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1249 parms = FD->parameters();
1250 else
1251 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1252
1253 unsigned ParamIndex = 0;
1254 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1255 I != E; ++I, ++ParamIndex) {
1256 const ParmVarDecl *PVD = *I;
1257 if (PVD->hasAttr<NonNullAttr>() ||
1258 isNonNullType(S.Context, PVD->getType())) {
1259 if (NonNullArgs.empty())
1260 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00001261
Douglas Gregorb4866e82015-06-19 18:13:19 +00001262 NonNullArgs.set(ParamIndex);
1263 }
1264 }
1265 } else {
1266 // If we have a non-function, non-method declaration but no
1267 // function prototype, try to dig out the function prototype.
1268 if (!Proto) {
1269 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1270 QualType type = VD->getType().getNonReferenceType();
1271 if (auto pointerType = type->getAs<PointerType>())
1272 type = pointerType->getPointeeType();
1273 else if (auto blockType = type->getAs<BlockPointerType>())
1274 type = blockType->getPointeeType();
1275 // FIXME: data member pointers?
1276
1277 // Dig out the function prototype, if there is one.
1278 Proto = type->getAs<FunctionProtoType>();
1279 }
1280 }
1281
1282 // Fill in non-null argument information from the nullability
1283 // information on the parameter types (if we have them).
1284 if (Proto) {
1285 unsigned Index = 0;
1286 for (auto paramType : Proto->getParamTypes()) {
1287 if (isNonNullType(S.Context, paramType)) {
1288 if (NonNullArgs.empty())
1289 NonNullArgs.resize(Args.size());
1290
1291 NonNullArgs.set(Index);
1292 }
1293
1294 ++Index;
1295 }
1296 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001297 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001298
Douglas Gregorb4866e82015-06-19 18:13:19 +00001299 // Check for non-null arguments.
1300 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1301 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001302 if (NonNullArgs[ArgIndex])
1303 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00001304 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001305}
1306
Richard Smith55ce3522012-06-25 20:30:08 +00001307/// Handles the checks for format strings, non-POD arguments to vararg
1308/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001309void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1310 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00001311 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001312 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001313 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001314 if (CurContext->isDependentContext())
1315 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001316
Ted Kremenekb8176da2010-09-09 04:33:05 +00001317 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001318 llvm::SmallBitVector CheckedVarArgs;
1319 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001320 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001321 // Only create vector if there are format attributes.
1322 CheckedVarArgs.resize(Args.size());
1323
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001324 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001325 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001326 }
Richard Smithd7293d72013-08-05 18:49:43 +00001327 }
Richard Smith55ce3522012-06-25 20:30:08 +00001328
1329 // Refuse POD arguments that weren't caught by the format string
1330 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001331 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001332 unsigned NumParams = Proto ? Proto->getNumParams()
1333 : FDecl && isa<FunctionDecl>(FDecl)
1334 ? cast<FunctionDecl>(FDecl)->getNumParams()
1335 : FDecl && isa<ObjCMethodDecl>(FDecl)
1336 ? cast<ObjCMethodDecl>(FDecl)->param_size()
1337 : 0;
1338
Alp Toker9cacbab2014-01-20 20:26:09 +00001339 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001340 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001341 if (const Expr *Arg = Args[ArgIdx]) {
1342 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1343 checkVariadicArgument(Arg, CallType);
1344 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001345 }
Richard Smithd7293d72013-08-05 18:49:43 +00001346 }
Mike Stump11289f42009-09-09 15:08:12 +00001347
Douglas Gregorb4866e82015-06-19 18:13:19 +00001348 if (FDecl || Proto) {
1349 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001350
Richard Trieu41bc0992013-06-22 00:20:41 +00001351 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001352 if (FDecl) {
1353 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1354 CheckArgumentWithTypeTag(I, Args.data());
1355 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001356 }
Richard Smith55ce3522012-06-25 20:30:08 +00001357}
1358
1359/// CheckConstructorCall - Check a constructor call for correctness and safety
1360/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001361void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1362 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001363 const FunctionProtoType *Proto,
1364 SourceLocation Loc) {
1365 VariadicCallType CallType =
1366 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001367 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1368 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00001369}
1370
1371/// CheckFunctionCall - Check a direct function call for various correctness
1372/// and safety properties not strictly enforced by the C type system.
1373bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1374 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001375 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1376 isa<CXXMethodDecl>(FDecl);
1377 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1378 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001379 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1380 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00001381 Expr** Args = TheCall->getArgs();
1382 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001383 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001384 // If this is a call to a member operator, hide the first argument
1385 // from checkCall.
1386 // FIXME: Our choice of AST representation here is less than ideal.
1387 ++Args;
1388 --NumArgs;
1389 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00001390 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00001391 IsMemberFunction, TheCall->getRParenLoc(),
1392 TheCall->getCallee()->getSourceRange(), CallType);
1393
1394 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1395 // None of the checks below are needed for functions that don't have
1396 // simple names (e.g., C++ conversion functions).
1397 if (!FnInfo)
1398 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001399
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001400 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001401 if (getLangOpts().ObjC1)
1402 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001403
Anna Zaks22122702012-01-17 00:37:07 +00001404 unsigned CMId = FDecl->getMemoryFunctionKind();
1405 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001406 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001407
Anna Zaks201d4892012-01-13 21:52:01 +00001408 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001409 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001410 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001411 else if (CMId == Builtin::BIstrncat)
1412 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001413 else
Anna Zaks22122702012-01-17 00:37:07 +00001414 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001415
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001416 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001417}
1418
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001419bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001420 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001421 VariadicCallType CallType =
1422 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001423
Douglas Gregorb4866e82015-06-19 18:13:19 +00001424 checkCall(Method, nullptr, Args,
1425 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1426 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001427
1428 return false;
1429}
1430
Richard Trieu664c4c62013-06-20 21:03:13 +00001431bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1432 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00001433 QualType Ty;
1434 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001435 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001436 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001437 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001438 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001439 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001440
Douglas Gregorb4866e82015-06-19 18:13:19 +00001441 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
1442 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001443 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001444
Richard Trieu664c4c62013-06-20 21:03:13 +00001445 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001446 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001447 CallType = VariadicDoesNotApply;
1448 } else if (Ty->isBlockPointerType()) {
1449 CallType = VariadicBlock;
1450 } else { // Ty->isFunctionPointerType()
1451 CallType = VariadicFunction;
1452 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001453
Douglas Gregorb4866e82015-06-19 18:13:19 +00001454 checkCall(NDecl, Proto,
1455 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1456 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001457 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001458
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001459 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001460}
1461
Richard Trieu41bc0992013-06-22 00:20:41 +00001462/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1463/// such as function pointers returned from functions.
1464bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001465 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001466 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00001467 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001468 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00001469 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001470 TheCall->getCallee()->getSourceRange(), CallType);
1471
1472 return false;
1473}
1474
Tim Northovere94a34c2014-03-11 10:49:14 +00001475static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1476 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1477 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1478 return false;
1479
1480 switch (Op) {
1481 case AtomicExpr::AO__c11_atomic_init:
1482 llvm_unreachable("There is no ordering argument for an init");
1483
1484 case AtomicExpr::AO__c11_atomic_load:
1485 case AtomicExpr::AO__atomic_load_n:
1486 case AtomicExpr::AO__atomic_load:
1487 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1488 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1489
1490 case AtomicExpr::AO__c11_atomic_store:
1491 case AtomicExpr::AO__atomic_store:
1492 case AtomicExpr::AO__atomic_store_n:
1493 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1494 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1495 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1496
1497 default:
1498 return true;
1499 }
1500}
1501
Richard Smithfeea8832012-04-12 05:08:17 +00001502ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1503 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001504 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1505 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001506
Richard Smithfeea8832012-04-12 05:08:17 +00001507 // All these operations take one of the following forms:
1508 enum {
1509 // C __c11_atomic_init(A *, C)
1510 Init,
1511 // C __c11_atomic_load(A *, int)
1512 Load,
1513 // void __atomic_load(A *, CP, int)
1514 Copy,
1515 // C __c11_atomic_add(A *, M, int)
1516 Arithmetic,
1517 // C __atomic_exchange_n(A *, CP, int)
1518 Xchg,
1519 // void __atomic_exchange(A *, C *, CP, int)
1520 GNUXchg,
1521 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1522 C11CmpXchg,
1523 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1524 GNUCmpXchg
1525 } Form = Init;
1526 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1527 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1528 // where:
1529 // C is an appropriate type,
1530 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1531 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1532 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1533 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001534
Gabor Horvath98bd0982015-03-16 09:59:54 +00001535 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1536 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1537 AtomicExpr::AO__atomic_load,
1538 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00001539 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1540 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1541 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1542 Op == AtomicExpr::AO__atomic_store_n ||
1543 Op == AtomicExpr::AO__atomic_exchange_n ||
1544 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1545 bool IsAddSub = false;
1546
1547 switch (Op) {
1548 case AtomicExpr::AO__c11_atomic_init:
1549 Form = Init;
1550 break;
1551
1552 case AtomicExpr::AO__c11_atomic_load:
1553 case AtomicExpr::AO__atomic_load_n:
1554 Form = Load;
1555 break;
1556
1557 case AtomicExpr::AO__c11_atomic_store:
1558 case AtomicExpr::AO__atomic_load:
1559 case AtomicExpr::AO__atomic_store:
1560 case AtomicExpr::AO__atomic_store_n:
1561 Form = Copy;
1562 break;
1563
1564 case AtomicExpr::AO__c11_atomic_fetch_add:
1565 case AtomicExpr::AO__c11_atomic_fetch_sub:
1566 case AtomicExpr::AO__atomic_fetch_add:
1567 case AtomicExpr::AO__atomic_fetch_sub:
1568 case AtomicExpr::AO__atomic_add_fetch:
1569 case AtomicExpr::AO__atomic_sub_fetch:
1570 IsAddSub = true;
1571 // Fall through.
1572 case AtomicExpr::AO__c11_atomic_fetch_and:
1573 case AtomicExpr::AO__c11_atomic_fetch_or:
1574 case AtomicExpr::AO__c11_atomic_fetch_xor:
1575 case AtomicExpr::AO__atomic_fetch_and:
1576 case AtomicExpr::AO__atomic_fetch_or:
1577 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001578 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001579 case AtomicExpr::AO__atomic_and_fetch:
1580 case AtomicExpr::AO__atomic_or_fetch:
1581 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001582 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001583 Form = Arithmetic;
1584 break;
1585
1586 case AtomicExpr::AO__c11_atomic_exchange:
1587 case AtomicExpr::AO__atomic_exchange_n:
1588 Form = Xchg;
1589 break;
1590
1591 case AtomicExpr::AO__atomic_exchange:
1592 Form = GNUXchg;
1593 break;
1594
1595 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1596 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1597 Form = C11CmpXchg;
1598 break;
1599
1600 case AtomicExpr::AO__atomic_compare_exchange:
1601 case AtomicExpr::AO__atomic_compare_exchange_n:
1602 Form = GNUCmpXchg;
1603 break;
1604 }
1605
1606 // Check we have the right number of arguments.
1607 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001608 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001609 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001610 << TheCall->getCallee()->getSourceRange();
1611 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001612 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1613 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001614 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001615 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001616 << TheCall->getCallee()->getSourceRange();
1617 return ExprError();
1618 }
1619
Richard Smithfeea8832012-04-12 05:08:17 +00001620 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001621 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001622 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1623 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1624 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001625 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001626 << Ptr->getType() << Ptr->getSourceRange();
1627 return ExprError();
1628 }
1629
Richard Smithfeea8832012-04-12 05:08:17 +00001630 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1631 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1632 QualType ValType = AtomTy; // 'C'
1633 if (IsC11) {
1634 if (!AtomTy->isAtomicType()) {
1635 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1636 << Ptr->getType() << Ptr->getSourceRange();
1637 return ExprError();
1638 }
Richard Smithe00921a2012-09-15 06:09:58 +00001639 if (AtomTy.isConstQualified()) {
1640 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1641 << Ptr->getType() << Ptr->getSourceRange();
1642 return ExprError();
1643 }
Richard Smithfeea8832012-04-12 05:08:17 +00001644 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001645 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001646
Richard Smithfeea8832012-04-12 05:08:17 +00001647 // For an arithmetic operation, the implied arithmetic must be well-formed.
1648 if (Form == Arithmetic) {
1649 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1650 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1651 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1652 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1653 return ExprError();
1654 }
1655 if (!IsAddSub && !ValType->isIntegerType()) {
1656 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1657 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1658 return ExprError();
1659 }
David Majnemere85cff82015-01-28 05:48:06 +00001660 if (IsC11 && ValType->isPointerType() &&
1661 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1662 diag::err_incomplete_type)) {
1663 return ExprError();
1664 }
Richard Smithfeea8832012-04-12 05:08:17 +00001665 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1666 // For __atomic_*_n operations, the value type must be a scalar integral or
1667 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001668 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001669 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1670 return ExprError();
1671 }
1672
Eli Friedmanaa769812013-09-11 03:49:34 +00001673 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1674 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001675 // For GNU atomics, require a trivially-copyable type. This is not part of
1676 // the GNU atomics specification, but we enforce it for sanity.
1677 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001678 << Ptr->getType() << Ptr->getSourceRange();
1679 return ExprError();
1680 }
1681
Richard Smithfeea8832012-04-12 05:08:17 +00001682 // FIXME: For any builtin other than a load, the ValType must not be
1683 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001684
1685 switch (ValType.getObjCLifetime()) {
1686 case Qualifiers::OCL_None:
1687 case Qualifiers::OCL_ExplicitNone:
1688 // okay
1689 break;
1690
1691 case Qualifiers::OCL_Weak:
1692 case Qualifiers::OCL_Strong:
1693 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001694 // FIXME: Can this happen? By this point, ValType should be known
1695 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001696 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1697 << ValType << Ptr->getSourceRange();
1698 return ExprError();
1699 }
1700
David Majnemerc6eb6502015-06-03 00:26:35 +00001701 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
1702 // volatile-ness of the pointee-type inject itself into the result or the
1703 // other operands.
1704 ValType.removeLocalVolatile();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001705 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001706 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001707 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001708 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001709 ResultType = Context.BoolTy;
1710
Richard Smithfeea8832012-04-12 05:08:17 +00001711 // The type of a parameter passed 'by value'. In the GNU atomics, such
1712 // arguments are actually passed as pointers.
1713 QualType ByValType = ValType; // 'CP'
1714 if (!IsC11 && !IsN)
1715 ByValType = Ptr->getType();
1716
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001717 // The first argument --- the pointer --- has a fixed type; we
1718 // deduce the types of the rest of the arguments accordingly. Walk
1719 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001720 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001721 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001722 if (i < NumVals[Form] + 1) {
1723 switch (i) {
1724 case 1:
1725 // The second argument is the non-atomic operand. For arithmetic, this
1726 // is always passed by value, and for a compare_exchange it is always
1727 // passed by address. For the rest, GNU uses by-address and C11 uses
1728 // by-value.
1729 assert(Form != Load);
1730 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1731 Ty = ValType;
1732 else if (Form == Copy || Form == Xchg)
1733 Ty = ByValType;
1734 else if (Form == Arithmetic)
1735 Ty = Context.getPointerDiffType();
1736 else
1737 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1738 break;
1739 case 2:
1740 // The third argument to compare_exchange / GNU exchange is a
1741 // (pointer to a) desired value.
1742 Ty = ByValType;
1743 break;
1744 case 3:
1745 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1746 Ty = Context.BoolTy;
1747 break;
1748 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001749 } else {
1750 // The order(s) are always converted to int.
1751 Ty = Context.IntTy;
1752 }
Richard Smithfeea8832012-04-12 05:08:17 +00001753
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001754 InitializedEntity Entity =
1755 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001756 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001757 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1758 if (Arg.isInvalid())
1759 return true;
1760 TheCall->setArg(i, Arg.get());
1761 }
1762
Richard Smithfeea8832012-04-12 05:08:17 +00001763 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001764 SmallVector<Expr*, 5> SubExprs;
1765 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001766 switch (Form) {
1767 case Init:
1768 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001769 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001770 break;
1771 case Load:
1772 SubExprs.push_back(TheCall->getArg(1)); // Order
1773 break;
1774 case Copy:
1775 case Arithmetic:
1776 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001777 SubExprs.push_back(TheCall->getArg(2)); // Order
1778 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001779 break;
1780 case GNUXchg:
1781 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1782 SubExprs.push_back(TheCall->getArg(3)); // Order
1783 SubExprs.push_back(TheCall->getArg(1)); // Val1
1784 SubExprs.push_back(TheCall->getArg(2)); // Val2
1785 break;
1786 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001787 SubExprs.push_back(TheCall->getArg(3)); // Order
1788 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001789 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001790 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001791 break;
1792 case GNUCmpXchg:
1793 SubExprs.push_back(TheCall->getArg(4)); // Order
1794 SubExprs.push_back(TheCall->getArg(1)); // Val1
1795 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1796 SubExprs.push_back(TheCall->getArg(2)); // Val2
1797 SubExprs.push_back(TheCall->getArg(3)); // Weak
1798 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001799 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001800
1801 if (SubExprs.size() >= 2 && Form != Init) {
1802 llvm::APSInt Result(32);
1803 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1804 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001805 Diag(SubExprs[1]->getLocStart(),
1806 diag::warn_atomic_op_has_invalid_memory_order)
1807 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001808 }
1809
Fariborz Jahanian615de762013-05-28 17:37:39 +00001810 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1811 SubExprs, ResultType, Op,
1812 TheCall->getRParenLoc());
1813
1814 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1815 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1816 Context.AtomicUsesUnsupportedLibcall(AE))
1817 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1818 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001819
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001820 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001821}
1822
1823
John McCall29ad95b2011-08-27 01:09:30 +00001824/// checkBuiltinArgument - Given a call to a builtin function, perform
1825/// normal type-checking on the given argument, updating the call in
1826/// place. This is useful when a builtin function requires custom
1827/// type-checking for some of its arguments but not necessarily all of
1828/// them.
1829///
1830/// Returns true on error.
1831static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1832 FunctionDecl *Fn = E->getDirectCallee();
1833 assert(Fn && "builtin call without direct callee!");
1834
1835 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1836 InitializedEntity Entity =
1837 InitializedEntity::InitializeParameter(S.Context, Param);
1838
1839 ExprResult Arg = E->getArg(0);
1840 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1841 if (Arg.isInvalid())
1842 return true;
1843
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001844 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001845 return false;
1846}
1847
Chris Lattnerdc046542009-05-08 06:58:22 +00001848/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1849/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1850/// type of its first argument. The main ActOnCallExpr routines have already
1851/// promoted the types of arguments because all of these calls are prototyped as
1852/// void(...).
1853///
1854/// This function goes through and does final semantic checking for these
1855/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001856ExprResult
1857Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001858 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001859 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1860 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1861
1862 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001863 if (TheCall->getNumArgs() < 1) {
1864 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1865 << 0 << 1 << TheCall->getNumArgs()
1866 << TheCall->getCallee()->getSourceRange();
1867 return ExprError();
1868 }
Mike Stump11289f42009-09-09 15:08:12 +00001869
Chris Lattnerdc046542009-05-08 06:58:22 +00001870 // Inspect the first argument of the atomic builtin. This should always be
1871 // a pointer type, whose element is an integral scalar or pointer type.
1872 // Because it is a pointer type, we don't have to worry about any implicit
1873 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001874 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001875 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001876 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1877 if (FirstArgResult.isInvalid())
1878 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001879 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001880 TheCall->setArg(0, FirstArg);
1881
John McCall31168b02011-06-15 23:02:42 +00001882 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1883 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001884 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1885 << FirstArg->getType() << FirstArg->getSourceRange();
1886 return ExprError();
1887 }
Mike Stump11289f42009-09-09 15:08:12 +00001888
John McCall31168b02011-06-15 23:02:42 +00001889 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001890 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001891 !ValType->isBlockPointerType()) {
1892 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1893 << FirstArg->getType() << FirstArg->getSourceRange();
1894 return ExprError();
1895 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001896
John McCall31168b02011-06-15 23:02:42 +00001897 switch (ValType.getObjCLifetime()) {
1898 case Qualifiers::OCL_None:
1899 case Qualifiers::OCL_ExplicitNone:
1900 // okay
1901 break;
1902
1903 case Qualifiers::OCL_Weak:
1904 case Qualifiers::OCL_Strong:
1905 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001906 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001907 << ValType << FirstArg->getSourceRange();
1908 return ExprError();
1909 }
1910
John McCallb50451a2011-10-05 07:41:44 +00001911 // Strip any qualifiers off ValType.
1912 ValType = ValType.getUnqualifiedType();
1913
Chandler Carruth3973af72010-07-18 20:54:12 +00001914 // The majority of builtins return a value, but a few have special return
1915 // types, so allow them to override appropriately below.
1916 QualType ResultType = ValType;
1917
Chris Lattnerdc046542009-05-08 06:58:22 +00001918 // We need to figure out which concrete builtin this maps onto. For example,
1919 // __sync_fetch_and_add with a 2 byte object turns into
1920 // __sync_fetch_and_add_2.
1921#define BUILTIN_ROW(x) \
1922 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1923 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001924
Chris Lattnerdc046542009-05-08 06:58:22 +00001925 static const unsigned BuiltinIndices[][5] = {
1926 BUILTIN_ROW(__sync_fetch_and_add),
1927 BUILTIN_ROW(__sync_fetch_and_sub),
1928 BUILTIN_ROW(__sync_fetch_and_or),
1929 BUILTIN_ROW(__sync_fetch_and_and),
1930 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00001931 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00001932
Chris Lattnerdc046542009-05-08 06:58:22 +00001933 BUILTIN_ROW(__sync_add_and_fetch),
1934 BUILTIN_ROW(__sync_sub_and_fetch),
1935 BUILTIN_ROW(__sync_and_and_fetch),
1936 BUILTIN_ROW(__sync_or_and_fetch),
1937 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00001938 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001939
Chris Lattnerdc046542009-05-08 06:58:22 +00001940 BUILTIN_ROW(__sync_val_compare_and_swap),
1941 BUILTIN_ROW(__sync_bool_compare_and_swap),
1942 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001943 BUILTIN_ROW(__sync_lock_release),
1944 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001945 };
Mike Stump11289f42009-09-09 15:08:12 +00001946#undef BUILTIN_ROW
1947
Chris Lattnerdc046542009-05-08 06:58:22 +00001948 // Determine the index of the size.
1949 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001950 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001951 case 1: SizeIndex = 0; break;
1952 case 2: SizeIndex = 1; break;
1953 case 4: SizeIndex = 2; break;
1954 case 8: SizeIndex = 3; break;
1955 case 16: SizeIndex = 4; break;
1956 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001957 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1958 << FirstArg->getType() << FirstArg->getSourceRange();
1959 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001960 }
Mike Stump11289f42009-09-09 15:08:12 +00001961
Chris Lattnerdc046542009-05-08 06:58:22 +00001962 // Each of these builtins has one pointer argument, followed by some number of
1963 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1964 // that we ignore. Find out which row of BuiltinIndices to read from as well
1965 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001966 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001967 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00001968 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00001969 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001970 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001971 case Builtin::BI__sync_fetch_and_add:
1972 case Builtin::BI__sync_fetch_and_add_1:
1973 case Builtin::BI__sync_fetch_and_add_2:
1974 case Builtin::BI__sync_fetch_and_add_4:
1975 case Builtin::BI__sync_fetch_and_add_8:
1976 case Builtin::BI__sync_fetch_and_add_16:
1977 BuiltinIndex = 0;
1978 break;
1979
1980 case Builtin::BI__sync_fetch_and_sub:
1981 case Builtin::BI__sync_fetch_and_sub_1:
1982 case Builtin::BI__sync_fetch_and_sub_2:
1983 case Builtin::BI__sync_fetch_and_sub_4:
1984 case Builtin::BI__sync_fetch_and_sub_8:
1985 case Builtin::BI__sync_fetch_and_sub_16:
1986 BuiltinIndex = 1;
1987 break;
1988
1989 case Builtin::BI__sync_fetch_and_or:
1990 case Builtin::BI__sync_fetch_and_or_1:
1991 case Builtin::BI__sync_fetch_and_or_2:
1992 case Builtin::BI__sync_fetch_and_or_4:
1993 case Builtin::BI__sync_fetch_and_or_8:
1994 case Builtin::BI__sync_fetch_and_or_16:
1995 BuiltinIndex = 2;
1996 break;
1997
1998 case Builtin::BI__sync_fetch_and_and:
1999 case Builtin::BI__sync_fetch_and_and_1:
2000 case Builtin::BI__sync_fetch_and_and_2:
2001 case Builtin::BI__sync_fetch_and_and_4:
2002 case Builtin::BI__sync_fetch_and_and_8:
2003 case Builtin::BI__sync_fetch_and_and_16:
2004 BuiltinIndex = 3;
2005 break;
Mike Stump11289f42009-09-09 15:08:12 +00002006
Douglas Gregor73722482011-11-28 16:30:08 +00002007 case Builtin::BI__sync_fetch_and_xor:
2008 case Builtin::BI__sync_fetch_and_xor_1:
2009 case Builtin::BI__sync_fetch_and_xor_2:
2010 case Builtin::BI__sync_fetch_and_xor_4:
2011 case Builtin::BI__sync_fetch_and_xor_8:
2012 case Builtin::BI__sync_fetch_and_xor_16:
2013 BuiltinIndex = 4;
2014 break;
2015
Hal Finkeld2208b52014-10-02 20:53:50 +00002016 case Builtin::BI__sync_fetch_and_nand:
2017 case Builtin::BI__sync_fetch_and_nand_1:
2018 case Builtin::BI__sync_fetch_and_nand_2:
2019 case Builtin::BI__sync_fetch_and_nand_4:
2020 case Builtin::BI__sync_fetch_and_nand_8:
2021 case Builtin::BI__sync_fetch_and_nand_16:
2022 BuiltinIndex = 5;
2023 WarnAboutSemanticsChange = true;
2024 break;
2025
Douglas Gregor73722482011-11-28 16:30:08 +00002026 case Builtin::BI__sync_add_and_fetch:
2027 case Builtin::BI__sync_add_and_fetch_1:
2028 case Builtin::BI__sync_add_and_fetch_2:
2029 case Builtin::BI__sync_add_and_fetch_4:
2030 case Builtin::BI__sync_add_and_fetch_8:
2031 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002032 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002033 break;
2034
2035 case Builtin::BI__sync_sub_and_fetch:
2036 case Builtin::BI__sync_sub_and_fetch_1:
2037 case Builtin::BI__sync_sub_and_fetch_2:
2038 case Builtin::BI__sync_sub_and_fetch_4:
2039 case Builtin::BI__sync_sub_and_fetch_8:
2040 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002041 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002042 break;
2043
2044 case Builtin::BI__sync_and_and_fetch:
2045 case Builtin::BI__sync_and_and_fetch_1:
2046 case Builtin::BI__sync_and_and_fetch_2:
2047 case Builtin::BI__sync_and_and_fetch_4:
2048 case Builtin::BI__sync_and_and_fetch_8:
2049 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002050 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002051 break;
2052
2053 case Builtin::BI__sync_or_and_fetch:
2054 case Builtin::BI__sync_or_and_fetch_1:
2055 case Builtin::BI__sync_or_and_fetch_2:
2056 case Builtin::BI__sync_or_and_fetch_4:
2057 case Builtin::BI__sync_or_and_fetch_8:
2058 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002059 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002060 break;
2061
2062 case Builtin::BI__sync_xor_and_fetch:
2063 case Builtin::BI__sync_xor_and_fetch_1:
2064 case Builtin::BI__sync_xor_and_fetch_2:
2065 case Builtin::BI__sync_xor_and_fetch_4:
2066 case Builtin::BI__sync_xor_and_fetch_8:
2067 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002068 BuiltinIndex = 10;
2069 break;
2070
2071 case Builtin::BI__sync_nand_and_fetch:
2072 case Builtin::BI__sync_nand_and_fetch_1:
2073 case Builtin::BI__sync_nand_and_fetch_2:
2074 case Builtin::BI__sync_nand_and_fetch_4:
2075 case Builtin::BI__sync_nand_and_fetch_8:
2076 case Builtin::BI__sync_nand_and_fetch_16:
2077 BuiltinIndex = 11;
2078 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002079 break;
Mike Stump11289f42009-09-09 15:08:12 +00002080
Chris Lattnerdc046542009-05-08 06:58:22 +00002081 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002082 case Builtin::BI__sync_val_compare_and_swap_1:
2083 case Builtin::BI__sync_val_compare_and_swap_2:
2084 case Builtin::BI__sync_val_compare_and_swap_4:
2085 case Builtin::BI__sync_val_compare_and_swap_8:
2086 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002087 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002088 NumFixed = 2;
2089 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002090
Chris Lattnerdc046542009-05-08 06:58:22 +00002091 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002092 case Builtin::BI__sync_bool_compare_and_swap_1:
2093 case Builtin::BI__sync_bool_compare_and_swap_2:
2094 case Builtin::BI__sync_bool_compare_and_swap_4:
2095 case Builtin::BI__sync_bool_compare_and_swap_8:
2096 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002097 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002098 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002099 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002100 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002101
2102 case Builtin::BI__sync_lock_test_and_set:
2103 case Builtin::BI__sync_lock_test_and_set_1:
2104 case Builtin::BI__sync_lock_test_and_set_2:
2105 case Builtin::BI__sync_lock_test_and_set_4:
2106 case Builtin::BI__sync_lock_test_and_set_8:
2107 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002108 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002109 break;
2110
Chris Lattnerdc046542009-05-08 06:58:22 +00002111 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002112 case Builtin::BI__sync_lock_release_1:
2113 case Builtin::BI__sync_lock_release_2:
2114 case Builtin::BI__sync_lock_release_4:
2115 case Builtin::BI__sync_lock_release_8:
2116 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002117 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002118 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002119 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002120 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002121
2122 case Builtin::BI__sync_swap:
2123 case Builtin::BI__sync_swap_1:
2124 case Builtin::BI__sync_swap_2:
2125 case Builtin::BI__sync_swap_4:
2126 case Builtin::BI__sync_swap_8:
2127 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002128 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002129 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002130 }
Mike Stump11289f42009-09-09 15:08:12 +00002131
Chris Lattnerdc046542009-05-08 06:58:22 +00002132 // Now that we know how many fixed arguments we expect, first check that we
2133 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002134 if (TheCall->getNumArgs() < 1+NumFixed) {
2135 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2136 << 0 << 1+NumFixed << TheCall->getNumArgs()
2137 << TheCall->getCallee()->getSourceRange();
2138 return ExprError();
2139 }
Mike Stump11289f42009-09-09 15:08:12 +00002140
Hal Finkeld2208b52014-10-02 20:53:50 +00002141 if (WarnAboutSemanticsChange) {
2142 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2143 << TheCall->getCallee()->getSourceRange();
2144 }
2145
Chris Lattner5b9241b2009-05-08 15:36:58 +00002146 // Get the decl for the concrete builtin from this, we can tell what the
2147 // concrete integer type we should convert to is.
2148 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Eric Christopher02d5d862015-08-06 01:01:12 +00002149 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002150 FunctionDecl *NewBuiltinDecl;
2151 if (NewBuiltinID == BuiltinID)
2152 NewBuiltinDecl = FDecl;
2153 else {
2154 // Perform builtin lookup to avoid redeclaring it.
2155 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2156 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2157 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2158 assert(Res.getFoundDecl());
2159 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00002160 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002161 return ExprError();
2162 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002163
John McCallcf142162010-08-07 06:22:56 +00002164 // The first argument --- the pointer --- has a fixed type; we
2165 // deduce the types of the rest of the arguments accordingly. Walk
2166 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00002167 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002168 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002169
Chris Lattnerdc046542009-05-08 06:58:22 +00002170 // GCC does an implicit conversion to the pointer or integer ValType. This
2171 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002172 // Initialize the argument.
2173 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2174 ValType, /*consume*/ false);
2175 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002176 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002177 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002178
Chris Lattnerdc046542009-05-08 06:58:22 +00002179 // Okay, we have something that *can* be converted to the right type. Check
2180 // to see if there is a potentially weird extension going on here. This can
2181 // happen when you do an atomic operation on something like an char* and
2182 // pass in 42. The 42 gets converted to char. This is even more strange
2183 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002184 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002185 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002186 }
Mike Stump11289f42009-09-09 15:08:12 +00002187
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002188 ASTContext& Context = this->getASTContext();
2189
2190 // Create a new DeclRefExpr to refer to the new decl.
2191 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2192 Context,
2193 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002194 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002195 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002196 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002197 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002198 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002199 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002200
Chris Lattnerdc046542009-05-08 06:58:22 +00002201 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002202 // FIXME: This loses syntactic information.
2203 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2204 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2205 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002206 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002207
Chandler Carruthbc8cab12010-07-18 07:23:17 +00002208 // Change the result type of the call to match the original value type. This
2209 // is arbitrary, but the codegen for these builtins ins design to handle it
2210 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00002211 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002212
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002213 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002214}
2215
Michael Zolotukhin84df1232015-09-08 23:52:33 +00002216/// SemaBuiltinNontemporalOverloaded - We have a call to
2217/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2218/// overloaded function based on the pointer type of its last argument.
2219///
2220/// This function goes through and does final semantic checking for these
2221/// builtins.
2222ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
2223 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2224 DeclRefExpr *DRE =
2225 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2226 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2227 unsigned BuiltinID = FDecl->getBuiltinID();
2228 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
2229 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
2230 "Unexpected nontemporal load/store builtin!");
2231 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
2232 unsigned numArgs = isStore ? 2 : 1;
2233
2234 // Ensure that we have the proper number of arguments.
2235 if (checkArgCount(*this, TheCall, numArgs))
2236 return ExprError();
2237
2238 // Inspect the last argument of the nontemporal builtin. This should always
2239 // be a pointer type, from which we imply the type of the memory access.
2240 // Because it is a pointer type, we don't have to worry about any implicit
2241 // casts here.
2242 Expr *PointerArg = TheCall->getArg(numArgs - 1);
2243 ExprResult PointerArgResult =
2244 DefaultFunctionArrayLvalueConversion(PointerArg);
2245
2246 if (PointerArgResult.isInvalid())
2247 return ExprError();
2248 PointerArg = PointerArgResult.get();
2249 TheCall->setArg(numArgs - 1, PointerArg);
2250
2251 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2252 if (!pointerType) {
2253 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
2254 << PointerArg->getType() << PointerArg->getSourceRange();
2255 return ExprError();
2256 }
2257
2258 QualType ValType = pointerType->getPointeeType();
2259
2260 // Strip any qualifiers off ValType.
2261 ValType = ValType.getUnqualifiedType();
2262 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2263 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
2264 !ValType->isVectorType()) {
2265 Diag(DRE->getLocStart(),
2266 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
2267 << PointerArg->getType() << PointerArg->getSourceRange();
2268 return ExprError();
2269 }
2270
2271 if (!isStore) {
2272 TheCall->setType(ValType);
2273 return TheCallResult;
2274 }
2275
2276 ExprResult ValArg = TheCall->getArg(0);
2277 InitializedEntity Entity = InitializedEntity::InitializeParameter(
2278 Context, ValType, /*consume*/ false);
2279 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2280 if (ValArg.isInvalid())
2281 return ExprError();
2282
2283 TheCall->setArg(0, ValArg.get());
2284 TheCall->setType(Context.VoidTy);
2285 return TheCallResult;
2286}
2287
Chris Lattner6436fb62009-02-18 06:01:06 +00002288/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002289/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002290/// Note: It might also make sense to do the UTF-16 conversion here (would
2291/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002292bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002293 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002294 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2295
Douglas Gregorfb65e592011-07-27 05:40:30 +00002296 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002297 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2298 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002299 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002300 }
Mike Stump11289f42009-09-09 15:08:12 +00002301
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002302 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002303 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002304 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002305 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002306 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002307 UTF16 *ToPtr = &ToBuf[0];
2308
2309 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2310 &ToPtr, ToPtr + NumBytes,
2311 strictConversion);
2312 // Check for conversion failure.
2313 if (Result != conversionOK)
2314 Diag(Arg->getLocStart(),
2315 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2316 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002317 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002318}
2319
Chris Lattnere202e6a2007-12-20 00:05:45 +00002320/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
2321/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00002322bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2323 Expr *Fn = TheCall->getCallee();
2324 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002325 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002326 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002327 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2328 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002329 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002330 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002331 return true;
2332 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002333
2334 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002335 return Diag(TheCall->getLocEnd(),
2336 diag::err_typecheck_call_too_few_args_at_least)
2337 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002338 }
2339
John McCall29ad95b2011-08-27 01:09:30 +00002340 // Type-check the first argument normally.
2341 if (checkBuiltinArgument(*this, TheCall, 0))
2342 return true;
2343
Chris Lattnere202e6a2007-12-20 00:05:45 +00002344 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002345 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002346 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002347 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002348 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002349 else if (FunctionDecl *FD = getCurFunctionDecl())
2350 isVariadic = FD->isVariadic();
2351 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002352 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002353
Chris Lattnere202e6a2007-12-20 00:05:45 +00002354 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002355 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2356 return true;
2357 }
Mike Stump11289f42009-09-09 15:08:12 +00002358
Chris Lattner43be2e62007-12-19 23:59:04 +00002359 // Verify that the second argument to the builtin is the last argument of the
2360 // current function or method.
2361 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002362 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002363
Nico Weber9eea7642013-05-24 23:31:57 +00002364 // These are valid if SecondArgIsLastNamedArgument is false after the next
2365 // block.
2366 QualType Type;
2367 SourceLocation ParamLoc;
2368
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002369 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2370 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002371 // FIXME: This isn't correct for methods (results in bogus warning).
2372 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002373 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002374 if (CurBlock)
2375 LastArg = *(CurBlock->TheDecl->param_end()-1);
2376 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002377 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002378 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002379 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002380 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002381
2382 Type = PV->getType();
2383 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002384 }
2385 }
Mike Stump11289f42009-09-09 15:08:12 +00002386
Chris Lattner43be2e62007-12-19 23:59:04 +00002387 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002388 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002389 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002390 else if (Type->isReferenceType()) {
2391 Diag(Arg->getLocStart(),
2392 diag::warn_va_start_of_reference_type_is_undefined);
2393 Diag(ParamLoc, diag::note_parameter_type) << Type;
2394 }
2395
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002396 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002397 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002398}
Chris Lattner43be2e62007-12-19 23:59:04 +00002399
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002400bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2401 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2402 // const char *named_addr);
2403
2404 Expr *Func = Call->getCallee();
2405
2406 if (Call->getNumArgs() < 3)
2407 return Diag(Call->getLocEnd(),
2408 diag::err_typecheck_call_too_few_args_at_least)
2409 << 0 /*function call*/ << 3 << Call->getNumArgs();
2410
2411 // Determine whether the current function is variadic or not.
2412 bool IsVariadic;
2413 if (BlockScopeInfo *CurBlock = getCurBlock())
2414 IsVariadic = CurBlock->TheDecl->isVariadic();
2415 else if (FunctionDecl *FD = getCurFunctionDecl())
2416 IsVariadic = FD->isVariadic();
2417 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2418 IsVariadic = MD->isVariadic();
2419 else
2420 llvm_unreachable("unexpected statement type");
2421
2422 if (!IsVariadic) {
2423 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2424 return true;
2425 }
2426
2427 // Type-check the first argument normally.
2428 if (checkBuiltinArgument(*this, Call, 0))
2429 return true;
2430
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002431 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002432 unsigned ArgNo;
2433 QualType Type;
2434 } ArgumentTypes[] = {
2435 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2436 { 2, Context.getSizeType() },
2437 };
2438
2439 for (const auto &AT : ArgumentTypes) {
2440 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2441 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2442 continue;
2443 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2444 << Arg->getType() << AT.Type << 1 /* different class */
2445 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2446 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2447 }
2448
2449 return false;
2450}
2451
Chris Lattner2da14fb2007-12-20 00:26:33 +00002452/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2453/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002454bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2455 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002456 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002457 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002458 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002459 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002460 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002461 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002462 << SourceRange(TheCall->getArg(2)->getLocStart(),
2463 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002464
John Wiegley01296292011-04-08 18:41:53 +00002465 ExprResult OrigArg0 = TheCall->getArg(0);
2466 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002467
Chris Lattner2da14fb2007-12-20 00:26:33 +00002468 // Do standard promotions between the two arguments, returning their common
2469 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002470 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002471 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2472 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002473
2474 // Make sure any conversions are pushed back into the call; this is
2475 // type safe since unordered compare builtins are declared as "_Bool
2476 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002477 TheCall->setArg(0, OrigArg0.get());
2478 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002479
John Wiegley01296292011-04-08 18:41:53 +00002480 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002481 return false;
2482
Chris Lattner2da14fb2007-12-20 00:26:33 +00002483 // If the common type isn't a real floating type, then the arguments were
2484 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002485 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002486 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002487 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002488 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2489 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002490
Chris Lattner2da14fb2007-12-20 00:26:33 +00002491 return false;
2492}
2493
Benjamin Kramer634fc102010-02-15 22:42:31 +00002494/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2495/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002496/// to check everything. We expect the last argument to be a floating point
2497/// value.
2498bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2499 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002500 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002501 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002502 if (TheCall->getNumArgs() > NumArgs)
2503 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002504 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002505 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002506 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002507 (*(TheCall->arg_end()-1))->getLocEnd());
2508
Benjamin Kramer64aae502010-02-16 10:07:31 +00002509 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002510
Eli Friedman7e4faac2009-08-31 20:06:00 +00002511 if (OrigArg->isTypeDependent())
2512 return false;
2513
Chris Lattner68784ef2010-05-06 05:50:07 +00002514 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002515 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002516 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002517 diag::err_typecheck_call_invalid_unary_fp)
2518 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002519
Chris Lattner68784ef2010-05-06 05:50:07 +00002520 // If this is an implicit conversion from float -> double, remove it.
2521 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2522 Expr *CastArg = Cast->getSubExpr();
2523 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2524 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2525 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002526 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002527 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002528 }
2529 }
2530
Eli Friedman7e4faac2009-08-31 20:06:00 +00002531 return false;
2532}
2533
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002534/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2535// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002536ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002537 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002538 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002539 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002540 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2541 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002542
Nate Begemana0110022010-06-08 00:16:34 +00002543 // Determine which of the following types of shufflevector we're checking:
2544 // 1) unary, vector mask: (lhs, mask)
2545 // 2) binary, vector mask: (lhs, rhs, mask)
2546 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2547 QualType resType = TheCall->getArg(0)->getType();
2548 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002549
Douglas Gregorc25f7662009-05-19 22:10:17 +00002550 if (!TheCall->getArg(0)->isTypeDependent() &&
2551 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002552 QualType LHSType = TheCall->getArg(0)->getType();
2553 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002554
Craig Topperbaca3892013-07-29 06:47:04 +00002555 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2556 return ExprError(Diag(TheCall->getLocStart(),
2557 diag::err_shufflevector_non_vector)
2558 << SourceRange(TheCall->getArg(0)->getLocStart(),
2559 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002560
Nate Begemana0110022010-06-08 00:16:34 +00002561 numElements = LHSType->getAs<VectorType>()->getNumElements();
2562 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002563
Nate Begemana0110022010-06-08 00:16:34 +00002564 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2565 // with mask. If so, verify that RHS is an integer vector type with the
2566 // same number of elts as lhs.
2567 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002568 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002569 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002570 return ExprError(Diag(TheCall->getLocStart(),
2571 diag::err_shufflevector_incompatible_vector)
2572 << SourceRange(TheCall->getArg(1)->getLocStart(),
2573 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002574 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002575 return ExprError(Diag(TheCall->getLocStart(),
2576 diag::err_shufflevector_incompatible_vector)
2577 << SourceRange(TheCall->getArg(0)->getLocStart(),
2578 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002579 } else if (numElements != numResElements) {
2580 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002581 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002582 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002583 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002584 }
2585
2586 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002587 if (TheCall->getArg(i)->isTypeDependent() ||
2588 TheCall->getArg(i)->isValueDependent())
2589 continue;
2590
Nate Begemana0110022010-06-08 00:16:34 +00002591 llvm::APSInt Result(32);
2592 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2593 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002594 diag::err_shufflevector_nonconstant_argument)
2595 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002596
Craig Topper50ad5b72013-08-03 17:40:38 +00002597 // Allow -1 which will be translated to undef in the IR.
2598 if (Result.isSigned() && Result.isAllOnesValue())
2599 continue;
2600
Chris Lattner7ab824e2008-08-10 02:05:13 +00002601 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002602 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002603 diag::err_shufflevector_argument_too_large)
2604 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002605 }
2606
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002607 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002608
Chris Lattner7ab824e2008-08-10 02:05:13 +00002609 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002610 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002611 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002612 }
2613
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002614 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2615 TheCall->getCallee()->getLocStart(),
2616 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002617}
Chris Lattner43be2e62007-12-19 23:59:04 +00002618
Hal Finkelc4d7c822013-09-18 03:29:45 +00002619/// SemaConvertVectorExpr - Handle __builtin_convertvector
2620ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2621 SourceLocation BuiltinLoc,
2622 SourceLocation RParenLoc) {
2623 ExprValueKind VK = VK_RValue;
2624 ExprObjectKind OK = OK_Ordinary;
2625 QualType DstTy = TInfo->getType();
2626 QualType SrcTy = E->getType();
2627
2628 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2629 return ExprError(Diag(BuiltinLoc,
2630 diag::err_convertvector_non_vector)
2631 << E->getSourceRange());
2632 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2633 return ExprError(Diag(BuiltinLoc,
2634 diag::err_convertvector_non_vector_type));
2635
2636 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2637 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2638 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2639 if (SrcElts != DstElts)
2640 return ExprError(Diag(BuiltinLoc,
2641 diag::err_convertvector_incompatible_vector)
2642 << E->getSourceRange());
2643 }
2644
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002645 return new (Context)
2646 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002647}
2648
Daniel Dunbarb7257262008-07-21 22:59:13 +00002649/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2650// This is declared to take (const void*, ...) and can take two
2651// optional constant int args.
2652bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002653 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002654
Chris Lattner3b054132008-11-19 05:08:23 +00002655 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002656 return Diag(TheCall->getLocEnd(),
2657 diag::err_typecheck_call_too_many_args_at_most)
2658 << 0 /*function call*/ << 3 << NumArgs
2659 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002660
2661 // Argument 0 is checked for us and the remaining arguments must be
2662 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002663 for (unsigned i = 1; i != NumArgs; ++i)
2664 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002665 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002666
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002667 return false;
2668}
2669
Hal Finkelf0417332014-07-17 14:25:55 +00002670/// SemaBuiltinAssume - Handle __assume (MS Extension).
2671// __assume does not evaluate its arguments, and should warn if its argument
2672// has side effects.
2673bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2674 Expr *Arg = TheCall->getArg(0);
2675 if (Arg->isInstantiationDependent()) return false;
2676
2677 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00002678 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002679 << Arg->getSourceRange()
2680 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2681
2682 return false;
2683}
2684
2685/// Handle __builtin_assume_aligned. This is declared
2686/// as (const void*, size_t, ...) and can take one optional constant int arg.
2687bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2688 unsigned NumArgs = TheCall->getNumArgs();
2689
2690 if (NumArgs > 3)
2691 return Diag(TheCall->getLocEnd(),
2692 diag::err_typecheck_call_too_many_args_at_most)
2693 << 0 /*function call*/ << 3 << NumArgs
2694 << TheCall->getSourceRange();
2695
2696 // The alignment must be a constant integer.
2697 Expr *Arg = TheCall->getArg(1);
2698
2699 // We can't check the value of a dependent argument.
2700 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2701 llvm::APSInt Result;
2702 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2703 return true;
2704
2705 if (!Result.isPowerOf2())
2706 return Diag(TheCall->getLocStart(),
2707 diag::err_alignment_not_power_of_two)
2708 << Arg->getSourceRange();
2709 }
2710
2711 if (NumArgs > 2) {
2712 ExprResult Arg(TheCall->getArg(2));
2713 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2714 Context.getSizeType(), false);
2715 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2716 if (Arg.isInvalid()) return true;
2717 TheCall->setArg(2, Arg.get());
2718 }
Hal Finkelf0417332014-07-17 14:25:55 +00002719
2720 return false;
2721}
2722
Eric Christopher8d0c6212010-04-17 02:26:23 +00002723/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2724/// TheCall is a constant expression.
2725bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2726 llvm::APSInt &Result) {
2727 Expr *Arg = TheCall->getArg(ArgNum);
2728 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2729 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2730
2731 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2732
2733 if (!Arg->isIntegerConstantExpr(Result, Context))
2734 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002735 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002736
Chris Lattnerd545ad12009-09-23 06:06:36 +00002737 return false;
2738}
2739
Richard Sandiford28940af2014-04-16 08:47:51 +00002740/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2741/// TheCall is a constant expression in the range [Low, High].
2742bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2743 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002744 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002745
2746 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002747 Expr *Arg = TheCall->getArg(ArgNum);
2748 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002749 return false;
2750
Eric Christopher8d0c6212010-04-17 02:26:23 +00002751 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002752 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002753 return true;
2754
Richard Sandiford28940af2014-04-16 08:47:51 +00002755 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002756 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002757 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002758
2759 return false;
2760}
2761
Luke Cheeseman59b2d832015-06-15 17:51:01 +00002762/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
2763/// TheCall is an ARM/AArch64 special register string literal.
2764bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
2765 int ArgNum, unsigned ExpectedFieldNum,
2766 bool AllowName) {
2767 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2768 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
2769 BuiltinID == ARM::BI__builtin_arm_rsr ||
2770 BuiltinID == ARM::BI__builtin_arm_rsrp ||
2771 BuiltinID == ARM::BI__builtin_arm_wsr ||
2772 BuiltinID == ARM::BI__builtin_arm_wsrp;
2773 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2774 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
2775 BuiltinID == AArch64::BI__builtin_arm_rsr ||
2776 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2777 BuiltinID == AArch64::BI__builtin_arm_wsr ||
2778 BuiltinID == AArch64::BI__builtin_arm_wsrp;
2779 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
2780
2781 // We can't check the value of a dependent argument.
2782 Expr *Arg = TheCall->getArg(ArgNum);
2783 if (Arg->isTypeDependent() || Arg->isValueDependent())
2784 return false;
2785
2786 // Check if the argument is a string literal.
2787 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2788 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2789 << Arg->getSourceRange();
2790
2791 // Check the type of special register given.
2792 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2793 SmallVector<StringRef, 6> Fields;
2794 Reg.split(Fields, ":");
2795
2796 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
2797 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
2798 << Arg->getSourceRange();
2799
2800 // If the string is the name of a register then we cannot check that it is
2801 // valid here but if the string is of one the forms described in ACLE then we
2802 // can check that the supplied fields are integers and within the valid
2803 // ranges.
2804 if (Fields.size() > 1) {
2805 bool FiveFields = Fields.size() == 5;
2806
2807 bool ValidString = true;
2808 if (IsARMBuiltin) {
2809 ValidString &= Fields[0].startswith_lower("cp") ||
2810 Fields[0].startswith_lower("p");
2811 if (ValidString)
2812 Fields[0] =
2813 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
2814
2815 ValidString &= Fields[2].startswith_lower("c");
2816 if (ValidString)
2817 Fields[2] = Fields[2].drop_front(1);
2818
2819 if (FiveFields) {
2820 ValidString &= Fields[3].startswith_lower("c");
2821 if (ValidString)
2822 Fields[3] = Fields[3].drop_front(1);
2823 }
2824 }
2825
2826 SmallVector<int, 5> Ranges;
2827 if (FiveFields)
2828 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
2829 else
2830 Ranges.append({15, 7, 15});
2831
2832 for (unsigned i=0; i<Fields.size(); ++i) {
2833 int IntField;
2834 ValidString &= !Fields[i].getAsInteger(10, IntField);
2835 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
2836 }
2837
2838 if (!ValidString)
2839 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
2840 << Arg->getSourceRange();
2841
2842 } else if (IsAArch64Builtin && Fields.size() == 1) {
2843 // If the register name is one of those that appear in the condition below
2844 // and the special register builtin being used is one of the write builtins,
2845 // then we require that the argument provided for writing to the register
2846 // is an integer constant expression. This is because it will be lowered to
2847 // an MSR (immediate) instruction, so we need to know the immediate at
2848 // compile time.
2849 if (TheCall->getNumArgs() != 2)
2850 return false;
2851
2852 std::string RegLower = Reg.lower();
2853 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
2854 RegLower != "pan" && RegLower != "uao")
2855 return false;
2856
2857 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2858 }
2859
2860 return false;
2861}
2862
Eric Christopherd9832702015-06-29 21:00:05 +00002863/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
2864/// This checks that the target supports __builtin_cpu_supports and
2865/// that the string argument is constant and valid.
2866bool Sema::SemaBuiltinCpuSupports(CallExpr *TheCall) {
2867 Expr *Arg = TheCall->getArg(0);
2868
2869 // Check if the argument is a string literal.
2870 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2871 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2872 << Arg->getSourceRange();
2873
2874 // Check the contents of the string.
2875 StringRef Feature =
2876 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2877 if (!Context.getTargetInfo().validateCpuSupports(Feature))
2878 return Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
2879 << Arg->getSourceRange();
2880 return false;
2881}
2882
Eli Friedmanc97d0142009-05-03 06:04:26 +00002883/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002884/// This checks that the target supports __builtin_longjmp and
2885/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002886bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002887 if (!Context.getTargetInfo().hasSjLjLowering())
2888 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
2889 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2890
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002891 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002892 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002893
Eric Christopher8d0c6212010-04-17 02:26:23 +00002894 // TODO: This is less than ideal. Overload this to take a value.
2895 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2896 return true;
2897
2898 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002899 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2900 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2901
2902 return false;
2903}
2904
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002905
2906/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
2907/// This checks that the target supports __builtin_setjmp.
2908bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
2909 if (!Context.getTargetInfo().hasSjLjLowering())
2910 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
2911 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2912 return false;
2913}
2914
Richard Smithd7293d72013-08-05 18:49:43 +00002915namespace {
2916enum StringLiteralCheckType {
2917 SLCT_NotALiteral,
2918 SLCT_UncheckedLiteral,
2919 SLCT_CheckedLiteral
2920};
2921}
2922
Richard Smith55ce3522012-06-25 20:30:08 +00002923// Determine if an expression is a string literal or constant string.
2924// If this function returns false on the arguments to a function expecting a
2925// format string, we will usually need to emit a warning.
2926// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002927static StringLiteralCheckType
2928checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2929 bool HasVAListArg, unsigned format_idx,
2930 unsigned firstDataArg, Sema::FormatStringType Type,
2931 Sema::VariadicCallType CallType, bool InFunctionCall,
2932 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002933 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002934 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002935 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002936
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002937 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002938
Richard Smithd7293d72013-08-05 18:49:43 +00002939 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002940 // Technically -Wformat-nonliteral does not warn about this case.
2941 // The behavior of printf and friends in this case is implementation
2942 // dependent. Ideally if the format string cannot be null then
2943 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002944 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002945
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002946 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002947 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002948 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002949 // The expression is a literal if both sub-expressions were, and it was
2950 // completely checked only if both sub-expressions were checked.
2951 const AbstractConditionalOperator *C =
2952 cast<AbstractConditionalOperator>(E);
2953 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002954 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002955 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002956 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002957 if (Left == SLCT_NotALiteral)
2958 return SLCT_NotALiteral;
2959 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002960 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002961 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002962 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002963 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002964 }
2965
2966 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002967 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2968 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002969 }
2970
John McCallc07a0c72011-02-17 10:25:35 +00002971 case Stmt::OpaqueValueExprClass:
2972 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2973 E = src;
2974 goto tryAgain;
2975 }
Richard Smith55ce3522012-06-25 20:30:08 +00002976 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002977
Ted Kremeneka8890832011-02-24 23:03:04 +00002978 case Stmt::PredefinedExprClass:
2979 // While __func__, etc., are technically not string literals, they
2980 // cannot contain format specifiers and thus are not a security
2981 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002982 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002983
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002984 case Stmt::DeclRefExprClass: {
2985 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002986
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002987 // As an exception, do not flag errors for variables binding to
2988 // const string literals.
2989 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2990 bool isConstant = false;
2991 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002992
Richard Smithd7293d72013-08-05 18:49:43 +00002993 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2994 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002995 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002996 isConstant = T.isConstant(S.Context) &&
2997 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002998 } else if (T->isObjCObjectPointerType()) {
2999 // In ObjC, there is usually no "const ObjectPointer" type,
3000 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00003001 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003002 }
Mike Stump11289f42009-09-09 15:08:12 +00003003
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003004 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003005 if (const Expr *Init = VD->getAnyInitializer()) {
3006 // Look through initializers like const char c[] = { "foo" }
3007 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3008 if (InitList->isStringLiteralInit())
3009 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3010 }
Richard Smithd7293d72013-08-05 18:49:43 +00003011 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003012 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003013 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003014 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003015 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003016 }
Mike Stump11289f42009-09-09 15:08:12 +00003017
Anders Carlssonb012ca92009-06-28 19:55:58 +00003018 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3019 // special check to see if the format string is a function parameter
3020 // of the function calling the printf function. If the function
3021 // has an attribute indicating it is a printf-like function, then we
3022 // should suppress warnings concerning non-literals being used in a call
3023 // to a vprintf function. For example:
3024 //
3025 // void
3026 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3027 // va_list ap;
3028 // va_start(ap, fmt);
3029 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3030 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00003031 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003032 if (HasVAListArg) {
3033 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3034 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3035 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003036 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003037 // adjust for implicit parameter
3038 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3039 if (MD->isInstance())
3040 ++PVIndex;
3041 // We also check if the formats are compatible.
3042 // We can't pass a 'scanf' string to a 'printf' function.
3043 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00003044 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00003045 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003046 }
3047 }
3048 }
3049 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003050 }
Mike Stump11289f42009-09-09 15:08:12 +00003051
Richard Smith55ce3522012-06-25 20:30:08 +00003052 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003053 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003054
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003055 case Stmt::CallExprClass:
3056 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003057 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003058 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3059 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3060 unsigned ArgIndex = FA->getFormatIdx();
3061 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3062 if (MD->isInstance())
3063 --ArgIndex;
3064 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00003065
Richard Smithd7293d72013-08-05 18:49:43 +00003066 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003067 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003068 Type, CallType, InFunctionCall,
3069 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003070 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3071 unsigned BuiltinID = FD->getBuiltinID();
3072 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3073 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3074 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00003075 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003076 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003077 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003078 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003079 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003080 }
3081 }
Mike Stump11289f42009-09-09 15:08:12 +00003082
Richard Smith55ce3522012-06-25 20:30:08 +00003083 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003084 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003085 case Stmt::ObjCStringLiteralClass:
3086 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00003087 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003088
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003089 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003090 StrE = ObjCFExpr->getString();
3091 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003092 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003093
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003094 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00003095 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
3096 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003097 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003098 }
Mike Stump11289f42009-09-09 15:08:12 +00003099
Richard Smith55ce3522012-06-25 20:30:08 +00003100 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003101 }
Mike Stump11289f42009-09-09 15:08:12 +00003102
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003103 default:
Richard Smith55ce3522012-06-25 20:30:08 +00003104 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003105 }
3106}
3107
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003108Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003109 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003110 .Case("scanf", FST_Scanf)
3111 .Cases("printf", "printf0", FST_Printf)
3112 .Cases("NSString", "CFString", FST_NSString)
3113 .Case("strftime", FST_Strftime)
3114 .Case("strfmon", FST_Strfmon)
3115 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003116 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00003117 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003118 .Default(FST_Unknown);
3119}
3120
Jordan Rose3e0ec582012-07-19 18:10:23 +00003121/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00003122/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003123/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003124bool Sema::CheckFormatArguments(const FormatAttr *Format,
3125 ArrayRef<const Expr *> Args,
3126 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003127 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003128 SourceLocation Loc, SourceRange Range,
3129 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00003130 FormatStringInfo FSI;
3131 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003132 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00003133 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00003134 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003135 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003136}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003137
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003138bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003139 bool HasVAListArg, unsigned format_idx,
3140 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003141 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003142 SourceLocation Loc, SourceRange Range,
3143 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003144 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003145 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003146 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00003147 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003148 }
Mike Stump11289f42009-09-09 15:08:12 +00003149
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003150 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003151
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003152 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00003153 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003154 // Dynamically generated format strings are difficult to
3155 // automatically vet at compile time. Requiring that format strings
3156 // are string literals: (1) permits the checking of format strings by
3157 // the compiler and thereby (2) can practically remove the source of
3158 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00003159
Mike Stump11289f42009-09-09 15:08:12 +00003160 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00003161 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00003162 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00003163 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003164 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00003165 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3166 format_idx, firstDataArg, Type, CallType,
3167 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003168 if (CT != SLCT_NotALiteral)
3169 // Literal format string found, check done!
3170 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00003171
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003172 // Strftime is particular as it always uses a single 'time' argument,
3173 // so it is safe to pass a non-literal string.
3174 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00003175 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003176
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003177 // Do not emit diag when the string param is a macro expansion and the
3178 // format is either NSString or CFString. This is a hack to prevent
3179 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3180 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00003181 if (Type == FST_NSString &&
3182 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00003183 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003184
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003185 // If there are no arguments specified, warn with -Wformat-security, otherwise
3186 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00003187 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003188 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003189 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003190 << OrigFormatExpr->getSourceRange();
3191 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003192 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003193 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003194 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00003195 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003196}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003197
Ted Kremenekab278de2010-01-28 23:39:18 +00003198namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00003199class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3200protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00003201 Sema &S;
3202 const StringLiteral *FExpr;
3203 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003204 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00003205 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00003206 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00003207 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003208 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00003209 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00003210 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00003211 bool usesPositionalArgs;
3212 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003213 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00003214 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00003215 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003216public:
Ted Kremenek02087932010-07-16 02:11:22 +00003217 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003218 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003219 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003220 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003221 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003222 Sema::VariadicCallType callType,
3223 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00003224 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003225 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3226 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003227 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00003228 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00003229 inFunctionCall(inFunctionCall), CallType(callType),
3230 CheckedVarArgs(CheckedVarArgs) {
3231 CoveredArgs.resize(numDataArgs);
3232 CoveredArgs.reset();
3233 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003234
Ted Kremenek019d2242010-01-29 01:50:07 +00003235 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003236
Ted Kremenek02087932010-07-16 02:11:22 +00003237 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003238 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003239
Jordan Rose92303592012-09-08 04:00:03 +00003240 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003241 const analyze_format_string::FormatSpecifier &FS,
3242 const analyze_format_string::ConversionSpecifier &CS,
3243 const char *startSpecifier, unsigned specifierLen,
3244 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00003245
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003246 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003247 const analyze_format_string::FormatSpecifier &FS,
3248 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003249
3250 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003251 const analyze_format_string::ConversionSpecifier &CS,
3252 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003253
Craig Toppere14c0f82014-03-12 04:55:44 +00003254 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003255
Craig Toppere14c0f82014-03-12 04:55:44 +00003256 void HandleInvalidPosition(const char *startSpecifier,
3257 unsigned specifierLen,
3258 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003259
Craig Toppere14c0f82014-03-12 04:55:44 +00003260 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003261
Craig Toppere14c0f82014-03-12 04:55:44 +00003262 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003263
Richard Trieu03cf7b72011-10-28 00:41:25 +00003264 template <typename Range>
3265 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3266 const Expr *ArgumentExpr,
3267 PartialDiagnostic PDiag,
3268 SourceLocation StringLoc,
3269 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003270 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003271
Ted Kremenek02087932010-07-16 02:11:22 +00003272protected:
Ted Kremenekce815422010-07-19 21:25:57 +00003273 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3274 const char *startSpec,
3275 unsigned specifierLen,
3276 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003277
3278 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
3279 const char *startSpec,
3280 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003281
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003282 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00003283 CharSourceRange getSpecifierRange(const char *startSpecifier,
3284 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00003285 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003286
Ted Kremenek5739de72010-01-29 01:06:55 +00003287 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003288
3289 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
3290 const analyze_format_string::ConversionSpecifier &CS,
3291 const char *startSpecifier, unsigned specifierLen,
3292 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003293
3294 template <typename Range>
3295 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3296 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003297 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00003298};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003299}
Ted Kremenekab278de2010-01-28 23:39:18 +00003300
Ted Kremenek02087932010-07-16 02:11:22 +00003301SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00003302 return OrigFormatExpr->getSourceRange();
3303}
3304
Ted Kremenek02087932010-07-16 02:11:22 +00003305CharSourceRange CheckFormatHandler::
3306getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00003307 SourceLocation Start = getLocationOfByte(startSpecifier);
3308 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3309
3310 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003311 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00003312
3313 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003314}
3315
Ted Kremenek02087932010-07-16 02:11:22 +00003316SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003317 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00003318}
3319
Ted Kremenek02087932010-07-16 02:11:22 +00003320void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
3321 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00003322 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
3323 getLocationOfByte(startSpecifier),
3324 /*IsStringLocation*/true,
3325 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00003326}
3327
Jordan Rose92303592012-09-08 04:00:03 +00003328void CheckFormatHandler::HandleInvalidLengthModifier(
3329 const analyze_format_string::FormatSpecifier &FS,
3330 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00003331 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00003332 using namespace analyze_format_string;
3333
3334 const LengthModifier &LM = FS.getLengthModifier();
3335 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3336
3337 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003338 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00003339 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003340 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003341 getLocationOfByte(LM.getStart()),
3342 /*IsStringLocation*/true,
3343 getSpecifierRange(startSpecifier, specifierLen));
3344
3345 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3346 << FixedLM->toString()
3347 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3348
3349 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003350 FixItHint Hint;
3351 if (DiagID == diag::warn_format_nonsensical_length)
3352 Hint = FixItHint::CreateRemoval(LMRange);
3353
3354 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003355 getLocationOfByte(LM.getStart()),
3356 /*IsStringLocation*/true,
3357 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00003358 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00003359 }
3360}
3361
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003362void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00003363 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003364 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003365 using namespace analyze_format_string;
3366
3367 const LengthModifier &LM = FS.getLengthModifier();
3368 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3369
3370 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003371 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00003372 if (FixedLM) {
3373 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3374 << LM.toString() << 0,
3375 getLocationOfByte(LM.getStart()),
3376 /*IsStringLocation*/true,
3377 getSpecifierRange(startSpecifier, specifierLen));
3378
3379 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3380 << FixedLM->toString()
3381 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3382
3383 } else {
3384 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3385 << LM.toString() << 0,
3386 getLocationOfByte(LM.getStart()),
3387 /*IsStringLocation*/true,
3388 getSpecifierRange(startSpecifier, specifierLen));
3389 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003390}
3391
3392void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3393 const analyze_format_string::ConversionSpecifier &CS,
3394 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00003395 using namespace analyze_format_string;
3396
3397 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00003398 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00003399 if (FixedCS) {
3400 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3401 << CS.toString() << /*conversion specifier*/1,
3402 getLocationOfByte(CS.getStart()),
3403 /*IsStringLocation*/true,
3404 getSpecifierRange(startSpecifier, specifierLen));
3405
3406 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3407 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3408 << FixedCS->toString()
3409 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3410 } else {
3411 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3412 << CS.toString() << /*conversion specifier*/1,
3413 getLocationOfByte(CS.getStart()),
3414 /*IsStringLocation*/true,
3415 getSpecifierRange(startSpecifier, specifierLen));
3416 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003417}
3418
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003419void CheckFormatHandler::HandlePosition(const char *startPos,
3420 unsigned posLen) {
3421 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3422 getLocationOfByte(startPos),
3423 /*IsStringLocation*/true,
3424 getSpecifierRange(startPos, posLen));
3425}
3426
Ted Kremenekd1668192010-02-27 01:41:03 +00003427void
Ted Kremenek02087932010-07-16 02:11:22 +00003428CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3429 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003430 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3431 << (unsigned) p,
3432 getLocationOfByte(startPos), /*IsStringLocation*/true,
3433 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003434}
3435
Ted Kremenek02087932010-07-16 02:11:22 +00003436void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003437 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003438 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3439 getLocationOfByte(startPos),
3440 /*IsStringLocation*/true,
3441 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003442}
3443
Ted Kremenek02087932010-07-16 02:11:22 +00003444void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003445 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003446 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003447 EmitFormatDiagnostic(
3448 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3449 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3450 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003451 }
Ted Kremenek02087932010-07-16 02:11:22 +00003452}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003453
Jordan Rose58bbe422012-07-19 18:10:08 +00003454// Note that this may return NULL if there was an error parsing or building
3455// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003456const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003457 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003458}
3459
3460void CheckFormatHandler::DoneProcessing() {
3461 // Does the number of data arguments exceed the number of
3462 // format conversions in the format string?
3463 if (!HasVAListArg) {
3464 // Find any arguments that weren't covered.
3465 CoveredArgs.flip();
3466 signed notCoveredArg = CoveredArgs.find_first();
3467 if (notCoveredArg >= 0) {
3468 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00003469 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3470 SourceLocation Loc = E->getLocStart();
3471 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3472 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3473 Loc, /*IsStringLocation*/false,
3474 getFormatStringRange());
3475 }
Bob Wilson23cd4342012-05-03 19:47:19 +00003476 }
Ted Kremenek02087932010-07-16 02:11:22 +00003477 }
3478 }
3479}
3480
Ted Kremenekce815422010-07-19 21:25:57 +00003481bool
3482CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3483 SourceLocation Loc,
3484 const char *startSpec,
3485 unsigned specifierLen,
3486 const char *csStart,
3487 unsigned csLen) {
3488
3489 bool keepGoing = true;
3490 if (argIndex < NumDataArgs) {
3491 // Consider the argument coverered, even though the specifier doesn't
3492 // make sense.
3493 CoveredArgs.set(argIndex);
3494 }
3495 else {
3496 // If argIndex exceeds the number of data arguments we
3497 // don't issue a warning because that is just a cascade of warnings (and
3498 // they may have intended '%%' anyway). We don't want to continue processing
3499 // the format string after this point, however, as we will like just get
3500 // gibberish when trying to match arguments.
3501 keepGoing = false;
3502 }
3503
Richard Trieu03cf7b72011-10-28 00:41:25 +00003504 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3505 << StringRef(csStart, csLen),
3506 Loc, /*IsStringLocation*/true,
3507 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003508
3509 return keepGoing;
3510}
3511
Richard Trieu03cf7b72011-10-28 00:41:25 +00003512void
3513CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3514 const char *startSpec,
3515 unsigned specifierLen) {
3516 EmitFormatDiagnostic(
3517 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3518 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3519}
3520
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003521bool
3522CheckFormatHandler::CheckNumArgs(
3523 const analyze_format_string::FormatSpecifier &FS,
3524 const analyze_format_string::ConversionSpecifier &CS,
3525 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3526
3527 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003528 PartialDiagnostic PDiag = FS.usesPositionalArg()
3529 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3530 << (argIndex+1) << NumDataArgs)
3531 : S.PDiag(diag::warn_printf_insufficient_data_args);
3532 EmitFormatDiagnostic(
3533 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3534 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003535 return false;
3536 }
3537 return true;
3538}
3539
Richard Trieu03cf7b72011-10-28 00:41:25 +00003540template<typename Range>
3541void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3542 SourceLocation Loc,
3543 bool IsStringLocation,
3544 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003545 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003546 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003547 Loc, IsStringLocation, StringRange, FixIt);
3548}
3549
3550/// \brief If the format string is not within the funcion call, emit a note
3551/// so that the function call and string are in diagnostic messages.
3552///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003553/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003554/// call and only one diagnostic message will be produced. Otherwise, an
3555/// extra note will be emitted pointing to location of the format string.
3556///
3557/// \param ArgumentExpr the expression that is passed as the format string
3558/// argument in the function call. Used for getting locations when two
3559/// diagnostics are emitted.
3560///
3561/// \param PDiag the callee should already have provided any strings for the
3562/// diagnostic message. This function only adds locations and fixits
3563/// to diagnostics.
3564///
3565/// \param Loc primary location for diagnostic. If two diagnostics are
3566/// required, one will be at Loc and a new SourceLocation will be created for
3567/// the other one.
3568///
3569/// \param IsStringLocation if true, Loc points to the format string should be
3570/// used for the note. Otherwise, Loc points to the argument list and will
3571/// be used with PDiag.
3572///
3573/// \param StringRange some or all of the string to highlight. This is
3574/// templated so it can accept either a CharSourceRange or a SourceRange.
3575///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003576/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003577template<typename Range>
3578void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3579 const Expr *ArgumentExpr,
3580 PartialDiagnostic PDiag,
3581 SourceLocation Loc,
3582 bool IsStringLocation,
3583 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003584 ArrayRef<FixItHint> FixIt) {
3585 if (InFunctionCall) {
3586 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3587 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003588 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00003589 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003590 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3591 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003592
3593 const Sema::SemaDiagnosticBuilder &Note =
3594 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3595 diag::note_format_string_defined);
3596
3597 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003598 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003599 }
3600}
3601
Ted Kremenek02087932010-07-16 02:11:22 +00003602//===--- CHECK: Printf format string checking ------------------------------===//
3603
3604namespace {
3605class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003606 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00003607public:
3608 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3609 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003610 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003611 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003612 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003613 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003614 Sema::VariadicCallType CallType,
3615 llvm::SmallBitVector &CheckedVarArgs)
3616 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3617 numDataArgs, beg, hasVAListArg, Args,
3618 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3619 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003620 {}
3621
Craig Toppere14c0f82014-03-12 04:55:44 +00003622
Ted Kremenek02087932010-07-16 02:11:22 +00003623 bool HandleInvalidPrintfConversionSpecifier(
3624 const analyze_printf::PrintfSpecifier &FS,
3625 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003626 unsigned specifierLen) override;
3627
Ted Kremenek02087932010-07-16 02:11:22 +00003628 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3629 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003630 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003631 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3632 const char *StartSpecifier,
3633 unsigned SpecifierLen,
3634 const Expr *E);
3635
Ted Kremenek02087932010-07-16 02:11:22 +00003636 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3637 const char *startSpecifier, unsigned specifierLen);
3638 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3639 const analyze_printf::OptionalAmount &Amt,
3640 unsigned type,
3641 const char *startSpecifier, unsigned specifierLen);
3642 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3643 const analyze_printf::OptionalFlag &flag,
3644 const char *startSpecifier, unsigned specifierLen);
3645 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3646 const analyze_printf::OptionalFlag &ignoredFlag,
3647 const analyze_printf::OptionalFlag &flag,
3648 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003649 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003650 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00003651
3652 void HandleEmptyObjCModifierFlag(const char *startFlag,
3653 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003654
Ted Kremenek2b417712015-07-02 05:39:16 +00003655 void HandleInvalidObjCModifierFlag(const char *startFlag,
3656 unsigned flagLen) override;
3657
3658 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
3659 const char *flagsEnd,
3660 const char *conversionPosition)
3661 override;
3662};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003663}
Ted Kremenek02087932010-07-16 02:11:22 +00003664
3665bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3666 const analyze_printf::PrintfSpecifier &FS,
3667 const char *startSpecifier,
3668 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003669 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003670 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003671
Ted Kremenekce815422010-07-19 21:25:57 +00003672 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3673 getLocationOfByte(CS.getStart()),
3674 startSpecifier, specifierLen,
3675 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003676}
3677
Ted Kremenek02087932010-07-16 02:11:22 +00003678bool CheckPrintfHandler::HandleAmount(
3679 const analyze_format_string::OptionalAmount &Amt,
3680 unsigned k, const char *startSpecifier,
3681 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003682
3683 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003684 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003685 unsigned argIndex = Amt.getArgIndex();
3686 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003687 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3688 << k,
3689 getLocationOfByte(Amt.getStart()),
3690 /*IsStringLocation*/true,
3691 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003692 // Don't do any more checking. We will just emit
3693 // spurious errors.
3694 return false;
3695 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003696
Ted Kremenek5739de72010-01-29 01:06:55 +00003697 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00003698 // Although not in conformance with C99, we also allow the argument to be
3699 // an 'unsigned int' as that is a reasonably safe case. GCC also
3700 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003701 CoveredArgs.set(argIndex);
3702 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003703 if (!Arg)
3704 return false;
3705
Ted Kremenek5739de72010-01-29 01:06:55 +00003706 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003707
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003708 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3709 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003710
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003711 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003712 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003713 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003714 << T << Arg->getSourceRange(),
3715 getLocationOfByte(Amt.getStart()),
3716 /*IsStringLocation*/true,
3717 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003718 // Don't do any more checking. We will just emit
3719 // spurious errors.
3720 return false;
3721 }
3722 }
3723 }
3724 return true;
3725}
Ted Kremenek5739de72010-01-29 01:06:55 +00003726
Tom Careb49ec692010-06-17 19:00:27 +00003727void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003728 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003729 const analyze_printf::OptionalAmount &Amt,
3730 unsigned type,
3731 const char *startSpecifier,
3732 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003733 const analyze_printf::PrintfConversionSpecifier &CS =
3734 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003735
Richard Trieu03cf7b72011-10-28 00:41:25 +00003736 FixItHint fixit =
3737 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3738 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3739 Amt.getConstantLength()))
3740 : FixItHint();
3741
3742 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3743 << type << CS.toString(),
3744 getLocationOfByte(Amt.getStart()),
3745 /*IsStringLocation*/true,
3746 getSpecifierRange(startSpecifier, specifierLen),
3747 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003748}
3749
Ted Kremenek02087932010-07-16 02:11:22 +00003750void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003751 const analyze_printf::OptionalFlag &flag,
3752 const char *startSpecifier,
3753 unsigned specifierLen) {
3754 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003755 const analyze_printf::PrintfConversionSpecifier &CS =
3756 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003757 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3758 << flag.toString() << CS.toString(),
3759 getLocationOfByte(flag.getPosition()),
3760 /*IsStringLocation*/true,
3761 getSpecifierRange(startSpecifier, specifierLen),
3762 FixItHint::CreateRemoval(
3763 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003764}
3765
3766void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003767 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003768 const analyze_printf::OptionalFlag &ignoredFlag,
3769 const analyze_printf::OptionalFlag &flag,
3770 const char *startSpecifier,
3771 unsigned specifierLen) {
3772 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003773 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3774 << ignoredFlag.toString() << flag.toString(),
3775 getLocationOfByte(ignoredFlag.getPosition()),
3776 /*IsStringLocation*/true,
3777 getSpecifierRange(startSpecifier, specifierLen),
3778 FixItHint::CreateRemoval(
3779 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003780}
3781
Ted Kremenek2b417712015-07-02 05:39:16 +00003782// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3783// bool IsStringLocation, Range StringRange,
3784// ArrayRef<FixItHint> Fixit = None);
3785
3786void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
3787 unsigned flagLen) {
3788 // Warn about an empty flag.
3789 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
3790 getLocationOfByte(startFlag),
3791 /*IsStringLocation*/true,
3792 getSpecifierRange(startFlag, flagLen));
3793}
3794
3795void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
3796 unsigned flagLen) {
3797 // Warn about an invalid flag.
3798 auto Range = getSpecifierRange(startFlag, flagLen);
3799 StringRef flag(startFlag, flagLen);
3800 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
3801 getLocationOfByte(startFlag),
3802 /*IsStringLocation*/true,
3803 Range, FixItHint::CreateRemoval(Range));
3804}
3805
3806void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
3807 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
3808 // Warn about using '[...]' without a '@' conversion.
3809 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
3810 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
3811 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
3812 getLocationOfByte(conversionPosition),
3813 /*IsStringLocation*/true,
3814 Range, FixItHint::CreateRemoval(Range));
3815}
3816
Richard Smith55ce3522012-06-25 20:30:08 +00003817// Determines if the specified is a C++ class or struct containing
3818// a member with the specified name and kind (e.g. a CXXMethodDecl named
3819// "c_str()").
3820template<typename MemberKind>
3821static llvm::SmallPtrSet<MemberKind*, 1>
3822CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3823 const RecordType *RT = Ty->getAs<RecordType>();
3824 llvm::SmallPtrSet<MemberKind*, 1> Results;
3825
3826 if (!RT)
3827 return Results;
3828 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003829 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003830 return Results;
3831
Alp Tokerb6cc5922014-05-03 03:45:55 +00003832 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003833 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003834 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003835
3836 // We just need to include all members of the right kind turned up by the
3837 // filter, at this point.
3838 if (S.LookupQualifiedName(R, RT->getDecl()))
3839 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3840 NamedDecl *decl = (*I)->getUnderlyingDecl();
3841 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3842 Results.insert(FK);
3843 }
3844 return Results;
3845}
3846
Richard Smith2868a732014-02-28 01:36:39 +00003847/// Check if we could call '.c_str()' on an object.
3848///
3849/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3850/// allow the call, or if it would be ambiguous).
3851bool Sema::hasCStrMethod(const Expr *E) {
3852 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3853 MethodSet Results =
3854 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3855 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3856 MI != ME; ++MI)
3857 if ((*MI)->getMinRequiredArguments() == 0)
3858 return true;
3859 return false;
3860}
3861
Richard Smith55ce3522012-06-25 20:30:08 +00003862// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003863// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003864// Returns true when a c_str() conversion method is found.
3865bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003866 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003867 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3868
3869 MethodSet Results =
3870 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3871
3872 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3873 MI != ME; ++MI) {
3874 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003875 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003876 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003877 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003878 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003879 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3880 << "c_str()"
3881 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3882 return true;
3883 }
3884 }
3885
3886 return false;
3887}
3888
Ted Kremenekab278de2010-01-28 23:39:18 +00003889bool
Ted Kremenek02087932010-07-16 02:11:22 +00003890CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003891 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003892 const char *startSpecifier,
3893 unsigned specifierLen) {
3894
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003895 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003896 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003897 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003898
Ted Kremenek6cd69422010-07-19 22:01:06 +00003899 if (FS.consumesDataArgument()) {
3900 if (atFirstArg) {
3901 atFirstArg = false;
3902 usesPositionalArgs = FS.usesPositionalArg();
3903 }
3904 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003905 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3906 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003907 return false;
3908 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003909 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003910
Ted Kremenekd1668192010-02-27 01:41:03 +00003911 // First check if the field width, precision, and conversion specifier
3912 // have matching data arguments.
3913 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3914 startSpecifier, specifierLen)) {
3915 return false;
3916 }
3917
3918 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3919 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003920 return false;
3921 }
3922
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003923 if (!CS.consumesDataArgument()) {
3924 // FIXME: Technically specifying a precision or field width here
3925 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003926 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003927 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003928
Ted Kremenek4a49d982010-02-26 19:18:41 +00003929 // Consume the argument.
3930 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003931 if (argIndex < NumDataArgs) {
3932 // The check to see if the argIndex is valid will come later.
3933 // We set the bit here because we may exit early from this
3934 // function if we encounter some other error.
3935 CoveredArgs.set(argIndex);
3936 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003937
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003938 // FreeBSD kernel extensions.
3939 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
3940 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
3941 // We need at least two arguments.
3942 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
3943 return false;
3944
3945 // Claim the second argument.
3946 CoveredArgs.set(argIndex + 1);
3947
3948 // Type check the first argument (int for %b, pointer for %D)
3949 const Expr *Ex = getDataArg(argIndex);
3950 const analyze_printf::ArgType &AT =
3951 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
3952 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
3953 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
3954 EmitFormatDiagnostic(
3955 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3956 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3957 << false << Ex->getSourceRange(),
3958 Ex->getLocStart(), /*IsStringLocation*/false,
3959 getSpecifierRange(startSpecifier, specifierLen));
3960
3961 // Type check the second argument (char * for both %b and %D)
3962 Ex = getDataArg(argIndex + 1);
3963 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
3964 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
3965 EmitFormatDiagnostic(
3966 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3967 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
3968 << false << Ex->getSourceRange(),
3969 Ex->getLocStart(), /*IsStringLocation*/false,
3970 getSpecifierRange(startSpecifier, specifierLen));
3971
3972 return true;
3973 }
3974
Ted Kremenek4a49d982010-02-26 19:18:41 +00003975 // Check for using an Objective-C specific conversion specifier
3976 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003977 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003978 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3979 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003980 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003981
Tom Careb49ec692010-06-17 19:00:27 +00003982 // Check for invalid use of field width
3983 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003984 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003985 startSpecifier, specifierLen);
3986 }
3987
3988 // Check for invalid use of precision
3989 if (!FS.hasValidPrecision()) {
3990 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3991 startSpecifier, specifierLen);
3992 }
3993
3994 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003995 if (!FS.hasValidThousandsGroupingPrefix())
3996 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003997 if (!FS.hasValidLeadingZeros())
3998 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3999 if (!FS.hasValidPlusPrefix())
4000 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00004001 if (!FS.hasValidSpacePrefix())
4002 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004003 if (!FS.hasValidAlternativeForm())
4004 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4005 if (!FS.hasValidLeftJustified())
4006 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4007
4008 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00004009 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4010 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4011 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004012 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4013 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4014 startSpecifier, specifierLen);
4015
4016 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004017 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004018 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4019 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004020 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004021 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004022 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004023 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4024 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00004025
Jordan Rose92303592012-09-08 04:00:03 +00004026 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4027 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4028
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004029 // The remaining checks depend on the data arguments.
4030 if (HasVAListArg)
4031 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004032
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004033 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004034 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004035
Jordan Rose58bbe422012-07-19 18:10:08 +00004036 const Expr *Arg = getDataArg(argIndex);
4037 if (!Arg)
4038 return true;
4039
4040 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00004041}
4042
Jordan Roseaee34382012-09-05 22:56:26 +00004043static bool requiresParensToAddCast(const Expr *E) {
4044 // FIXME: We should have a general way to reason about operator
4045 // precedence and whether parens are actually needed here.
4046 // Take care of a few common cases where they aren't.
4047 const Expr *Inside = E->IgnoreImpCasts();
4048 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
4049 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
4050
4051 switch (Inside->getStmtClass()) {
4052 case Stmt::ArraySubscriptExprClass:
4053 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004054 case Stmt::CharacterLiteralClass:
4055 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004056 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004057 case Stmt::FloatingLiteralClass:
4058 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004059 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004060 case Stmt::ObjCArrayLiteralClass:
4061 case Stmt::ObjCBoolLiteralExprClass:
4062 case Stmt::ObjCBoxedExprClass:
4063 case Stmt::ObjCDictionaryLiteralClass:
4064 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004065 case Stmt::ObjCIvarRefExprClass:
4066 case Stmt::ObjCMessageExprClass:
4067 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004068 case Stmt::ObjCStringLiteralClass:
4069 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004070 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004071 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004072 case Stmt::UnaryOperatorClass:
4073 return false;
4074 default:
4075 return true;
4076 }
4077}
4078
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004079static std::pair<QualType, StringRef>
4080shouldNotPrintDirectly(const ASTContext &Context,
4081 QualType IntendedTy,
4082 const Expr *E) {
4083 // Use a 'while' to peel off layers of typedefs.
4084 QualType TyTy = IntendedTy;
4085 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
4086 StringRef Name = UserTy->getDecl()->getName();
4087 QualType CastTy = llvm::StringSwitch<QualType>(Name)
4088 .Case("NSInteger", Context.LongTy)
4089 .Case("NSUInteger", Context.UnsignedLongTy)
4090 .Case("SInt32", Context.IntTy)
4091 .Case("UInt32", Context.UnsignedIntTy)
4092 .Default(QualType());
4093
4094 if (!CastTy.isNull())
4095 return std::make_pair(CastTy, Name);
4096
4097 TyTy = UserTy->desugar();
4098 }
4099
4100 // Strip parens if necessary.
4101 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4102 return shouldNotPrintDirectly(Context,
4103 PE->getSubExpr()->getType(),
4104 PE->getSubExpr());
4105
4106 // If this is a conditional expression, then its result type is constructed
4107 // via usual arithmetic conversions and thus there might be no necessary
4108 // typedef sugar there. Recurse to operands to check for NSInteger &
4109 // Co. usage condition.
4110 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4111 QualType TrueTy, FalseTy;
4112 StringRef TrueName, FalseName;
4113
4114 std::tie(TrueTy, TrueName) =
4115 shouldNotPrintDirectly(Context,
4116 CO->getTrueExpr()->getType(),
4117 CO->getTrueExpr());
4118 std::tie(FalseTy, FalseName) =
4119 shouldNotPrintDirectly(Context,
4120 CO->getFalseExpr()->getType(),
4121 CO->getFalseExpr());
4122
4123 if (TrueTy == FalseTy)
4124 return std::make_pair(TrueTy, TrueName);
4125 else if (TrueTy.isNull())
4126 return std::make_pair(FalseTy, FalseName);
4127 else if (FalseTy.isNull())
4128 return std::make_pair(TrueTy, TrueName);
4129 }
4130
4131 return std::make_pair(QualType(), StringRef());
4132}
4133
Richard Smith55ce3522012-06-25 20:30:08 +00004134bool
4135CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4136 const char *StartSpecifier,
4137 unsigned SpecifierLen,
4138 const Expr *E) {
4139 using namespace analyze_format_string;
4140 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004141 // Now type check the data expression that matches the
4142 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004143 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4144 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00004145 if (!AT.isValid())
4146 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00004147
Jordan Rose598ec092012-12-05 18:44:40 +00004148 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00004149 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4150 ExprTy = TET->getUnderlyingExpr()->getType();
4151 }
4152
Seth Cantrellb4802962015-03-04 03:12:10 +00004153 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4154
4155 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00004156 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004157 }
Jordan Rose98709982012-06-04 22:48:57 +00004158
Jordan Rose22b74712012-09-05 22:56:19 +00004159 // Look through argument promotions for our error message's reported type.
4160 // This includes the integral and floating promotions, but excludes array
4161 // and function pointer decay; seeing that an argument intended to be a
4162 // string has type 'char [6]' is probably more confusing than 'char *'.
4163 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4164 if (ICE->getCastKind() == CK_IntegralCast ||
4165 ICE->getCastKind() == CK_FloatingCast) {
4166 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00004167 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00004168
4169 // Check if we didn't match because of an implicit cast from a 'char'
4170 // or 'short' to an 'int'. This is done because printf is a varargs
4171 // function.
4172 if (ICE->getType() == S.Context.IntTy ||
4173 ICE->getType() == S.Context.UnsignedIntTy) {
4174 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00004175 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00004176 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00004177 }
Jordan Rose98709982012-06-04 22:48:57 +00004178 }
Jordan Rose598ec092012-12-05 18:44:40 +00004179 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4180 // Special case for 'a', which has type 'int' in C.
4181 // Note, however, that we do /not/ want to treat multibyte constants like
4182 // 'MooV' as characters! This form is deprecated but still exists.
4183 if (ExprTy == S.Context.IntTy)
4184 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4185 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00004186 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004187
Jordan Rosebc53ed12014-05-31 04:12:14 +00004188 // Look through enums to their underlying type.
4189 bool IsEnum = false;
4190 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4191 ExprTy = EnumTy->getDecl()->getIntegerType();
4192 IsEnum = true;
4193 }
4194
Jordan Rose0e5badd2012-12-05 18:44:49 +00004195 // %C in an Objective-C context prints a unichar, not a wchar_t.
4196 // If the argument is an integer of some kind, believe the %C and suggest
4197 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00004198 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004199 if (ObjCContext &&
4200 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4201 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4202 !ExprTy->isCharType()) {
4203 // 'unichar' is defined as a typedef of unsigned short, but we should
4204 // prefer using the typedef if it is visible.
4205 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00004206
4207 // While we are here, check if the value is an IntegerLiteral that happens
4208 // to be within the valid range.
4209 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4210 const llvm::APInt &V = IL->getValue();
4211 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4212 return true;
4213 }
4214
Jordan Rose0e5badd2012-12-05 18:44:49 +00004215 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4216 Sema::LookupOrdinaryName);
4217 if (S.LookupName(Result, S.getCurScope())) {
4218 NamedDecl *ND = Result.getFoundDecl();
4219 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4220 if (TD->getUnderlyingType() == IntendedTy)
4221 IntendedTy = S.Context.getTypedefType(TD);
4222 }
4223 }
4224 }
4225
4226 // Special-case some of Darwin's platform-independence types by suggesting
4227 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004228 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00004229 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004230 QualType CastTy;
4231 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
4232 if (!CastTy.isNull()) {
4233 IntendedTy = CastTy;
4234 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00004235 }
4236 }
4237
Jordan Rose22b74712012-09-05 22:56:19 +00004238 // We may be able to offer a FixItHint if it is a supported type.
4239 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00004240 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00004241 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004242
Jordan Rose22b74712012-09-05 22:56:19 +00004243 if (success) {
4244 // Get the fix string from the fixed format specifier
4245 SmallString<16> buf;
4246 llvm::raw_svector_ostream os(buf);
4247 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004248
Jordan Roseaee34382012-09-05 22:56:26 +00004249 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4250
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004251 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00004252 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4253 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4254 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4255 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00004256 // In this case, the specifier is wrong and should be changed to match
4257 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00004258 EmitFormatDiagnostic(S.PDiag(diag)
4259 << AT.getRepresentativeTypeName(S.Context)
4260 << IntendedTy << IsEnum << E->getSourceRange(),
4261 E->getLocStart(),
4262 /*IsStringLocation*/ false, SpecRange,
4263 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00004264
4265 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00004266 // The canonical type for formatting this value is different from the
4267 // actual type of the expression. (This occurs, for example, with Darwin's
4268 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
4269 // should be printed as 'long' for 64-bit compatibility.)
4270 // Rather than emitting a normal format/argument mismatch, we want to
4271 // add a cast to the recommended type (and correct the format string
4272 // if necessary).
4273 SmallString<16> CastBuf;
4274 llvm::raw_svector_ostream CastFix(CastBuf);
4275 CastFix << "(";
4276 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
4277 CastFix << ")";
4278
4279 SmallVector<FixItHint,4> Hints;
4280 if (!AT.matchesType(S.Context, IntendedTy))
4281 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
4282
4283 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
4284 // If there's already a cast present, just replace it.
4285 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
4286 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
4287
4288 } else if (!requiresParensToAddCast(E)) {
4289 // If the expression has high enough precedence,
4290 // just write the C-style cast.
4291 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4292 CastFix.str()));
4293 } else {
4294 // Otherwise, add parens around the expression as well as the cast.
4295 CastFix << "(";
4296 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4297 CastFix.str()));
4298
Alp Tokerb6cc5922014-05-03 03:45:55 +00004299 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00004300 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
4301 }
4302
Jordan Rose0e5badd2012-12-05 18:44:49 +00004303 if (ShouldNotPrintDirectly) {
4304 // The expression has a type that should not be printed directly.
4305 // We extract the name from the typedef because we don't want to show
4306 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004307 StringRef Name;
4308 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
4309 Name = TypedefTy->getDecl()->getName();
4310 else
4311 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004312 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00004313 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004314 << E->getSourceRange(),
4315 E->getLocStart(), /*IsStringLocation=*/false,
4316 SpecRange, Hints);
4317 } else {
4318 // In this case, the expression could be printed using a different
4319 // specifier, but we've decided that the specifier is probably correct
4320 // and we should cast instead. Just use the normal warning message.
4321 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00004322 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4323 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004324 << E->getSourceRange(),
4325 E->getLocStart(), /*IsStringLocation*/false,
4326 SpecRange, Hints);
4327 }
Jordan Roseaee34382012-09-05 22:56:26 +00004328 }
Jordan Rose22b74712012-09-05 22:56:19 +00004329 } else {
4330 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
4331 SpecifierLen);
4332 // Since the warning for passing non-POD types to variadic functions
4333 // was deferred until now, we emit a warning for non-POD
4334 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00004335 switch (S.isValidVarArgType(ExprTy)) {
4336 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00004337 case Sema::VAK_ValidInCXX11: {
4338 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4339 if (match == analyze_printf::ArgType::NoMatchPedantic) {
4340 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4341 }
Richard Smithd7293d72013-08-05 18:49:43 +00004342
Seth Cantrellb4802962015-03-04 03:12:10 +00004343 EmitFormatDiagnostic(
4344 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4345 << IsEnum << CSR << E->getSourceRange(),
4346 E->getLocStart(), /*IsStringLocation*/ false, CSR);
4347 break;
4348 }
Richard Smithd7293d72013-08-05 18:49:43 +00004349 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00004350 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00004351 EmitFormatDiagnostic(
4352 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004353 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00004354 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00004355 << CallType
4356 << AT.getRepresentativeTypeName(S.Context)
4357 << CSR
4358 << E->getSourceRange(),
4359 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00004360 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00004361 break;
4362
4363 case Sema::VAK_Invalid:
4364 if (ExprTy->isObjCObjectType())
4365 EmitFormatDiagnostic(
4366 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4367 << S.getLangOpts().CPlusPlus11
4368 << ExprTy
4369 << CallType
4370 << AT.getRepresentativeTypeName(S.Context)
4371 << CSR
4372 << E->getSourceRange(),
4373 E->getLocStart(), /*IsStringLocation*/false, CSR);
4374 else
4375 // FIXME: If this is an initializer list, suggest removing the braces
4376 // or inserting a cast to the target type.
4377 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4378 << isa<InitListExpr>(E) << ExprTy << CallType
4379 << AT.getRepresentativeTypeName(S.Context)
4380 << E->getSourceRange();
4381 break;
4382 }
4383
4384 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4385 "format string specifier index out of range");
4386 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004387 }
4388
Ted Kremenekab278de2010-01-28 23:39:18 +00004389 return true;
4390}
4391
Ted Kremenek02087932010-07-16 02:11:22 +00004392//===--- CHECK: Scanf format string checking ------------------------------===//
4393
4394namespace {
4395class CheckScanfHandler : public CheckFormatHandler {
4396public:
4397 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4398 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004399 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004400 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004401 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004402 Sema::VariadicCallType CallType,
4403 llvm::SmallBitVector &CheckedVarArgs)
4404 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4405 numDataArgs, beg, hasVAListArg,
4406 Args, formatIdx, inFunctionCall, CallType,
4407 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004408 {}
Ted Kremenek02087932010-07-16 02:11:22 +00004409
4410 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4411 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004412 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00004413
4414 bool HandleInvalidScanfConversionSpecifier(
4415 const analyze_scanf::ScanfSpecifier &FS,
4416 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004417 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004418
Craig Toppere14c0f82014-03-12 04:55:44 +00004419 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00004420};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004421}
Ted Kremenekab278de2010-01-28 23:39:18 +00004422
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004423void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4424 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004425 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4426 getLocationOfByte(end), /*IsStringLocation*/true,
4427 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004428}
4429
Ted Kremenekce815422010-07-19 21:25:57 +00004430bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4431 const analyze_scanf::ScanfSpecifier &FS,
4432 const char *startSpecifier,
4433 unsigned specifierLen) {
4434
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004435 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004436 FS.getConversionSpecifier();
4437
4438 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4439 getLocationOfByte(CS.getStart()),
4440 startSpecifier, specifierLen,
4441 CS.getStart(), CS.getLength());
4442}
4443
Ted Kremenek02087932010-07-16 02:11:22 +00004444bool CheckScanfHandler::HandleScanfSpecifier(
4445 const analyze_scanf::ScanfSpecifier &FS,
4446 const char *startSpecifier,
4447 unsigned specifierLen) {
4448
4449 using namespace analyze_scanf;
4450 using namespace analyze_format_string;
4451
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004452 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004453
Ted Kremenek6cd69422010-07-19 22:01:06 +00004454 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4455 // be used to decide if we are using positional arguments consistently.
4456 if (FS.consumesDataArgument()) {
4457 if (atFirstArg) {
4458 atFirstArg = false;
4459 usesPositionalArgs = FS.usesPositionalArg();
4460 }
4461 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004462 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4463 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004464 return false;
4465 }
Ted Kremenek02087932010-07-16 02:11:22 +00004466 }
4467
4468 // Check if the field with is non-zero.
4469 const OptionalAmount &Amt = FS.getFieldWidth();
4470 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4471 if (Amt.getConstantAmount() == 0) {
4472 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4473 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00004474 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4475 getLocationOfByte(Amt.getStart()),
4476 /*IsStringLocation*/true, R,
4477 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00004478 }
4479 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004480
Ted Kremenek02087932010-07-16 02:11:22 +00004481 if (!FS.consumesDataArgument()) {
4482 // FIXME: Technically specifying a precision or field width here
4483 // makes no sense. Worth issuing a warning at some point.
4484 return true;
4485 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004486
Ted Kremenek02087932010-07-16 02:11:22 +00004487 // Consume the argument.
4488 unsigned argIndex = FS.getArgIndex();
4489 if (argIndex < NumDataArgs) {
4490 // The check to see if the argIndex is valid will come later.
4491 // We set the bit here because we may exit early from this
4492 // function if we encounter some other error.
4493 CoveredArgs.set(argIndex);
4494 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004495
Ted Kremenek4407ea42010-07-20 20:04:47 +00004496 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004497 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004498 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4499 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004500 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004501 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004502 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004503 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4504 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004505
Jordan Rose92303592012-09-08 04:00:03 +00004506 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4507 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4508
Ted Kremenek02087932010-07-16 02:11:22 +00004509 // The remaining checks depend on the data arguments.
4510 if (HasVAListArg)
4511 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004512
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004513 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004514 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00004515
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004516 // Check that the argument type matches the format specifier.
4517 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004518 if (!Ex)
4519 return true;
4520
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004521 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00004522
4523 if (!AT.isValid()) {
4524 return true;
4525 }
4526
Seth Cantrellb4802962015-03-04 03:12:10 +00004527 analyze_format_string::ArgType::MatchKind match =
4528 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00004529 if (match == analyze_format_string::ArgType::Match) {
4530 return true;
4531 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004532
Seth Cantrell79340072015-03-04 05:58:08 +00004533 ScanfSpecifier fixedFS = FS;
4534 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4535 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004536
Seth Cantrell79340072015-03-04 05:58:08 +00004537 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4538 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4539 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4540 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004541
Seth Cantrell79340072015-03-04 05:58:08 +00004542 if (success) {
4543 // Get the fix string from the fixed format specifier.
4544 SmallString<128> buf;
4545 llvm::raw_svector_ostream os(buf);
4546 fixedFS.toString(os);
4547
4548 EmitFormatDiagnostic(
4549 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4550 << Ex->getType() << false << Ex->getSourceRange(),
4551 Ex->getLocStart(),
4552 /*IsStringLocation*/ false,
4553 getSpecifierRange(startSpecifier, specifierLen),
4554 FixItHint::CreateReplacement(
4555 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4556 } else {
4557 EmitFormatDiagnostic(S.PDiag(diag)
4558 << AT.getRepresentativeTypeName(S.Context)
4559 << Ex->getType() << false << Ex->getSourceRange(),
4560 Ex->getLocStart(),
4561 /*IsStringLocation*/ false,
4562 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004563 }
4564
Ted Kremenek02087932010-07-16 02:11:22 +00004565 return true;
4566}
4567
4568void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00004569 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004570 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004571 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004572 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00004573 bool inFunctionCall, VariadicCallType CallType,
4574 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004575
Ted Kremenekab278de2010-01-28 23:39:18 +00004576 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004577 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004578 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004579 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004580 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4581 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004582 return;
4583 }
Ted Kremenek02087932010-07-16 02:11:22 +00004584
Ted Kremenekab278de2010-01-28 23:39:18 +00004585 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004586 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004587 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004588 // Account for cases where the string literal is truncated in a declaration.
4589 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4590 assert(T && "String literal not of constant array type!");
4591 size_t TypeSize = T->getSize().getZExtValue();
4592 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004593 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004594
4595 // Emit a warning if the string literal is truncated and does not contain an
4596 // embedded null character.
4597 if (TypeSize <= StrRef.size() &&
4598 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4599 CheckFormatHandler::EmitFormatDiagnostic(
4600 *this, inFunctionCall, Args[format_idx],
4601 PDiag(diag::warn_printf_format_string_not_null_terminated),
4602 FExpr->getLocStart(),
4603 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4604 return;
4605 }
4606
Ted Kremenekab278de2010-01-28 23:39:18 +00004607 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004608 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004609 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004610 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004611 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4612 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004613 return;
4614 }
Ted Kremenek02087932010-07-16 02:11:22 +00004615
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004616 if (Type == FST_Printf || Type == FST_NSString ||
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004617 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek02087932010-07-16 02:11:22 +00004618 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004619 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004620 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004621 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004622
Hans Wennborg23926bd2011-12-15 10:25:47 +00004623 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004624 getLangOpts(),
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004625 Context.getTargetInfo(),
4626 Type == FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00004627 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004628 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004629 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004630 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004631 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004632
Hans Wennborg23926bd2011-12-15 10:25:47 +00004633 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004634 getLangOpts(),
4635 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004636 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004637 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004638}
4639
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004640bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4641 // Str - The format string. NOTE: this is NOT null-terminated!
4642 StringRef StrRef = FExpr->getString();
4643 const char *Str = StrRef.data();
4644 // Account for cases where the string literal is truncated in a declaration.
4645 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4646 assert(T && "String literal not of constant array type!");
4647 size_t TypeSize = T->getSize().getZExtValue();
4648 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4649 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4650 getLangOpts(),
4651 Context.getTargetInfo());
4652}
4653
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004654//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4655
4656// Returns the related absolute value function that is larger, of 0 if one
4657// does not exist.
4658static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4659 switch (AbsFunction) {
4660 default:
4661 return 0;
4662
4663 case Builtin::BI__builtin_abs:
4664 return Builtin::BI__builtin_labs;
4665 case Builtin::BI__builtin_labs:
4666 return Builtin::BI__builtin_llabs;
4667 case Builtin::BI__builtin_llabs:
4668 return 0;
4669
4670 case Builtin::BI__builtin_fabsf:
4671 return Builtin::BI__builtin_fabs;
4672 case Builtin::BI__builtin_fabs:
4673 return Builtin::BI__builtin_fabsl;
4674 case Builtin::BI__builtin_fabsl:
4675 return 0;
4676
4677 case Builtin::BI__builtin_cabsf:
4678 return Builtin::BI__builtin_cabs;
4679 case Builtin::BI__builtin_cabs:
4680 return Builtin::BI__builtin_cabsl;
4681 case Builtin::BI__builtin_cabsl:
4682 return 0;
4683
4684 case Builtin::BIabs:
4685 return Builtin::BIlabs;
4686 case Builtin::BIlabs:
4687 return Builtin::BIllabs;
4688 case Builtin::BIllabs:
4689 return 0;
4690
4691 case Builtin::BIfabsf:
4692 return Builtin::BIfabs;
4693 case Builtin::BIfabs:
4694 return Builtin::BIfabsl;
4695 case Builtin::BIfabsl:
4696 return 0;
4697
4698 case Builtin::BIcabsf:
4699 return Builtin::BIcabs;
4700 case Builtin::BIcabs:
4701 return Builtin::BIcabsl;
4702 case Builtin::BIcabsl:
4703 return 0;
4704 }
4705}
4706
4707// Returns the argument type of the absolute value function.
4708static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4709 unsigned AbsType) {
4710 if (AbsType == 0)
4711 return QualType();
4712
4713 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4714 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4715 if (Error != ASTContext::GE_None)
4716 return QualType();
4717
4718 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4719 if (!FT)
4720 return QualType();
4721
4722 if (FT->getNumParams() != 1)
4723 return QualType();
4724
4725 return FT->getParamType(0);
4726}
4727
4728// Returns the best absolute value function, or zero, based on type and
4729// current absolute value function.
4730static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4731 unsigned AbsFunctionKind) {
4732 unsigned BestKind = 0;
4733 uint64_t ArgSize = Context.getTypeSize(ArgType);
4734 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4735 Kind = getLargerAbsoluteValueFunction(Kind)) {
4736 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4737 if (Context.getTypeSize(ParamType) >= ArgSize) {
4738 if (BestKind == 0)
4739 BestKind = Kind;
4740 else if (Context.hasSameType(ParamType, ArgType)) {
4741 BestKind = Kind;
4742 break;
4743 }
4744 }
4745 }
4746 return BestKind;
4747}
4748
4749enum AbsoluteValueKind {
4750 AVK_Integer,
4751 AVK_Floating,
4752 AVK_Complex
4753};
4754
4755static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4756 if (T->isIntegralOrEnumerationType())
4757 return AVK_Integer;
4758 if (T->isRealFloatingType())
4759 return AVK_Floating;
4760 if (T->isAnyComplexType())
4761 return AVK_Complex;
4762
4763 llvm_unreachable("Type not integer, floating, or complex");
4764}
4765
4766// Changes the absolute value function to a different type. Preserves whether
4767// the function is a builtin.
4768static unsigned changeAbsFunction(unsigned AbsKind,
4769 AbsoluteValueKind ValueKind) {
4770 switch (ValueKind) {
4771 case AVK_Integer:
4772 switch (AbsKind) {
4773 default:
4774 return 0;
4775 case Builtin::BI__builtin_fabsf:
4776 case Builtin::BI__builtin_fabs:
4777 case Builtin::BI__builtin_fabsl:
4778 case Builtin::BI__builtin_cabsf:
4779 case Builtin::BI__builtin_cabs:
4780 case Builtin::BI__builtin_cabsl:
4781 return Builtin::BI__builtin_abs;
4782 case Builtin::BIfabsf:
4783 case Builtin::BIfabs:
4784 case Builtin::BIfabsl:
4785 case Builtin::BIcabsf:
4786 case Builtin::BIcabs:
4787 case Builtin::BIcabsl:
4788 return Builtin::BIabs;
4789 }
4790 case AVK_Floating:
4791 switch (AbsKind) {
4792 default:
4793 return 0;
4794 case Builtin::BI__builtin_abs:
4795 case Builtin::BI__builtin_labs:
4796 case Builtin::BI__builtin_llabs:
4797 case Builtin::BI__builtin_cabsf:
4798 case Builtin::BI__builtin_cabs:
4799 case Builtin::BI__builtin_cabsl:
4800 return Builtin::BI__builtin_fabsf;
4801 case Builtin::BIabs:
4802 case Builtin::BIlabs:
4803 case Builtin::BIllabs:
4804 case Builtin::BIcabsf:
4805 case Builtin::BIcabs:
4806 case Builtin::BIcabsl:
4807 return Builtin::BIfabsf;
4808 }
4809 case AVK_Complex:
4810 switch (AbsKind) {
4811 default:
4812 return 0;
4813 case Builtin::BI__builtin_abs:
4814 case Builtin::BI__builtin_labs:
4815 case Builtin::BI__builtin_llabs:
4816 case Builtin::BI__builtin_fabsf:
4817 case Builtin::BI__builtin_fabs:
4818 case Builtin::BI__builtin_fabsl:
4819 return Builtin::BI__builtin_cabsf;
4820 case Builtin::BIabs:
4821 case Builtin::BIlabs:
4822 case Builtin::BIllabs:
4823 case Builtin::BIfabsf:
4824 case Builtin::BIfabs:
4825 case Builtin::BIfabsl:
4826 return Builtin::BIcabsf;
4827 }
4828 }
4829 llvm_unreachable("Unable to convert function");
4830}
4831
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004832static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004833 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4834 if (!FnInfo)
4835 return 0;
4836
4837 switch (FDecl->getBuiltinID()) {
4838 default:
4839 return 0;
4840 case Builtin::BI__builtin_abs:
4841 case Builtin::BI__builtin_fabs:
4842 case Builtin::BI__builtin_fabsf:
4843 case Builtin::BI__builtin_fabsl:
4844 case Builtin::BI__builtin_labs:
4845 case Builtin::BI__builtin_llabs:
4846 case Builtin::BI__builtin_cabs:
4847 case Builtin::BI__builtin_cabsf:
4848 case Builtin::BI__builtin_cabsl:
4849 case Builtin::BIabs:
4850 case Builtin::BIlabs:
4851 case Builtin::BIllabs:
4852 case Builtin::BIfabs:
4853 case Builtin::BIfabsf:
4854 case Builtin::BIfabsl:
4855 case Builtin::BIcabs:
4856 case Builtin::BIcabsf:
4857 case Builtin::BIcabsl:
4858 return FDecl->getBuiltinID();
4859 }
4860 llvm_unreachable("Unknown Builtin type");
4861}
4862
4863// If the replacement is valid, emit a note with replacement function.
4864// Additionally, suggest including the proper header if not already included.
4865static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004866 unsigned AbsKind, QualType ArgType) {
4867 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004868 const char *HeaderName = nullptr;
4869 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004870 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4871 FunctionName = "std::abs";
4872 if (ArgType->isIntegralOrEnumerationType()) {
4873 HeaderName = "cstdlib";
4874 } else if (ArgType->isRealFloatingType()) {
4875 HeaderName = "cmath";
4876 } else {
4877 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004878 }
Richard Trieubeffb832014-04-15 23:47:53 +00004879
4880 // Lookup all std::abs
4881 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004882 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004883 R.suppressDiagnostics();
4884 S.LookupQualifiedName(R, Std);
4885
4886 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004887 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004888 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4889 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4890 } else {
4891 FDecl = dyn_cast<FunctionDecl>(I);
4892 }
4893 if (!FDecl)
4894 continue;
4895
4896 // Found std::abs(), check that they are the right ones.
4897 if (FDecl->getNumParams() != 1)
4898 continue;
4899
4900 // Check that the parameter type can handle the argument.
4901 QualType ParamType = FDecl->getParamDecl(0)->getType();
4902 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4903 S.Context.getTypeSize(ArgType) <=
4904 S.Context.getTypeSize(ParamType)) {
4905 // Found a function, don't need the header hint.
4906 EmitHeaderHint = false;
4907 break;
4908 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004909 }
Richard Trieubeffb832014-04-15 23:47:53 +00004910 }
4911 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00004912 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00004913 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4914
4915 if (HeaderName) {
4916 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4917 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4918 R.suppressDiagnostics();
4919 S.LookupName(R, S.getCurScope());
4920
4921 if (R.isSingleResult()) {
4922 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4923 if (FD && FD->getBuiltinID() == AbsKind) {
4924 EmitHeaderHint = false;
4925 } else {
4926 return;
4927 }
4928 } else if (!R.empty()) {
4929 return;
4930 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004931 }
4932 }
4933
4934 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00004935 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004936
Richard Trieubeffb832014-04-15 23:47:53 +00004937 if (!HeaderName)
4938 return;
4939
4940 if (!EmitHeaderHint)
4941 return;
4942
Alp Toker5d96e0a2014-07-11 20:53:51 +00004943 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4944 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00004945}
4946
4947static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4948 if (!FDecl)
4949 return false;
4950
4951 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4952 return false;
4953
4954 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4955
4956 while (ND && ND->isInlineNamespace()) {
4957 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004958 }
Richard Trieubeffb832014-04-15 23:47:53 +00004959
4960 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4961 return false;
4962
4963 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4964 return false;
4965
4966 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004967}
4968
4969// Warn when using the wrong abs() function.
4970void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4971 const FunctionDecl *FDecl,
4972 IdentifierInfo *FnInfo) {
4973 if (Call->getNumArgs() != 1)
4974 return;
4975
4976 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00004977 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4978 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004979 return;
4980
4981 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4982 QualType ParamType = Call->getArg(0)->getType();
4983
Alp Toker5d96e0a2014-07-11 20:53:51 +00004984 // Unsigned types cannot be negative. Suggest removing the absolute value
4985 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004986 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00004987 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00004988 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004989 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4990 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00004991 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004992 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4993 return;
4994 }
4995
Richard Trieubeffb832014-04-15 23:47:53 +00004996 // std::abs has overloads which prevent most of the absolute value problems
4997 // from occurring.
4998 if (IsStdAbs)
4999 return;
5000
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005001 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5002 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5003
5004 // The argument and parameter are the same kind. Check if they are the right
5005 // size.
5006 if (ArgValueKind == ParamValueKind) {
5007 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
5008 return;
5009
5010 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
5011 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
5012 << FDecl << ArgType << ParamType;
5013
5014 if (NewAbsKind == 0)
5015 return;
5016
5017 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005018 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005019 return;
5020 }
5021
5022 // ArgValueKind != ParamValueKind
5023 // The wrong type of absolute value function was used. Attempt to find the
5024 // proper one.
5025 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
5026 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
5027 if (NewAbsKind == 0)
5028 return;
5029
5030 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
5031 << FDecl << ParamValueKind << ArgValueKind;
5032
5033 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005034 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005035 return;
5036}
5037
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005038//===--- CHECK: Standard memory functions ---------------------------------===//
5039
Nico Weber0e6daef2013-12-26 23:38:39 +00005040/// \brief Takes the expression passed to the size_t parameter of functions
5041/// such as memcmp, strncat, etc and warns if it's a comparison.
5042///
5043/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
5044static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
5045 IdentifierInfo *FnName,
5046 SourceLocation FnLoc,
5047 SourceLocation RParenLoc) {
5048 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
5049 if (!Size)
5050 return false;
5051
5052 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
5053 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
5054 return false;
5055
Nico Weber0e6daef2013-12-26 23:38:39 +00005056 SourceRange SizeRange = Size->getSourceRange();
5057 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
5058 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00005059 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005060 << FnName << FixItHint::CreateInsertion(
5061 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00005062 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00005063 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00005064 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00005065 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
5066 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00005067
5068 return true;
5069}
5070
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005071/// \brief Determine whether the given type is or contains a dynamic class type
5072/// (e.g., whether it has a vtable).
5073static const CXXRecordDecl *getContainedDynamicClass(QualType T,
5074 bool &IsContained) {
5075 // Look through array types while ignoring qualifiers.
5076 const Type *Ty = T->getBaseElementTypeUnsafe();
5077 IsContained = false;
5078
5079 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5080 RD = RD ? RD->getDefinition() : nullptr;
5081 if (!RD)
5082 return nullptr;
5083
5084 if (RD->isDynamicClass())
5085 return RD;
5086
5087 // Check all the fields. If any bases were dynamic, the class is dynamic.
5088 // It's impossible for a class to transitively contain itself by value, so
5089 // infinite recursion is impossible.
5090 for (auto *FD : RD->fields()) {
5091 bool SubContained;
5092 if (const CXXRecordDecl *ContainedRD =
5093 getContainedDynamicClass(FD->getType(), SubContained)) {
5094 IsContained = true;
5095 return ContainedRD;
5096 }
5097 }
5098
5099 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00005100}
5101
Chandler Carruth889ed862011-06-21 23:04:20 +00005102/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005103/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00005104static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00005105 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005106 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5107 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5108 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005109
Craig Topperc3ec1492014-05-26 06:22:03 +00005110 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005111}
5112
Chandler Carruth889ed862011-06-21 23:04:20 +00005113/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00005114static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005115 if (const UnaryExprOrTypeTraitExpr *SizeOf =
5116 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5117 if (SizeOf->getKind() == clang::UETT_SizeOf)
5118 return SizeOf->getTypeOfArgument();
5119
5120 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00005121}
5122
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005123/// \brief Check for dangerous or invalid arguments to memset().
5124///
Chandler Carruthac687262011-06-03 06:23:57 +00005125/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005126/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5127/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005128///
5129/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005130void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00005131 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005132 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00005133 assert(BId != 0);
5134
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005135 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00005136 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00005137 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00005138 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005139 return;
5140
Anna Zaks22122702012-01-17 00:37:07 +00005141 unsigned LastArg = (BId == Builtin::BImemset ||
5142 BId == Builtin::BIstrndup ? 1 : 2);
5143 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00005144 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005145
Nico Weber0e6daef2013-12-26 23:38:39 +00005146 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5147 Call->getLocStart(), Call->getRParenLoc()))
5148 return;
5149
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005150 // We have special checking when the length is a sizeof expression.
5151 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5152 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5153 llvm::FoldingSetNodeID SizeOfArgID;
5154
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005155 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5156 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005157 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005158
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005159 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00005160 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005161 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00005162 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00005163
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005164 // Never warn about void type pointers. This can be used to suppress
5165 // false positives.
5166 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005167 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005168
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005169 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5170 // actually comparing the expressions for equality. Because computing the
5171 // expression IDs can be expensive, we only do this if the diagnostic is
5172 // enabled.
5173 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005174 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5175 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005176 // We only compute IDs for expressions if the warning is enabled, and
5177 // cache the sizeof arg's ID.
5178 if (SizeOfArgID == llvm::FoldingSetNodeID())
5179 SizeOfArg->Profile(SizeOfArgID, Context, true);
5180 llvm::FoldingSetNodeID DestID;
5181 Dest->Profile(DestID, Context, true);
5182 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00005183 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5184 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005185 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00005186 StringRef ReadableName = FnName->getName();
5187
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005188 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00005189 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005190 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00005191 if (!PointeeTy->isIncompleteType() &&
5192 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005193 ActionIdx = 2; // If the pointee's size is sizeof(char),
5194 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00005195
5196 // If the function is defined as a builtin macro, do not show macro
5197 // expansion.
5198 SourceLocation SL = SizeOfArg->getExprLoc();
5199 SourceRange DSR = Dest->getSourceRange();
5200 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005201 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00005202
5203 if (SM.isMacroArgExpansion(SL)) {
5204 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5205 SL = SM.getSpellingLoc(SL);
5206 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5207 SM.getSpellingLoc(DSR.getEnd()));
5208 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5209 SM.getSpellingLoc(SSR.getEnd()));
5210 }
5211
Anna Zaksd08d9152012-05-30 23:14:52 +00005212 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005213 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00005214 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00005215 << PointeeTy
5216 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00005217 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00005218 << SSR);
5219 DiagRuntimeBehavior(SL, SizeOfArg,
5220 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5221 << ActionIdx
5222 << SSR);
5223
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005224 break;
5225 }
5226 }
5227
5228 // Also check for cases where the sizeof argument is the exact same
5229 // type as the memory argument, and where it points to a user-defined
5230 // record type.
5231 if (SizeOfArgTy != QualType()) {
5232 if (PointeeTy->isRecordType() &&
5233 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
5234 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
5235 PDiag(diag::warn_sizeof_pointer_type_memaccess)
5236 << FnName << SizeOfArgTy << ArgIdx
5237 << PointeeTy << Dest->getSourceRange()
5238 << LenExpr->getSourceRange());
5239 break;
5240 }
Nico Weberc5e73862011-06-14 16:14:58 +00005241 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00005242 } else if (DestTy->isArrayType()) {
5243 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00005244 }
Nico Weberc5e73862011-06-14 16:14:58 +00005245
Nico Weberc44b35e2015-03-21 17:37:46 +00005246 if (PointeeTy == QualType())
5247 continue;
Anna Zaks22122702012-01-17 00:37:07 +00005248
Nico Weberc44b35e2015-03-21 17:37:46 +00005249 // Always complain about dynamic classes.
5250 bool IsContained;
5251 if (const CXXRecordDecl *ContainedRD =
5252 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00005253
Nico Weberc44b35e2015-03-21 17:37:46 +00005254 unsigned OperationType = 0;
5255 // "overwritten" if we're warning about the destination for any call
5256 // but memcmp; otherwise a verb appropriate to the call.
5257 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
5258 if (BId == Builtin::BImemcpy)
5259 OperationType = 1;
5260 else if(BId == Builtin::BImemmove)
5261 OperationType = 2;
5262 else if (BId == Builtin::BImemcmp)
5263 OperationType = 3;
5264 }
5265
John McCall31168b02011-06-15 23:02:42 +00005266 DiagRuntimeBehavior(
5267 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00005268 PDiag(diag::warn_dyn_class_memaccess)
5269 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
5270 << FnName << IsContained << ContainedRD << OperationType
5271 << Call->getCallee()->getSourceRange());
5272 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
5273 BId != Builtin::BImemset)
5274 DiagRuntimeBehavior(
5275 Dest->getExprLoc(), Dest,
5276 PDiag(diag::warn_arc_object_memaccess)
5277 << ArgIdx << FnName << PointeeTy
5278 << Call->getCallee()->getSourceRange());
5279 else
5280 continue;
5281
5282 DiagRuntimeBehavior(
5283 Dest->getExprLoc(), Dest,
5284 PDiag(diag::note_bad_memaccess_silence)
5285 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
5286 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005287 }
Nico Weberc44b35e2015-03-21 17:37:46 +00005288
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005289}
5290
Ted Kremenek6865f772011-08-18 20:55:45 +00005291// A little helper routine: ignore addition and subtraction of integer literals.
5292// This intentionally does not ignore all integer constant expressions because
5293// we don't want to remove sizeof().
5294static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
5295 Ex = Ex->IgnoreParenCasts();
5296
5297 for (;;) {
5298 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
5299 if (!BO || !BO->isAdditiveOp())
5300 break;
5301
5302 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
5303 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
5304
5305 if (isa<IntegerLiteral>(RHS))
5306 Ex = LHS;
5307 else if (isa<IntegerLiteral>(LHS))
5308 Ex = RHS;
5309 else
5310 break;
5311 }
5312
5313 return Ex;
5314}
5315
Anna Zaks13b08572012-08-08 21:42:23 +00005316static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
5317 ASTContext &Context) {
5318 // Only handle constant-sized or VLAs, but not flexible members.
5319 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
5320 // Only issue the FIXIT for arrays of size > 1.
5321 if (CAT->getSize().getSExtValue() <= 1)
5322 return false;
5323 } else if (!Ty->isVariableArrayType()) {
5324 return false;
5325 }
5326 return true;
5327}
5328
Ted Kremenek6865f772011-08-18 20:55:45 +00005329// Warn if the user has made the 'size' argument to strlcpy or strlcat
5330// be the size of the source, instead of the destination.
5331void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
5332 IdentifierInfo *FnName) {
5333
5334 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00005335 unsigned NumArgs = Call->getNumArgs();
5336 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00005337 return;
5338
5339 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5340 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00005341 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00005342
5343 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5344 Call->getLocStart(), Call->getRParenLoc()))
5345 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00005346
5347 // Look for 'strlcpy(dst, x, sizeof(x))'
5348 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5349 CompareWithSrc = Ex;
5350 else {
5351 // Look for 'strlcpy(dst, x, strlen(x))'
5352 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00005353 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5354 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00005355 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5356 }
5357 }
5358
5359 if (!CompareWithSrc)
5360 return;
5361
5362 // Determine if the argument to sizeof/strlen is equal to the source
5363 // argument. In principle there's all kinds of things you could do
5364 // here, for instance creating an == expression and evaluating it with
5365 // EvaluateAsBooleanCondition, but this uses a more direct technique:
5366 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5367 if (!SrcArgDRE)
5368 return;
5369
5370 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5371 if (!CompareWithSrcDRE ||
5372 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5373 return;
5374
5375 const Expr *OriginalSizeArg = Call->getArg(2);
5376 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5377 << OriginalSizeArg->getSourceRange() << FnName;
5378
5379 // Output a FIXIT hint if the destination is an array (rather than a
5380 // pointer to an array). This could be enhanced to handle some
5381 // pointers if we know the actual size, like if DstArg is 'array+2'
5382 // we could say 'sizeof(array)-2'.
5383 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00005384 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00005385 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005386
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005387 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005388 llvm::raw_svector_ostream OS(sizeString);
5389 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005390 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00005391 OS << ")";
5392
5393 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5394 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5395 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00005396}
5397
Anna Zaks314cd092012-02-01 19:08:57 +00005398/// Check if two expressions refer to the same declaration.
5399static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5400 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5401 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5402 return D1->getDecl() == D2->getDecl();
5403 return false;
5404}
5405
5406static const Expr *getStrlenExprArg(const Expr *E) {
5407 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5408 const FunctionDecl *FD = CE->getDirectCallee();
5409 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00005410 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005411 return CE->getArg(0)->IgnoreParenCasts();
5412 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005413 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005414}
5415
5416// Warn on anti-patterns as the 'size' argument to strncat.
5417// The correct size argument should look like following:
5418// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5419void Sema::CheckStrncatArguments(const CallExpr *CE,
5420 IdentifierInfo *FnName) {
5421 // Don't crash if the user has the wrong number of arguments.
5422 if (CE->getNumArgs() < 3)
5423 return;
5424 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5425 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5426 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5427
Nico Weber0e6daef2013-12-26 23:38:39 +00005428 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5429 CE->getRParenLoc()))
5430 return;
5431
Anna Zaks314cd092012-02-01 19:08:57 +00005432 // Identify common expressions, which are wrongly used as the size argument
5433 // to strncat and may lead to buffer overflows.
5434 unsigned PatternType = 0;
5435 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5436 // - sizeof(dst)
5437 if (referToTheSameDecl(SizeOfArg, DstArg))
5438 PatternType = 1;
5439 // - sizeof(src)
5440 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5441 PatternType = 2;
5442 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5443 if (BE->getOpcode() == BO_Sub) {
5444 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5445 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5446 // - sizeof(dst) - strlen(dst)
5447 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5448 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5449 PatternType = 1;
5450 // - sizeof(src) - (anything)
5451 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5452 PatternType = 2;
5453 }
5454 }
5455
5456 if (PatternType == 0)
5457 return;
5458
Anna Zaks5069aa32012-02-03 01:27:37 +00005459 // Generate the diagnostic.
5460 SourceLocation SL = LenArg->getLocStart();
5461 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005462 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00005463
5464 // If the function is defined as a builtin macro, do not show macro expansion.
5465 if (SM.isMacroArgExpansion(SL)) {
5466 SL = SM.getSpellingLoc(SL);
5467 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5468 SM.getSpellingLoc(SR.getEnd()));
5469 }
5470
Anna Zaks13b08572012-08-08 21:42:23 +00005471 // Check if the destination is an array (rather than a pointer to an array).
5472 QualType DstTy = DstArg->getType();
5473 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5474 Context);
5475 if (!isKnownSizeArray) {
5476 if (PatternType == 1)
5477 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5478 else
5479 Diag(SL, diag::warn_strncat_src_size) << SR;
5480 return;
5481 }
5482
Anna Zaks314cd092012-02-01 19:08:57 +00005483 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00005484 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005485 else
Anna Zaks5069aa32012-02-03 01:27:37 +00005486 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005487
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005488 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00005489 llvm::raw_svector_ostream OS(sizeString);
5490 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005491 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005492 OS << ") - ";
5493 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005494 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005495 OS << ") - 1";
5496
Anna Zaks5069aa32012-02-03 01:27:37 +00005497 Diag(SL, diag::note_strncat_wrong_size)
5498 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005499}
5500
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005501//===--- CHECK: Return Address of Stack Variable --------------------------===//
5502
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005503static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5504 Decl *ParentDecl);
5505static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5506 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005507
5508/// CheckReturnStackAddr - Check if a return statement returns the address
5509/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005510static void
5511CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5512 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005513
Craig Topperc3ec1492014-05-26 06:22:03 +00005514 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005515 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005516
5517 // Perform checking for returned stack addresses, local blocks,
5518 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005519 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005520 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005521 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005522 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005523 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005524 }
5525
Craig Topperc3ec1492014-05-26 06:22:03 +00005526 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005527 return; // Nothing suspicious was found.
5528
5529 SourceLocation diagLoc;
5530 SourceRange diagRange;
5531 if (refVars.empty()) {
5532 diagLoc = stackE->getLocStart();
5533 diagRange = stackE->getSourceRange();
5534 } else {
5535 // We followed through a reference variable. 'stackE' contains the
5536 // problematic expression but we will warn at the return statement pointing
5537 // at the reference variable. We will later display the "trail" of
5538 // reference variables using notes.
5539 diagLoc = refVars[0]->getLocStart();
5540 diagRange = refVars[0]->getSourceRange();
5541 }
5542
5543 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005544 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005545 : diag::warn_ret_stack_addr)
5546 << DR->getDecl()->getDeclName() << diagRange;
5547 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005548 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005549 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005550 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005551 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005552 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
5553 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005554 << diagRange;
5555 }
5556
5557 // Display the "trail" of reference variables that we followed until we
5558 // found the problematic expression using notes.
5559 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5560 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5561 // If this var binds to another reference var, show the range of the next
5562 // var, otherwise the var binds to the problematic expression, in which case
5563 // show the range of the expression.
5564 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5565 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005566 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5567 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005568 }
5569}
5570
5571/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5572/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005573/// to a location on the stack, a local block, an address of a label, or a
5574/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005575/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005576/// encounter a subexpression that (1) clearly does not lead to one of the
5577/// above problematic expressions (2) is something we cannot determine leads to
5578/// a problematic expression based on such local checking.
5579///
5580/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5581/// the expression that they point to. Such variables are added to the
5582/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005583///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005584/// EvalAddr processes expressions that are pointers that are used as
5585/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005586/// At the base case of the recursion is a check for the above problematic
5587/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005588///
5589/// This implementation handles:
5590///
5591/// * pointer-to-pointer casts
5592/// * implicit conversions from array references to pointers
5593/// * taking the address of fields
5594/// * arbitrary interplay between "&" and "*" operators
5595/// * pointer arithmetic from an address of a stack variable
5596/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005597static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5598 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005599 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005600 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005601
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005602 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005603 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005604 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005605 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005606 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005607
Peter Collingbourne91147592011-04-15 00:35:48 +00005608 E = E->IgnoreParens();
5609
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005610 // Our "symbolic interpreter" is just a dispatch off the currently
5611 // viewed AST node. We then recursively traverse the AST by calling
5612 // EvalAddr and EvalVal appropriately.
5613 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005614 case Stmt::DeclRefExprClass: {
5615 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5616
Richard Smith40f08eb2014-01-30 22:05:38 +00005617 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005618 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005619 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005620
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005621 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5622 // If this is a reference variable, follow through to the expression that
5623 // it points to.
5624 if (V->hasLocalStorage() &&
5625 V->getType()->isReferenceType() && V->hasInit()) {
5626 // Add the reference variable to the "trail".
5627 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005628 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005629 }
5630
Craig Topperc3ec1492014-05-26 06:22:03 +00005631 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005632 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005633
Chris Lattner934edb22007-12-28 05:31:15 +00005634 case Stmt::UnaryOperatorClass: {
5635 // The only unary operator that make sense to handle here
5636 // is AddrOf. All others don't make sense as pointers.
5637 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005638
John McCalle3027922010-08-25 11:45:40 +00005639 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005640 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005641 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005642 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005643 }
Mike Stump11289f42009-09-09 15:08:12 +00005644
Chris Lattner934edb22007-12-28 05:31:15 +00005645 case Stmt::BinaryOperatorClass: {
5646 // Handle pointer arithmetic. All other binary operators are not valid
5647 // in this context.
5648 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005649 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005650
John McCalle3027922010-08-25 11:45:40 +00005651 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005652 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005653
Chris Lattner934edb22007-12-28 05:31:15 +00005654 Expr *Base = B->getLHS();
5655
5656 // Determine which argument is the real pointer base. It could be
5657 // the RHS argument instead of the LHS.
5658 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005659
Chris Lattner934edb22007-12-28 05:31:15 +00005660 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005661 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005662 }
Steve Naroff2752a172008-09-10 19:17:48 +00005663
Chris Lattner934edb22007-12-28 05:31:15 +00005664 // For conditional operators we need to see if either the LHS or RHS are
5665 // valid DeclRefExpr*s. If one of them is valid, we return it.
5666 case Stmt::ConditionalOperatorClass: {
5667 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005668
Chris Lattner934edb22007-12-28 05:31:15 +00005669 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005670 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5671 if (Expr *LHSExpr = C->getLHS()) {
5672 // In C++, we can have a throw-expression, which has 'void' type.
5673 if (!LHSExpr->getType()->isVoidType())
5674 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005675 return LHS;
5676 }
Chris Lattner934edb22007-12-28 05:31:15 +00005677
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005678 // In C++, we can have a throw-expression, which has 'void' type.
5679 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005680 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005681
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005682 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005683 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005684
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005685 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00005686 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005687 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00005688 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005689
5690 case Stmt::AddrLabelExprClass:
5691 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00005692
John McCall28fc7092011-11-10 05:35:25 +00005693 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005694 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5695 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005696
Ted Kremenekc3b4c522008-08-07 00:49:01 +00005697 // For casts, we need to handle conversions from arrays to
5698 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00005699 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00005700 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005701 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00005702 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00005703 case Stmt::CXXStaticCastExprClass:
5704 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00005705 case Stmt::CXXConstCastExprClass:
5706 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00005707 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5708 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00005709 case CK_LValueToRValue:
5710 case CK_NoOp:
5711 case CK_BaseToDerived:
5712 case CK_DerivedToBase:
5713 case CK_UncheckedDerivedToBase:
5714 case CK_Dynamic:
5715 case CK_CPointerToObjCPointerCast:
5716 case CK_BlockPointerToObjCPointerCast:
5717 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005718 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005719
5720 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005721 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005722
Richard Trieudadefde2014-07-02 04:39:38 +00005723 case CK_BitCast:
5724 if (SubExpr->getType()->isAnyPointerType() ||
5725 SubExpr->getType()->isBlockPointerType() ||
5726 SubExpr->getType()->isObjCQualifiedIdType())
5727 return EvalAddr(SubExpr, refVars, ParentDecl);
5728 else
5729 return nullptr;
5730
Eli Friedman8195ad72012-02-23 23:04:32 +00005731 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005732 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00005733 }
Chris Lattner934edb22007-12-28 05:31:15 +00005734 }
Mike Stump11289f42009-09-09 15:08:12 +00005735
Douglas Gregorfe314812011-06-21 17:03:29 +00005736 case Stmt::MaterializeTemporaryExprClass:
5737 if (Expr *Result = EvalAddr(
5738 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005739 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005740 return Result;
5741
5742 return E;
5743
Chris Lattner934edb22007-12-28 05:31:15 +00005744 // Everything else: we simply don't reason about them.
5745 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005746 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00005747 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005748}
Mike Stump11289f42009-09-09 15:08:12 +00005749
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005750
5751/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5752/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005753static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5754 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005755do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005756 // We should only be called for evaluating non-pointer expressions, or
5757 // expressions with a pointer type that are not used as references but instead
5758 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00005759
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005760 // Our "symbolic interpreter" is just a dispatch off the currently
5761 // viewed AST node. We then recursively traverse the AST by calling
5762 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00005763
5764 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005765 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005766 case Stmt::ImplicitCastExprClass: {
5767 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00005768 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005769 E = IE->getSubExpr();
5770 continue;
5771 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005772 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00005773 }
5774
John McCall28fc7092011-11-10 05:35:25 +00005775 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005776 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005777
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005778 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005779 // When we hit a DeclRefExpr we are looking at code that refers to a
5780 // variable's name. If it's not a reference variable we check if it has
5781 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005782 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005783
Richard Smith40f08eb2014-01-30 22:05:38 +00005784 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005785 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005786 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005787
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005788 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5789 // Check if it refers to itself, e.g. "int& i = i;".
5790 if (V == ParentDecl)
5791 return DR;
5792
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005793 if (V->hasLocalStorage()) {
5794 if (!V->getType()->isReferenceType())
5795 return DR;
5796
5797 // Reference variable, follow through to the expression that
5798 // it points to.
5799 if (V->hasInit()) {
5800 // Add the reference variable to the "trail".
5801 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005802 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005803 }
5804 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005805 }
Mike Stump11289f42009-09-09 15:08:12 +00005806
Craig Topperc3ec1492014-05-26 06:22:03 +00005807 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005808 }
Mike Stump11289f42009-09-09 15:08:12 +00005809
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005810 case Stmt::UnaryOperatorClass: {
5811 // The only unary operator that make sense to handle here
5812 // is Deref. All others don't resolve to a "name." This includes
5813 // handling all sorts of rvalues passed to a unary operator.
5814 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005815
John McCalle3027922010-08-25 11:45:40 +00005816 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005817 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005818
Craig Topperc3ec1492014-05-26 06:22:03 +00005819 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005820 }
Mike Stump11289f42009-09-09 15:08:12 +00005821
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005822 case Stmt::ArraySubscriptExprClass: {
5823 // Array subscripts are potential references to data on the stack. We
5824 // retrieve the DeclRefExpr* for the array variable if it indeed
5825 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005826 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005827 }
Mike Stump11289f42009-09-09 15:08:12 +00005828
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005829 case Stmt::OMPArraySectionExprClass: {
5830 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
5831 ParentDecl);
5832 }
5833
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005834 case Stmt::ConditionalOperatorClass: {
5835 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005836 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005837 ConditionalOperator *C = cast<ConditionalOperator>(E);
5838
Anders Carlsson801c5c72007-11-30 19:04:31 +00005839 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005840 if (Expr *LHSExpr = C->getLHS()) {
5841 // In C++, we can have a throw-expression, which has 'void' type.
5842 if (!LHSExpr->getType()->isVoidType())
5843 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5844 return LHS;
5845 }
5846
5847 // In C++, we can have a throw-expression, which has 'void' type.
5848 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005849 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005850
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005851 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005852 }
Mike Stump11289f42009-09-09 15:08:12 +00005853
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005854 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005855 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005856 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005857
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005858 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005859 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005860 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005861
5862 // Check whether the member type is itself a reference, in which case
5863 // we're not going to refer to the member, but to what the member refers to.
5864 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005865 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005866
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005867 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005868 }
Mike Stump11289f42009-09-09 15:08:12 +00005869
Douglas Gregorfe314812011-06-21 17:03:29 +00005870 case Stmt::MaterializeTemporaryExprClass:
5871 if (Expr *Result = EvalVal(
5872 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005873 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005874 return Result;
5875
5876 return E;
5877
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005878 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005879 // Check that we don't return or take the address of a reference to a
5880 // temporary. This is only useful in C++.
5881 if (!E->isTypeDependent() && E->isRValue())
5882 return E;
5883
5884 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005885 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005886 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005887} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005888}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005889
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005890void
5891Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5892 SourceLocation ReturnLoc,
5893 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005894 const AttrVec *Attrs,
5895 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005896 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5897
5898 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00005899 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
5900 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00005901 CheckNonNullExpr(*this, RetValExp))
5902 Diag(ReturnLoc, diag::warn_null_ret)
5903 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00005904
5905 // C++11 [basic.stc.dynamic.allocation]p4:
5906 // If an allocation function declared with a non-throwing
5907 // exception-specification fails to allocate storage, it shall return
5908 // a null pointer. Any other allocation function that fails to allocate
5909 // storage shall indicate failure only by throwing an exception [...]
5910 if (FD) {
5911 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5912 if (Op == OO_New || Op == OO_Array_New) {
5913 const FunctionProtoType *Proto
5914 = FD->getType()->castAs<FunctionProtoType>();
5915 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5916 CheckNonNullExpr(*this, RetValExp))
5917 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5918 << FD << getLangOpts().CPlusPlus11;
5919 }
5920 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005921}
5922
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005923//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5924
5925/// Check for comparisons of floating point operands using != and ==.
5926/// Issue a warning if these are no self-comparisons, as they are not likely
5927/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00005928void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00005929 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5930 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005931
5932 // Special case: check for x == x (which is OK).
5933 // Do not emit warnings for such cases.
5934 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5935 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5936 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00005937 return;
Mike Stump11289f42009-09-09 15:08:12 +00005938
5939
Ted Kremenekeda40e22007-11-29 00:59:04 +00005940 // Special case: check for comparisons against literals that can be exactly
5941 // represented by APFloat. In such cases, do not emit a warning. This
5942 // is a heuristic: often comparison against such literals are used to
5943 // detect if a value in a variable has not changed. This clearly can
5944 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00005945 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5946 if (FLL->isExact())
5947 return;
5948 } else
5949 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5950 if (FLR->isExact())
5951 return;
Mike Stump11289f42009-09-09 15:08:12 +00005952
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005953 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00005954 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005955 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005956 return;
Mike Stump11289f42009-09-09 15:08:12 +00005957
David Blaikie1f4ff152012-07-16 20:47:22 +00005958 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005959 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005960 return;
Mike Stump11289f42009-09-09 15:08:12 +00005961
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005962 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00005963 Diag(Loc, diag::warn_floatingpoint_eq)
5964 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005965}
John McCallca01b222010-01-04 23:21:16 +00005966
John McCall70aa5392010-01-06 05:24:50 +00005967//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5968//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00005969
John McCall70aa5392010-01-06 05:24:50 +00005970namespace {
John McCallca01b222010-01-04 23:21:16 +00005971
John McCall70aa5392010-01-06 05:24:50 +00005972/// Structure recording the 'active' range of an integer-valued
5973/// expression.
5974struct IntRange {
5975 /// The number of bits active in the int.
5976 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00005977
John McCall70aa5392010-01-06 05:24:50 +00005978 /// True if the int is known not to have negative values.
5979 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00005980
John McCall70aa5392010-01-06 05:24:50 +00005981 IntRange(unsigned Width, bool NonNegative)
5982 : Width(Width), NonNegative(NonNegative)
5983 {}
John McCallca01b222010-01-04 23:21:16 +00005984
John McCall817d4af2010-11-10 23:38:19 +00005985 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00005986 static IntRange forBoolType() {
5987 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00005988 }
5989
John McCall817d4af2010-11-10 23:38:19 +00005990 /// Returns the range of an opaque value of the given integral type.
5991 static IntRange forValueOfType(ASTContext &C, QualType T) {
5992 return forValueOfCanonicalType(C,
5993 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00005994 }
5995
John McCall817d4af2010-11-10 23:38:19 +00005996 /// Returns the range of an opaque value of a canonical integral type.
5997 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00005998 assert(T->isCanonicalUnqualified());
5999
6000 if (const VectorType *VT = dyn_cast<VectorType>(T))
6001 T = VT->getElementType().getTypePtr();
6002 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6003 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006004 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6005 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00006006
David Majnemer6a426652013-06-07 22:07:20 +00006007 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00006008 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00006009 EnumDecl *Enum = ET->getDecl();
6010 if (!Enum->isCompleteDefinition())
6011 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00006012
David Majnemer6a426652013-06-07 22:07:20 +00006013 unsigned NumPositive = Enum->getNumPositiveBits();
6014 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00006015
David Majnemer6a426652013-06-07 22:07:20 +00006016 if (NumNegative == 0)
6017 return IntRange(NumPositive, true/*NonNegative*/);
6018 else
6019 return IntRange(std::max(NumPositive + 1, NumNegative),
6020 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00006021 }
John McCall70aa5392010-01-06 05:24:50 +00006022
6023 const BuiltinType *BT = cast<BuiltinType>(T);
6024 assert(BT->isInteger());
6025
6026 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6027 }
6028
John McCall817d4af2010-11-10 23:38:19 +00006029 /// Returns the "target" range of a canonical integral type, i.e.
6030 /// the range of values expressible in the type.
6031 ///
6032 /// This matches forValueOfCanonicalType except that enums have the
6033 /// full range of their type, not the range of their enumerators.
6034 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
6035 assert(T->isCanonicalUnqualified());
6036
6037 if (const VectorType *VT = dyn_cast<VectorType>(T))
6038 T = VT->getElementType().getTypePtr();
6039 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6040 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006041 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6042 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006043 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00006044 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006045
6046 const BuiltinType *BT = cast<BuiltinType>(T);
6047 assert(BT->isInteger());
6048
6049 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6050 }
6051
6052 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00006053 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00006054 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00006055 L.NonNegative && R.NonNegative);
6056 }
6057
John McCall817d4af2010-11-10 23:38:19 +00006058 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00006059 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00006060 return IntRange(std::min(L.Width, R.Width),
6061 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00006062 }
6063};
6064
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006065static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
6066 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006067 if (value.isSigned() && value.isNegative())
6068 return IntRange(value.getMinSignedBits(), false);
6069
6070 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006071 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006072
6073 // isNonNegative() just checks the sign bit without considering
6074 // signedness.
6075 return IntRange(value.getActiveBits(), true);
6076}
6077
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006078static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
6079 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006080 if (result.isInt())
6081 return GetValueRange(C, result.getInt(), MaxWidth);
6082
6083 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00006084 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6085 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6086 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6087 R = IntRange::join(R, El);
6088 }
John McCall70aa5392010-01-06 05:24:50 +00006089 return R;
6090 }
6091
6092 if (result.isComplexInt()) {
6093 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6094 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6095 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00006096 }
6097
6098 // This can happen with lossless casts to intptr_t of "based" lvalues.
6099 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00006100 // FIXME: The only reason we need to pass the type in here is to get
6101 // the sign right on this one case. It would be nice if APValue
6102 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006103 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00006104 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00006105}
John McCall70aa5392010-01-06 05:24:50 +00006106
Eli Friedmane6d33952013-07-08 20:20:06 +00006107static QualType GetExprType(Expr *E) {
6108 QualType Ty = E->getType();
6109 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6110 Ty = AtomicRHS->getValueType();
6111 return Ty;
6112}
6113
John McCall70aa5392010-01-06 05:24:50 +00006114/// Pseudo-evaluate the given integer expression, estimating the
6115/// range of values it might take.
6116///
6117/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006118static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006119 E = E->IgnoreParens();
6120
6121 // Try a full evaluation first.
6122 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006123 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00006124 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006125
6126 // I think we only want to look through implicit casts here; if the
6127 // user has an explicit widening cast, we should treat the value as
6128 // being of the new, wider type.
6129 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00006130 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00006131 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6132
Eli Friedmane6d33952013-07-08 20:20:06 +00006133 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00006134
John McCalle3027922010-08-25 11:45:40 +00006135 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00006136
John McCall70aa5392010-01-06 05:24:50 +00006137 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00006138 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00006139 return OutputTypeRange;
6140
6141 IntRange SubRange
6142 = GetExprRange(C, CE->getSubExpr(),
6143 std::min(MaxWidth, OutputTypeRange.Width));
6144
6145 // Bail out if the subexpr's range is as wide as the cast type.
6146 if (SubRange.Width >= OutputTypeRange.Width)
6147 return OutputTypeRange;
6148
6149 // Otherwise, we take the smaller width, and we're non-negative if
6150 // either the output type or the subexpr is.
6151 return IntRange(SubRange.Width,
6152 SubRange.NonNegative || OutputTypeRange.NonNegative);
6153 }
6154
6155 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6156 // If we can fold the condition, just take that operand.
6157 bool CondResult;
6158 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6159 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6160 : CO->getFalseExpr(),
6161 MaxWidth);
6162
6163 // Otherwise, conservatively merge.
6164 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6165 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6166 return IntRange::join(L, R);
6167 }
6168
6169 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6170 switch (BO->getOpcode()) {
6171
6172 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00006173 case BO_LAnd:
6174 case BO_LOr:
6175 case BO_LT:
6176 case BO_GT:
6177 case BO_LE:
6178 case BO_GE:
6179 case BO_EQ:
6180 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00006181 return IntRange::forBoolType();
6182
John McCallc3688382011-07-13 06:35:24 +00006183 // The type of the assignments is the type of the LHS, so the RHS
6184 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00006185 case BO_MulAssign:
6186 case BO_DivAssign:
6187 case BO_RemAssign:
6188 case BO_AddAssign:
6189 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00006190 case BO_XorAssign:
6191 case BO_OrAssign:
6192 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00006193 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00006194
John McCallc3688382011-07-13 06:35:24 +00006195 // Simple assignments just pass through the RHS, which will have
6196 // been coerced to the LHS type.
6197 case BO_Assign:
6198 // TODO: bitfields?
6199 return GetExprRange(C, BO->getRHS(), MaxWidth);
6200
John McCall70aa5392010-01-06 05:24:50 +00006201 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006202 case BO_PtrMemD:
6203 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00006204 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006205
John McCall2ce81ad2010-01-06 22:07:33 +00006206 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00006207 case BO_And:
6208 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00006209 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6210 GetExprRange(C, BO->getRHS(), MaxWidth));
6211
John McCall70aa5392010-01-06 05:24:50 +00006212 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00006213 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00006214 // ...except that we want to treat '1 << (blah)' as logically
6215 // positive. It's an important idiom.
6216 if (IntegerLiteral *I
6217 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6218 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006219 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00006220 return IntRange(R.Width, /*NonNegative*/ true);
6221 }
6222 }
6223 // fallthrough
6224
John McCalle3027922010-08-25 11:45:40 +00006225 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00006226 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006227
John McCall2ce81ad2010-01-06 22:07:33 +00006228 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00006229 case BO_Shr:
6230 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00006231 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6232
6233 // If the shift amount is a positive constant, drop the width by
6234 // that much.
6235 llvm::APSInt shift;
6236 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6237 shift.isNonNegative()) {
6238 unsigned zext = shift.getZExtValue();
6239 if (zext >= L.Width)
6240 L.Width = (L.NonNegative ? 0 : 1);
6241 else
6242 L.Width -= zext;
6243 }
6244
6245 return L;
6246 }
6247
6248 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00006249 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00006250 return GetExprRange(C, BO->getRHS(), MaxWidth);
6251
John McCall2ce81ad2010-01-06 22:07:33 +00006252 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00006253 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00006254 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00006255 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006256 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006257
John McCall51431812011-07-14 22:39:48 +00006258 // The width of a division result is mostly determined by the size
6259 // of the LHS.
6260 case BO_Div: {
6261 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006262 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006263 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6264
6265 // If the divisor is constant, use that.
6266 llvm::APSInt divisor;
6267 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
6268 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
6269 if (log2 >= L.Width)
6270 L.Width = (L.NonNegative ? 0 : 1);
6271 else
6272 L.Width = std::min(L.Width - log2, MaxWidth);
6273 return L;
6274 }
6275
6276 // Otherwise, just use the LHS's width.
6277 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6278 return IntRange(L.Width, L.NonNegative && R.NonNegative);
6279 }
6280
6281 // The result of a remainder can't be larger than the result of
6282 // either side.
6283 case BO_Rem: {
6284 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006285 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006286 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6287 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6288
6289 IntRange meet = IntRange::meet(L, R);
6290 meet.Width = std::min(meet.Width, MaxWidth);
6291 return meet;
6292 }
6293
6294 // The default behavior is okay for these.
6295 case BO_Mul:
6296 case BO_Add:
6297 case BO_Xor:
6298 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00006299 break;
6300 }
6301
John McCall51431812011-07-14 22:39:48 +00006302 // The default case is to treat the operation as if it were closed
6303 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00006304 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6305 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
6306 return IntRange::join(L, R);
6307 }
6308
6309 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6310 switch (UO->getOpcode()) {
6311 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00006312 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00006313 return IntRange::forBoolType();
6314
6315 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006316 case UO_Deref:
6317 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00006318 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006319
6320 default:
6321 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
6322 }
6323 }
6324
Ted Kremeneka553fbf2013-10-14 18:55:27 +00006325 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6326 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
6327
John McCalld25db7e2013-05-06 21:39:12 +00006328 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00006329 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00006330 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00006331
Eli Friedmane6d33952013-07-08 20:20:06 +00006332 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006333}
John McCall263a48b2010-01-04 23:31:57 +00006334
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006335static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006336 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00006337}
6338
John McCall263a48b2010-01-04 23:31:57 +00006339/// Checks whether the given value, which currently has the given
6340/// source semantics, has the same value when coerced through the
6341/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006342static bool IsSameFloatAfterCast(const llvm::APFloat &value,
6343 const llvm::fltSemantics &Src,
6344 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006345 llvm::APFloat truncated = value;
6346
6347 bool ignored;
6348 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6349 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6350
6351 return truncated.bitwiseIsEqual(value);
6352}
6353
6354/// Checks whether the given value, which currently has the given
6355/// source semantics, has the same value when coerced through the
6356/// target semantics.
6357///
6358/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006359static bool IsSameFloatAfterCast(const APValue &value,
6360 const llvm::fltSemantics &Src,
6361 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006362 if (value.isFloat())
6363 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6364
6365 if (value.isVector()) {
6366 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6367 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6368 return false;
6369 return true;
6370 }
6371
6372 assert(value.isComplexFloat());
6373 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6374 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6375}
6376
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006377static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006378
Ted Kremenek6274be42010-09-23 21:43:44 +00006379static bool IsZero(Sema &S, Expr *E) {
6380 // Suppress cases where we are comparing against an enum constant.
6381 if (const DeclRefExpr *DR =
6382 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6383 if (isa<EnumConstantDecl>(DR->getDecl()))
6384 return false;
6385
6386 // Suppress cases where the '0' value is expanded from a macro.
6387 if (E->getLocStart().isMacroID())
6388 return false;
6389
John McCallcc7e5bf2010-05-06 08:58:33 +00006390 llvm::APSInt Value;
6391 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6392}
6393
John McCall2551c1b2010-10-06 00:25:24 +00006394static bool HasEnumType(Expr *E) {
6395 // Strip off implicit integral promotions.
6396 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006397 if (ICE->getCastKind() != CK_IntegralCast &&
6398 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00006399 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006400 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00006401 }
6402
6403 return E->getType()->isEnumeralType();
6404}
6405
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006406static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00006407 // Disable warning in template instantiations.
6408 if (!S.ActiveTemplateInstantiations.empty())
6409 return;
6410
John McCalle3027922010-08-25 11:45:40 +00006411 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00006412 if (E->isValueDependent())
6413 return;
6414
John McCalle3027922010-08-25 11:45:40 +00006415 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006416 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006417 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006418 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006419 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006420 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006421 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006422 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006423 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006424 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006425 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006426 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006427 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006428 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006429 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006430 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6431 }
6432}
6433
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006434static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006435 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006436 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006437 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00006438 // Disable warning in template instantiations.
6439 if (!S.ActiveTemplateInstantiations.empty())
6440 return;
6441
Richard Trieu0f097742014-04-04 04:13:47 +00006442 // TODO: Investigate using GetExprRange() to get tighter bounds
6443 // on the bit ranges.
6444 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00006445 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00006446 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00006447 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6448 unsigned OtherWidth = OtherRange.Width;
6449
6450 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6451
Richard Trieu560910c2012-11-14 22:50:24 +00006452 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00006453 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00006454 return;
6455
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006456 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00006457 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006458
Richard Trieu0f097742014-04-04 04:13:47 +00006459 // Used for diagnostic printout.
6460 enum {
6461 LiteralConstant = 0,
6462 CXXBoolLiteralTrue,
6463 CXXBoolLiteralFalse
6464 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006465
Richard Trieu0f097742014-04-04 04:13:47 +00006466 if (!OtherIsBooleanType) {
6467 QualType ConstantT = Constant->getType();
6468 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00006469
Richard Trieu0f097742014-04-04 04:13:47 +00006470 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6471 return;
6472 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6473 "comparison with non-integer type");
6474
6475 bool ConstantSigned = ConstantT->isSignedIntegerType();
6476 bool CommonSigned = CommonT->isSignedIntegerType();
6477
6478 bool EqualityOnly = false;
6479
6480 if (CommonSigned) {
6481 // The common type is signed, therefore no signed to unsigned conversion.
6482 if (!OtherRange.NonNegative) {
6483 // Check that the constant is representable in type OtherT.
6484 if (ConstantSigned) {
6485 if (OtherWidth >= Value.getMinSignedBits())
6486 return;
6487 } else { // !ConstantSigned
6488 if (OtherWidth >= Value.getActiveBits() + 1)
6489 return;
6490 }
6491 } else { // !OtherSigned
6492 // Check that the constant is representable in type OtherT.
6493 // Negative values are out of range.
6494 if (ConstantSigned) {
6495 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6496 return;
6497 } else { // !ConstantSigned
6498 if (OtherWidth >= Value.getActiveBits())
6499 return;
6500 }
Richard Trieu560910c2012-11-14 22:50:24 +00006501 }
Richard Trieu0f097742014-04-04 04:13:47 +00006502 } else { // !CommonSigned
6503 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006504 if (OtherWidth >= Value.getActiveBits())
6505 return;
Craig Toppercf360162014-06-18 05:13:11 +00006506 } else { // OtherSigned
6507 assert(!ConstantSigned &&
6508 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006509 // Check to see if the constant is representable in OtherT.
6510 if (OtherWidth > Value.getActiveBits())
6511 return;
6512 // Check to see if the constant is equivalent to a negative value
6513 // cast to CommonT.
6514 if (S.Context.getIntWidth(ConstantT) ==
6515 S.Context.getIntWidth(CommonT) &&
6516 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6517 return;
6518 // The constant value rests between values that OtherT can represent
6519 // after conversion. Relational comparison still works, but equality
6520 // comparisons will be tautological.
6521 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006522 }
6523 }
Richard Trieu0f097742014-04-04 04:13:47 +00006524
6525 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6526
6527 if (op == BO_EQ || op == BO_NE) {
6528 IsTrue = op == BO_NE;
6529 } else if (EqualityOnly) {
6530 return;
6531 } else if (RhsConstant) {
6532 if (op == BO_GT || op == BO_GE)
6533 IsTrue = !PositiveConstant;
6534 else // op == BO_LT || op == BO_LE
6535 IsTrue = PositiveConstant;
6536 } else {
6537 if (op == BO_LT || op == BO_LE)
6538 IsTrue = !PositiveConstant;
6539 else // op == BO_GT || op == BO_GE
6540 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006541 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006542 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00006543 // Other isKnownToHaveBooleanValue
6544 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6545 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6546 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6547
6548 static const struct LinkedConditions {
6549 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6550 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6551 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6552 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6553 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6554 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6555
6556 } TruthTable = {
6557 // Constant on LHS. | Constant on RHS. |
6558 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6559 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6560 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6561 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6562 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6563 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6564 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6565 };
6566
6567 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6568
6569 enum ConstantValue ConstVal = Zero;
6570 if (Value.isUnsigned() || Value.isNonNegative()) {
6571 if (Value == 0) {
6572 LiteralOrBoolConstant =
6573 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6574 ConstVal = Zero;
6575 } else if (Value == 1) {
6576 LiteralOrBoolConstant =
6577 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6578 ConstVal = One;
6579 } else {
6580 LiteralOrBoolConstant = LiteralConstant;
6581 ConstVal = GT_One;
6582 }
6583 } else {
6584 ConstVal = LT_Zero;
6585 }
6586
6587 CompareBoolWithConstantResult CmpRes;
6588
6589 switch (op) {
6590 case BO_LT:
6591 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6592 break;
6593 case BO_GT:
6594 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6595 break;
6596 case BO_LE:
6597 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6598 break;
6599 case BO_GE:
6600 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6601 break;
6602 case BO_EQ:
6603 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6604 break;
6605 case BO_NE:
6606 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6607 break;
6608 default:
6609 CmpRes = Unkwn;
6610 break;
6611 }
6612
6613 if (CmpRes == AFals) {
6614 IsTrue = false;
6615 } else if (CmpRes == ATrue) {
6616 IsTrue = true;
6617 } else {
6618 return;
6619 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006620 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006621
6622 // If this is a comparison to an enum constant, include that
6623 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006624 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006625 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6626 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6627
6628 SmallString<64> PrettySourceValue;
6629 llvm::raw_svector_ostream OS(PrettySourceValue);
6630 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00006631 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006632 else
6633 OS << Value;
6634
Richard Trieu0f097742014-04-04 04:13:47 +00006635 S.DiagRuntimeBehavior(
6636 E->getOperatorLoc(), E,
6637 S.PDiag(diag::warn_out_of_range_compare)
6638 << OS.str() << LiteralOrBoolConstant
6639 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6640 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006641}
6642
John McCallcc7e5bf2010-05-06 08:58:33 +00006643/// Analyze the operands of the given comparison. Implements the
6644/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006645static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00006646 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6647 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006648}
John McCall263a48b2010-01-04 23:31:57 +00006649
John McCallca01b222010-01-04 23:21:16 +00006650/// \brief Implements -Wsign-compare.
6651///
Richard Trieu82402a02011-09-15 21:56:47 +00006652/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006653static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006654 // The type the comparison is being performed in.
6655 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006656
6657 // Only analyze comparison operators where both sides have been converted to
6658 // the same type.
6659 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6660 return AnalyzeImpConvsInComparison(S, E);
6661
6662 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006663 if (E->isValueDependent())
6664 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006665
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006666 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6667 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006668
6669 bool IsComparisonConstant = false;
6670
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006671 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006672 // of 'true' or 'false'.
6673 if (T->isIntegralType(S.Context)) {
6674 llvm::APSInt RHSValue;
6675 bool IsRHSIntegralLiteral =
6676 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6677 llvm::APSInt LHSValue;
6678 bool IsLHSIntegralLiteral =
6679 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6680 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6681 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6682 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6683 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6684 else
6685 IsComparisonConstant =
6686 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006687 } else if (!T->hasUnsignedIntegerRepresentation())
6688 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006689
John McCallcc7e5bf2010-05-06 08:58:33 +00006690 // We don't do anything special if this isn't an unsigned integral
6691 // comparison: we're only interested in integral comparisons, and
6692 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00006693 //
6694 // We also don't care about value-dependent expressions or expressions
6695 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006696 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00006697 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006698
John McCallcc7e5bf2010-05-06 08:58:33 +00006699 // Check to see if one of the (unmodified) operands is of different
6700 // signedness.
6701 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00006702 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6703 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00006704 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00006705 signedOperand = LHS;
6706 unsignedOperand = RHS;
6707 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6708 signedOperand = RHS;
6709 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00006710 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00006711 CheckTrivialUnsignedComparison(S, E);
6712 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006713 }
6714
John McCallcc7e5bf2010-05-06 08:58:33 +00006715 // Otherwise, calculate the effective range of the signed operand.
6716 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00006717
John McCallcc7e5bf2010-05-06 08:58:33 +00006718 // Go ahead and analyze implicit conversions in the operands. Note
6719 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00006720 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6721 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00006722
John McCallcc7e5bf2010-05-06 08:58:33 +00006723 // If the signed range is non-negative, -Wsign-compare won't fire,
6724 // but we should still check for comparisons which are always true
6725 // or false.
6726 if (signedRange.NonNegative)
6727 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006728
6729 // For (in)equality comparisons, if the unsigned operand is a
6730 // constant which cannot collide with a overflowed signed operand,
6731 // then reinterpreting the signed operand as unsigned will not
6732 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00006733 if (E->isEqualityOp()) {
6734 unsigned comparisonWidth = S.Context.getIntWidth(T);
6735 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00006736
John McCallcc7e5bf2010-05-06 08:58:33 +00006737 // We should never be unable to prove that the unsigned operand is
6738 // non-negative.
6739 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6740
6741 if (unsignedRange.Width < comparisonWidth)
6742 return;
6743 }
6744
Douglas Gregorbfb4a212012-05-01 01:53:49 +00006745 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6746 S.PDiag(diag::warn_mixed_sign_comparison)
6747 << LHS->getType() << RHS->getType()
6748 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00006749}
6750
John McCall1f425642010-11-11 03:21:53 +00006751/// Analyzes an attempt to assign the given value to a bitfield.
6752///
6753/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006754static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6755 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00006756 assert(Bitfield->isBitField());
6757 if (Bitfield->isInvalidDecl())
6758 return false;
6759
John McCalldeebbcf2010-11-11 05:33:51 +00006760 // White-list bool bitfields.
6761 if (Bitfield->getType()->isBooleanType())
6762 return false;
6763
Douglas Gregor789adec2011-02-04 13:09:01 +00006764 // Ignore value- or type-dependent expressions.
6765 if (Bitfield->getBitWidth()->isValueDependent() ||
6766 Bitfield->getBitWidth()->isTypeDependent() ||
6767 Init->isValueDependent() ||
6768 Init->isTypeDependent())
6769 return false;
6770
John McCall1f425642010-11-11 03:21:53 +00006771 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6772
Richard Smith5fab0c92011-12-28 19:48:30 +00006773 llvm::APSInt Value;
6774 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00006775 return false;
6776
John McCall1f425642010-11-11 03:21:53 +00006777 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00006778 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00006779
6780 if (OriginalWidth <= FieldWidth)
6781 return false;
6782
Eli Friedmanc267a322012-01-26 23:11:39 +00006783 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006784 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00006785 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00006786
Eli Friedmanc267a322012-01-26 23:11:39 +00006787 // Check whether the stored value is equal to the original value.
6788 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00006789 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00006790 return false;
6791
Eli Friedmanc267a322012-01-26 23:11:39 +00006792 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00006793 // therefore don't strictly fit into a signed bitfield of width 1.
6794 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00006795 return false;
6796
John McCall1f425642010-11-11 03:21:53 +00006797 std::string PrettyValue = Value.toString(10);
6798 std::string PrettyTrunc = TruncatedValue.toString(10);
6799
6800 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6801 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6802 << Init->getSourceRange();
6803
6804 return true;
6805}
6806
John McCalld2a53122010-11-09 23:24:47 +00006807/// Analyze the given simple or compound assignment for warning-worthy
6808/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006809static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006810 // Just recurse on the LHS.
6811 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6812
6813 // We want to recurse on the RHS as normal unless we're assigning to
6814 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006815 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006816 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006817 E->getOperatorLoc())) {
6818 // Recurse, ignoring any implicit conversions on the RHS.
6819 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6820 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006821 }
6822 }
6823
6824 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6825}
6826
John McCall263a48b2010-01-04 23:31:57 +00006827/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006828static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006829 SourceLocation CContext, unsigned diag,
6830 bool pruneControlFlow = false) {
6831 if (pruneControlFlow) {
6832 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6833 S.PDiag(diag)
6834 << SourceType << T << E->getSourceRange()
6835 << SourceRange(CContext));
6836 return;
6837 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006838 S.Diag(E->getExprLoc(), diag)
6839 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6840}
6841
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006842/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006843static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006844 SourceLocation CContext, unsigned diag,
6845 bool pruneControlFlow = false) {
6846 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006847}
6848
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006849/// Diagnose an implicit cast from a literal expression. Does not warn when the
6850/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006851void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6852 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006853 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006854 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006855 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006856 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6857 T->hasUnsignedIntegerRepresentation());
6858 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006859 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006860 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006861 return;
6862
Eli Friedman07185912013-08-29 23:44:43 +00006863 // FIXME: Force the precision of the source value down so we don't print
6864 // digits which are usually useless (we don't really care here if we
6865 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6866 // would automatically print the shortest representation, but it's a bit
6867 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006868 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006869 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6870 precision = (precision * 59 + 195) / 196;
6871 Value.toString(PrettySourceValue, precision);
6872
David Blaikie9b88cc02012-05-15 17:18:27 +00006873 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006874 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6875 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6876 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006877 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006878
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006879 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006880 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6881 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006882}
6883
John McCall18a2c2c2010-11-09 22:22:12 +00006884std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6885 if (!Range.Width) return "0";
6886
6887 llvm::APSInt ValueInRange = Value;
6888 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006889 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006890 return ValueInRange.toString(10);
6891}
6892
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006893static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6894 if (!isa<ImplicitCastExpr>(Ex))
6895 return false;
6896
6897 Expr *InnerE = Ex->IgnoreParenImpCasts();
6898 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6899 const Type *Source =
6900 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6901 if (Target->isDependentType())
6902 return false;
6903
6904 const BuiltinType *FloatCandidateBT =
6905 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6906 const Type *BoolCandidateType = ToBool ? Target : Source;
6907
6908 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6909 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6910}
6911
6912void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6913 SourceLocation CC) {
6914 unsigned NumArgs = TheCall->getNumArgs();
6915 for (unsigned i = 0; i < NumArgs; ++i) {
6916 Expr *CurrA = TheCall->getArg(i);
6917 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6918 continue;
6919
6920 bool IsSwapped = ((i > 0) &&
6921 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6922 IsSwapped |= ((i < (NumArgs - 1)) &&
6923 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6924 if (IsSwapped) {
6925 // Warn on this floating-point to bool conversion.
6926 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6927 CurrA->getType(), CC,
6928 diag::warn_impcast_floating_point_to_bool);
6929 }
6930 }
6931}
6932
Richard Trieu5b993502014-10-15 03:42:06 +00006933static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6934 SourceLocation CC) {
6935 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6936 E->getExprLoc()))
6937 return;
6938
6939 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6940 const Expr::NullPointerConstantKind NullKind =
6941 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6942 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6943 return;
6944
6945 // Return if target type is a safe conversion.
6946 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6947 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6948 return;
6949
6950 SourceLocation Loc = E->getSourceRange().getBegin();
6951
6952 // __null is usually wrapped in a macro. Go up a macro if that is the case.
6953 if (NullKind == Expr::NPCK_GNUNull) {
6954 if (Loc.isMacroID())
6955 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6956 }
6957
6958 // Only warn if the null and context location are in the same macro expansion.
6959 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6960 return;
6961
6962 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6963 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6964 << FixItHint::CreateReplacement(Loc,
6965 S.getFixItZeroLiteralForType(T, Loc));
6966}
6967
Douglas Gregor5054cb02015-07-07 03:58:22 +00006968static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
6969 ObjCArrayLiteral *ArrayLiteral);
6970static void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
6971 ObjCDictionaryLiteral *DictionaryLiteral);
6972
6973/// Check a single element within a collection literal against the
6974/// target element type.
6975static void checkObjCCollectionLiteralElement(Sema &S,
6976 QualType TargetElementType,
6977 Expr *Element,
6978 unsigned ElementKind) {
6979 // Skip a bitcast to 'id' or qualified 'id'.
6980 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
6981 if (ICE->getCastKind() == CK_BitCast &&
6982 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
6983 Element = ICE->getSubExpr();
6984 }
6985
6986 QualType ElementType = Element->getType();
6987 ExprResult ElementResult(Element);
6988 if (ElementType->getAs<ObjCObjectPointerType>() &&
6989 S.CheckSingleAssignmentConstraints(TargetElementType,
6990 ElementResult,
6991 false, false)
6992 != Sema::Compatible) {
6993 S.Diag(Element->getLocStart(),
6994 diag::warn_objc_collection_literal_element)
6995 << ElementType << ElementKind << TargetElementType
6996 << Element->getSourceRange();
6997 }
6998
6999 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7000 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7001 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7002 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7003}
7004
7005/// Check an Objective-C array literal being converted to the given
7006/// target type.
7007static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7008 ObjCArrayLiteral *ArrayLiteral) {
7009 if (!S.NSArrayDecl)
7010 return;
7011
7012 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7013 if (!TargetObjCPtr)
7014 return;
7015
7016 if (TargetObjCPtr->isUnspecialized() ||
7017 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7018 != S.NSArrayDecl->getCanonicalDecl())
7019 return;
7020
7021 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7022 if (TypeArgs.size() != 1)
7023 return;
7024
7025 QualType TargetElementType = TypeArgs[0];
7026 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
7027 checkObjCCollectionLiteralElement(S, TargetElementType,
7028 ArrayLiteral->getElement(I),
7029 0);
7030 }
7031}
7032
7033/// Check an Objective-C dictionary literal being converted to the given
7034/// target type.
7035static void checkObjCDictionaryLiteral(
7036 Sema &S, QualType TargetType,
7037 ObjCDictionaryLiteral *DictionaryLiteral) {
7038 if (!S.NSDictionaryDecl)
7039 return;
7040
7041 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7042 if (!TargetObjCPtr)
7043 return;
7044
7045 if (TargetObjCPtr->isUnspecialized() ||
7046 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7047 != S.NSDictionaryDecl->getCanonicalDecl())
7048 return;
7049
7050 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7051 if (TypeArgs.size() != 2)
7052 return;
7053
7054 QualType TargetKeyType = TypeArgs[0];
7055 QualType TargetObjectType = TypeArgs[1];
7056 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
7057 auto Element = DictionaryLiteral->getKeyValueElement(I);
7058 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7059 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7060 }
7061}
7062
John McCallcc7e5bf2010-05-06 08:58:33 +00007063void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00007064 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007065 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00007066
John McCallcc7e5bf2010-05-06 08:58:33 +00007067 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
7068 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
7069 if (Source == Target) return;
7070 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00007071
Chandler Carruthc22845a2011-07-26 05:40:03 +00007072 // If the conversion context location is invalid don't complain. We also
7073 // don't want to emit a warning if the issue occurs from the expansion of
7074 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
7075 // delay this check as long as possible. Once we detect we are in that
7076 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007077 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00007078 return;
7079
Richard Trieu021baa32011-09-23 20:10:00 +00007080 // Diagnose implicit casts to bool.
7081 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
7082 if (isa<StringLiteral>(E))
7083 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00007084 // and expressions, for instance, assert(0 && "error here"), are
7085 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00007086 return DiagnoseImpCast(S, E, T, CC,
7087 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00007088 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7089 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7090 // This covers the literal expressions that evaluate to Objective-C
7091 // objects.
7092 return DiagnoseImpCast(S, E, T, CC,
7093 diag::warn_impcast_objective_c_literal_to_bool);
7094 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007095 if (Source->isPointerType() || Source->canDecayToPointerType()) {
7096 // Warn on pointer to bool conversion that is always true.
7097 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
7098 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00007099 }
Richard Trieu021baa32011-09-23 20:10:00 +00007100 }
John McCall263a48b2010-01-04 23:31:57 +00007101
Douglas Gregor5054cb02015-07-07 03:58:22 +00007102 // Check implicit casts from Objective-C collection literals to specialized
7103 // collection types, e.g., NSArray<NSString *> *.
7104 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7105 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
7106 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7107 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
7108
John McCall263a48b2010-01-04 23:31:57 +00007109 // Strip vector types.
7110 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007111 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007112 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007113 return;
John McCallacf0ee52010-10-08 02:01:28 +00007114 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007115 }
Chris Lattneree7286f2011-06-14 04:51:15 +00007116
7117 // If the vector cast is cast between two vectors of the same size, it is
7118 // a bitcast, not a conversion.
7119 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
7120 return;
John McCall263a48b2010-01-04 23:31:57 +00007121
7122 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
7123 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
7124 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00007125 if (auto VecTy = dyn_cast<VectorType>(Target))
7126 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00007127
7128 // Strip complex types.
7129 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007130 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007131 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007132 return;
7133
John McCallacf0ee52010-10-08 02:01:28 +00007134 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007135 }
John McCall263a48b2010-01-04 23:31:57 +00007136
7137 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
7138 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
7139 }
7140
7141 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
7142 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
7143
7144 // If the source is floating point...
7145 if (SourceBT && SourceBT->isFloatingPoint()) {
7146 // ...and the target is floating point...
7147 if (TargetBT && TargetBT->isFloatingPoint()) {
7148 // ...then warn if we're dropping FP rank.
7149
7150 // Builtin FP kinds are ordered by increasing FP rank.
7151 if (SourceBT->getKind() > TargetBT->getKind()) {
7152 // Don't warn about float constants that are precisely
7153 // representable in the target type.
7154 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007155 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00007156 // Value might be a float, a float vector, or a float complex.
7157 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00007158 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
7159 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00007160 return;
7161 }
7162
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007163 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007164 return;
7165
John McCallacf0ee52010-10-08 02:01:28 +00007166 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00007167 }
7168 return;
7169 }
7170
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007171 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00007172 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007173 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007174 return;
7175
Chandler Carruth22c7a792011-02-17 11:05:49 +00007176 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00007177 // We also want to warn on, e.g., "int i = -1.234"
7178 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7179 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7180 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7181
Chandler Carruth016ef402011-04-10 08:36:24 +00007182 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
7183 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00007184 } else {
7185 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
7186 }
7187 }
John McCall263a48b2010-01-04 23:31:57 +00007188
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007189 // If the target is bool, warn if expr is a function or method call.
7190 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
7191 isa<CallExpr>(E)) {
7192 // Check last argument of function call to see if it is an
7193 // implicit cast from a type matching the type the result
7194 // is being cast to.
7195 CallExpr *CEx = cast<CallExpr>(E);
7196 unsigned NumArgs = CEx->getNumArgs();
7197 if (NumArgs > 0) {
7198 Expr *LastA = CEx->getArg(NumArgs - 1);
7199 Expr *InnerE = LastA->IgnoreParenImpCasts();
7200 const Type *InnerType =
7201 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7202 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
7203 // Warn on this floating-point to bool conversion
7204 DiagnoseImpCast(S, E, T, CC,
7205 diag::warn_impcast_floating_point_to_bool);
7206 }
7207 }
7208 }
John McCall263a48b2010-01-04 23:31:57 +00007209 return;
7210 }
7211
Richard Trieu5b993502014-10-15 03:42:06 +00007212 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00007213
David Blaikie9366d2b2012-06-19 21:19:06 +00007214 if (!Source->isIntegerType() || !Target->isIntegerType())
7215 return;
7216
David Blaikie7555b6a2012-05-15 16:56:36 +00007217 // TODO: remove this early return once the false positives for constant->bool
7218 // in templates, macros, etc, are reduced or removed.
7219 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
7220 return;
7221
John McCallcc7e5bf2010-05-06 08:58:33 +00007222 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00007223 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00007224
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007225 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00007226 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007227 // TODO: this should happen for bitfield stores, too.
7228 llvm::APSInt Value(32);
7229 if (E->isIntegerConstantExpr(Value, S.Context)) {
7230 if (S.SourceMgr.isInSystemMacro(CC))
7231 return;
7232
John McCall18a2c2c2010-11-09 22:22:12 +00007233 std::string PrettySourceValue = Value.toString(10);
7234 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007235
Ted Kremenek33ba9952011-10-22 02:37:33 +00007236 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7237 S.PDiag(diag::warn_impcast_integer_precision_constant)
7238 << PrettySourceValue << PrettyTargetValue
7239 << E->getType() << T << E->getSourceRange()
7240 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00007241 return;
7242 }
7243
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007244 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
7245 if (S.SourceMgr.isInSystemMacro(CC))
7246 return;
7247
David Blaikie9455da02012-04-12 22:40:54 +00007248 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00007249 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
7250 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00007251 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00007252 }
7253
7254 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
7255 (!TargetRange.NonNegative && SourceRange.NonNegative &&
7256 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007257
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007258 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007259 return;
7260
John McCallcc7e5bf2010-05-06 08:58:33 +00007261 unsigned DiagID = diag::warn_impcast_integer_sign;
7262
7263 // Traditionally, gcc has warned about this under -Wsign-compare.
7264 // We also want to warn about it in -Wconversion.
7265 // So if -Wconversion is off, use a completely identical diagnostic
7266 // in the sign-compare group.
7267 // The conditional-checking code will
7268 if (ICContext) {
7269 DiagID = diag::warn_impcast_integer_sign_conditional;
7270 *ICContext = true;
7271 }
7272
John McCallacf0ee52010-10-08 02:01:28 +00007273 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00007274 }
7275
Douglas Gregora78f1932011-02-22 02:45:07 +00007276 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00007277 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
7278 // type, to give us better diagnostics.
7279 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007280 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00007281 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7282 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
7283 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
7284 SourceType = S.Context.getTypeDeclType(Enum);
7285 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
7286 }
7287 }
7288
Douglas Gregora78f1932011-02-22 02:45:07 +00007289 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
7290 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00007291 if (SourceEnum->getDecl()->hasNameForLinkage() &&
7292 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007293 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007294 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007295 return;
7296
Douglas Gregor364f7db2011-03-12 00:14:31 +00007297 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00007298 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007299 }
Douglas Gregora78f1932011-02-22 02:45:07 +00007300
John McCall263a48b2010-01-04 23:31:57 +00007301 return;
7302}
7303
David Blaikie18e9ac72012-05-15 21:57:38 +00007304void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7305 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007306
7307void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00007308 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007309 E = E->IgnoreParenImpCasts();
7310
7311 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00007312 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007313
John McCallacf0ee52010-10-08 02:01:28 +00007314 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007315 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007316 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00007317 return;
7318}
7319
David Blaikie18e9ac72012-05-15 21:57:38 +00007320void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7321 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00007322 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007323
7324 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00007325 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
7326 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007327
7328 // If -Wconversion would have warned about either of the candidates
7329 // for a signedness conversion to the context type...
7330 if (!Suspicious) return;
7331
7332 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007333 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00007334 return;
7335
John McCallcc7e5bf2010-05-06 08:58:33 +00007336 // ...then check whether it would have warned about either of the
7337 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00007338 if (E->getType() == T) return;
7339
7340 Suspicious = false;
7341 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
7342 E->getType(), CC, &Suspicious);
7343 if (!Suspicious)
7344 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00007345 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007346}
7347
Richard Trieu65724892014-11-15 06:37:39 +00007348/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7349/// Input argument E is a logical expression.
7350static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
7351 if (S.getLangOpts().Bool)
7352 return;
7353 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
7354}
7355
John McCallcc7e5bf2010-05-06 08:58:33 +00007356/// AnalyzeImplicitConversions - Find and report any interesting
7357/// implicit conversions in the given expression. There are a couple
7358/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007359void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00007360 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00007361 Expr *E = OrigE->IgnoreParenImpCasts();
7362
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00007363 if (E->isTypeDependent() || E->isValueDependent())
7364 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00007365
John McCallcc7e5bf2010-05-06 08:58:33 +00007366 // For conditional operators, we analyze the arguments as if they
7367 // were being fed directly into the output.
7368 if (isa<ConditionalOperator>(E)) {
7369 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00007370 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007371 return;
7372 }
7373
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007374 // Check implicit argument conversions for function calls.
7375 if (CallExpr *Call = dyn_cast<CallExpr>(E))
7376 CheckImplicitArgumentConversions(S, Call, CC);
7377
John McCallcc7e5bf2010-05-06 08:58:33 +00007378 // Go ahead and check any implicit conversions we might have skipped.
7379 // The non-canonical typecheck is just an optimization;
7380 // CheckImplicitConversion will filter out dead implicit conversions.
7381 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007382 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007383
7384 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00007385
7386 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00007387 if (POE->getResultExpr())
7388 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00007389 }
7390
Fariborz Jahanian947efbc2015-02-26 17:59:54 +00007391 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
7392 if (OVE->getSourceExpr())
7393 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
7394 return;
7395 }
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00007396
John McCallcc7e5bf2010-05-06 08:58:33 +00007397 // Skip past explicit casts.
7398 if (isa<ExplicitCastExpr>(E)) {
7399 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00007400 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007401 }
7402
John McCalld2a53122010-11-09 23:24:47 +00007403 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7404 // Do a somewhat different check with comparison operators.
7405 if (BO->isComparisonOp())
7406 return AnalyzeComparison(S, BO);
7407
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007408 // And with simple assignments.
7409 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00007410 return AnalyzeAssignment(S, BO);
7411 }
John McCallcc7e5bf2010-05-06 08:58:33 +00007412
7413 // These break the otherwise-useful invariant below. Fortunately,
7414 // we don't really need to recurse into them, because any internal
7415 // expressions should have been analyzed already when they were
7416 // built into statements.
7417 if (isa<StmtExpr>(E)) return;
7418
7419 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00007420 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00007421
7422 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00007423 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00007424 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00007425 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00007426 for (Stmt *SubStmt : E->children()) {
7427 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00007428 if (!ChildExpr)
7429 continue;
7430
Richard Trieu955231d2014-01-25 01:10:35 +00007431 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00007432 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00007433 // Ignore checking string literals that are in logical and operators.
7434 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00007435 continue;
7436 AnalyzeImplicitConversions(S, ChildExpr, CC);
7437 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007438
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007439 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00007440 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
7441 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007442 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00007443
7444 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
7445 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007446 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007447 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007448
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007449 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
7450 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00007451 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007452}
7453
7454} // end anonymous namespace
7455
Richard Trieu3bb8b562014-02-26 02:36:06 +00007456enum {
7457 AddressOf,
7458 FunctionPointer,
7459 ArrayPointer
7460};
7461
Richard Trieuc1888e02014-06-28 23:25:37 +00007462// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
7463// Returns true when emitting a warning about taking the address of a reference.
7464static bool CheckForReference(Sema &SemaRef, const Expr *E,
7465 PartialDiagnostic PD) {
7466 E = E->IgnoreParenImpCasts();
7467
7468 const FunctionDecl *FD = nullptr;
7469
7470 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7471 if (!DRE->getDecl()->getType()->isReferenceType())
7472 return false;
7473 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7474 if (!M->getMemberDecl()->getType()->isReferenceType())
7475 return false;
7476 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00007477 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00007478 return false;
7479 FD = Call->getDirectCallee();
7480 } else {
7481 return false;
7482 }
7483
7484 SemaRef.Diag(E->getExprLoc(), PD);
7485
7486 // If possible, point to location of function.
7487 if (FD) {
7488 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
7489 }
7490
7491 return true;
7492}
7493
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007494// Returns true if the SourceLocation is expanded from any macro body.
7495// Returns false if the SourceLocation is invalid, is from not in a macro
7496// expansion, or is from expanded from a top-level macro argument.
7497static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
7498 if (Loc.isInvalid())
7499 return false;
7500
7501 while (Loc.isMacroID()) {
7502 if (SM.isMacroBodyExpansion(Loc))
7503 return true;
7504 Loc = SM.getImmediateMacroCallerLoc(Loc);
7505 }
7506
7507 return false;
7508}
7509
Richard Trieu3bb8b562014-02-26 02:36:06 +00007510/// \brief Diagnose pointers that are always non-null.
7511/// \param E the expression containing the pointer
7512/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
7513/// compared to a null pointer
7514/// \param IsEqual True when the comparison is equal to a null pointer
7515/// \param Range Extra SourceRange to highlight in the diagnostic
7516void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
7517 Expr::NullPointerConstantKind NullKind,
7518 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00007519 if (!E)
7520 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007521
7522 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007523 if (E->getExprLoc().isMacroID()) {
7524 const SourceManager &SM = getSourceManager();
7525 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
7526 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00007527 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007528 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007529 E = E->IgnoreImpCasts();
7530
7531 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
7532
Richard Trieuf7432752014-06-06 21:39:26 +00007533 if (isa<CXXThisExpr>(E)) {
7534 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
7535 : diag::warn_this_bool_conversion;
7536 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
7537 return;
7538 }
7539
Richard Trieu3bb8b562014-02-26 02:36:06 +00007540 bool IsAddressOf = false;
7541
7542 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7543 if (UO->getOpcode() != UO_AddrOf)
7544 return;
7545 IsAddressOf = true;
7546 E = UO->getSubExpr();
7547 }
7548
Richard Trieuc1888e02014-06-28 23:25:37 +00007549 if (IsAddressOf) {
7550 unsigned DiagID = IsCompare
7551 ? diag::warn_address_of_reference_null_compare
7552 : diag::warn_address_of_reference_bool_conversion;
7553 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
7554 << IsEqual;
7555 if (CheckForReference(*this, E, PD)) {
7556 return;
7557 }
7558 }
7559
Richard Trieu3bb8b562014-02-26 02:36:06 +00007560 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00007561 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007562 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
7563 D = R->getDecl();
7564 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7565 D = M->getMemberDecl();
7566 }
7567
7568 // Weak Decls can be null.
7569 if (!D || D->isWeak())
7570 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007571
7572 // Check for parameter decl with nonnull attribute
7573 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
7574 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
7575 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
7576 unsigned NumArgs = FD->getNumParams();
7577 llvm::SmallBitVector AttrNonNull(NumArgs);
7578 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
7579 if (!NonNull->args_size()) {
7580 AttrNonNull.set(0, NumArgs);
7581 break;
7582 }
7583 for (unsigned Val : NonNull->args()) {
7584 if (Val >= NumArgs)
7585 continue;
7586 AttrNonNull.set(Val);
7587 }
7588 }
7589 if (!AttrNonNull.empty())
7590 for (unsigned i = 0; i < NumArgs; ++i)
Aaron Ballman2521f362014-12-11 19:35:42 +00007591 if (FD->getParamDecl(i) == PV &&
7592 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007593 std::string Str;
7594 llvm::raw_string_ostream S(Str);
7595 E->printPretty(S, nullptr, getPrintingPolicy());
7596 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
7597 : diag::warn_cast_nonnull_to_bool;
7598 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
7599 << Range << IsEqual;
7600 return;
7601 }
7602 }
7603 }
7604
Richard Trieu3bb8b562014-02-26 02:36:06 +00007605 QualType T = D->getType();
7606 const bool IsArray = T->isArrayType();
7607 const bool IsFunction = T->isFunctionType();
7608
Richard Trieuc1888e02014-06-28 23:25:37 +00007609 // Address of function is used to silence the function warning.
7610 if (IsAddressOf && IsFunction) {
7611 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007612 }
7613
7614 // Found nothing.
7615 if (!IsAddressOf && !IsFunction && !IsArray)
7616 return;
7617
7618 // Pretty print the expression for the diagnostic.
7619 std::string Str;
7620 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00007621 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00007622
7623 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7624 : diag::warn_impcast_pointer_to_bool;
7625 unsigned DiagType;
7626 if (IsAddressOf)
7627 DiagType = AddressOf;
7628 else if (IsFunction)
7629 DiagType = FunctionPointer;
7630 else if (IsArray)
7631 DiagType = ArrayPointer;
7632 else
7633 llvm_unreachable("Could not determine diagnostic.");
7634 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7635 << Range << IsEqual;
7636
7637 if (!IsFunction)
7638 return;
7639
7640 // Suggest '&' to silence the function warning.
7641 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7642 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7643
7644 // Check to see if '()' fixit should be emitted.
7645 QualType ReturnType;
7646 UnresolvedSet<4> NonTemplateOverloads;
7647 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7648 if (ReturnType.isNull())
7649 return;
7650
7651 if (IsCompare) {
7652 // There are two cases here. If there is null constant, the only suggest
7653 // for a pointer return type. If the null is 0, then suggest if the return
7654 // type is a pointer or an integer type.
7655 if (!ReturnType->isPointerType()) {
7656 if (NullKind == Expr::NPCK_ZeroExpression ||
7657 NullKind == Expr::NPCK_ZeroLiteral) {
7658 if (!ReturnType->isIntegerType())
7659 return;
7660 } else {
7661 return;
7662 }
7663 }
7664 } else { // !IsCompare
7665 // For function to bool, only suggest if the function pointer has bool
7666 // return type.
7667 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7668 return;
7669 }
7670 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007671 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00007672}
7673
7674
John McCallcc7e5bf2010-05-06 08:58:33 +00007675/// Diagnoses "dangerous" implicit conversions within the given
7676/// expression (which is a full expression). Implements -Wconversion
7677/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007678///
7679/// \param CC the "context" location of the implicit conversion, i.e.
7680/// the most location of the syntactic entity requiring the implicit
7681/// conversion
7682void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007683 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00007684 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00007685 return;
7686
7687 // Don't diagnose for value- or type-dependent expressions.
7688 if (E->isTypeDependent() || E->isValueDependent())
7689 return;
7690
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007691 // Check for array bounds violations in cases where the check isn't triggered
7692 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7693 // ArraySubscriptExpr is on the RHS of a variable initialization.
7694 CheckArrayAccess(E);
7695
John McCallacf0ee52010-10-08 02:01:28 +00007696 // This is not the right CC for (e.g.) a variable initialization.
7697 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007698}
7699
Richard Trieu65724892014-11-15 06:37:39 +00007700/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7701/// Input argument E is a logical expression.
7702void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7703 ::CheckBoolLikeConversion(*this, E, CC);
7704}
7705
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007706/// Diagnose when expression is an integer constant expression and its evaluation
7707/// results in integer overflow
7708void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00007709 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7710 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007711}
7712
Richard Smithc406cb72013-01-17 01:17:56 +00007713namespace {
7714/// \brief Visitor for expressions which looks for unsequenced operations on the
7715/// same object.
7716class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007717 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7718
Richard Smithc406cb72013-01-17 01:17:56 +00007719 /// \brief A tree of sequenced regions within an expression. Two regions are
7720 /// unsequenced if one is an ancestor or a descendent of the other. When we
7721 /// finish processing an expression with sequencing, such as a comma
7722 /// expression, we fold its tree nodes into its parent, since they are
7723 /// unsequenced with respect to nodes we will visit later.
7724 class SequenceTree {
7725 struct Value {
7726 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7727 unsigned Parent : 31;
7728 bool Merged : 1;
7729 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007730 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00007731
7732 public:
7733 /// \brief A region within an expression which may be sequenced with respect
7734 /// to some other region.
7735 class Seq {
7736 explicit Seq(unsigned N) : Index(N) {}
7737 unsigned Index;
7738 friend class SequenceTree;
7739 public:
7740 Seq() : Index(0) {}
7741 };
7742
7743 SequenceTree() { Values.push_back(Value(0)); }
7744 Seq root() const { return Seq(0); }
7745
7746 /// \brief Create a new sequence of operations, which is an unsequenced
7747 /// subset of \p Parent. This sequence of operations is sequenced with
7748 /// respect to other children of \p Parent.
7749 Seq allocate(Seq Parent) {
7750 Values.push_back(Value(Parent.Index));
7751 return Seq(Values.size() - 1);
7752 }
7753
7754 /// \brief Merge a sequence of operations into its parent.
7755 void merge(Seq S) {
7756 Values[S.Index].Merged = true;
7757 }
7758
7759 /// \brief Determine whether two operations are unsequenced. This operation
7760 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7761 /// should have been merged into its parent as appropriate.
7762 bool isUnsequenced(Seq Cur, Seq Old) {
7763 unsigned C = representative(Cur.Index);
7764 unsigned Target = representative(Old.Index);
7765 while (C >= Target) {
7766 if (C == Target)
7767 return true;
7768 C = Values[C].Parent;
7769 }
7770 return false;
7771 }
7772
7773 private:
7774 /// \brief Pick a representative for a sequence.
7775 unsigned representative(unsigned K) {
7776 if (Values[K].Merged)
7777 // Perform path compression as we go.
7778 return Values[K].Parent = representative(Values[K].Parent);
7779 return K;
7780 }
7781 };
7782
7783 /// An object for which we can track unsequenced uses.
7784 typedef NamedDecl *Object;
7785
7786 /// Different flavors of object usage which we track. We only track the
7787 /// least-sequenced usage of each kind.
7788 enum UsageKind {
7789 /// A read of an object. Multiple unsequenced reads are OK.
7790 UK_Use,
7791 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00007792 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00007793 UK_ModAsValue,
7794 /// A modification of an object which is not sequenced before the value
7795 /// computation of the expression, such as n++.
7796 UK_ModAsSideEffect,
7797
7798 UK_Count = UK_ModAsSideEffect + 1
7799 };
7800
7801 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00007802 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00007803 Expr *Use;
7804 SequenceTree::Seq Seq;
7805 };
7806
7807 struct UsageInfo {
7808 UsageInfo() : Diagnosed(false) {}
7809 Usage Uses[UK_Count];
7810 /// Have we issued a diagnostic for this variable already?
7811 bool Diagnosed;
7812 };
7813 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7814
7815 Sema &SemaRef;
7816 /// Sequenced regions within the expression.
7817 SequenceTree Tree;
7818 /// Declaration modifications and references which we have seen.
7819 UsageInfoMap UsageMap;
7820 /// The region we are currently within.
7821 SequenceTree::Seq Region;
7822 /// Filled in with declarations which were modified as a side-effect
7823 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007824 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00007825 /// Expressions to check later. We defer checking these to reduce
7826 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007827 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00007828
7829 /// RAII object wrapping the visitation of a sequenced subexpression of an
7830 /// expression. At the end of this process, the side-effects of the evaluation
7831 /// become sequenced with respect to the value computation of the result, so
7832 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7833 /// UK_ModAsValue.
7834 struct SequencedSubexpression {
7835 SequencedSubexpression(SequenceChecker &Self)
7836 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7837 Self.ModAsSideEffect = &ModAsSideEffect;
7838 }
7839 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00007840 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7841 MI != ME; ++MI) {
7842 UsageInfo &U = Self.UsageMap[MI->first];
7843 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7844 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7845 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00007846 }
7847 Self.ModAsSideEffect = OldModAsSideEffect;
7848 }
7849
7850 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007851 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7852 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00007853 };
7854
Richard Smith40238f02013-06-20 22:21:56 +00007855 /// RAII object wrapping the visitation of a subexpression which we might
7856 /// choose to evaluate as a constant. If any subexpression is evaluated and
7857 /// found to be non-constant, this allows us to suppress the evaluation of
7858 /// the outer expression.
7859 class EvaluationTracker {
7860 public:
7861 EvaluationTracker(SequenceChecker &Self)
7862 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7863 Self.EvalTracker = this;
7864 }
7865 ~EvaluationTracker() {
7866 Self.EvalTracker = Prev;
7867 if (Prev)
7868 Prev->EvalOK &= EvalOK;
7869 }
7870
7871 bool evaluate(const Expr *E, bool &Result) {
7872 if (!EvalOK || E->isValueDependent())
7873 return false;
7874 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7875 return EvalOK;
7876 }
7877
7878 private:
7879 SequenceChecker &Self;
7880 EvaluationTracker *Prev;
7881 bool EvalOK;
7882 } *EvalTracker;
7883
Richard Smithc406cb72013-01-17 01:17:56 +00007884 /// \brief Find the object which is produced by the specified expression,
7885 /// if any.
7886 Object getObject(Expr *E, bool Mod) const {
7887 E = E->IgnoreParenCasts();
7888 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7889 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7890 return getObject(UO->getSubExpr(), Mod);
7891 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7892 if (BO->getOpcode() == BO_Comma)
7893 return getObject(BO->getRHS(), Mod);
7894 if (Mod && BO->isAssignmentOp())
7895 return getObject(BO->getLHS(), Mod);
7896 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7897 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7898 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7899 return ME->getMemberDecl();
7900 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7901 // FIXME: If this is a reference, map through to its value.
7902 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00007903 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00007904 }
7905
7906 /// \brief Note that an object was modified or used by an expression.
7907 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7908 Usage &U = UI.Uses[UK];
7909 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7910 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7911 ModAsSideEffect->push_back(std::make_pair(O, U));
7912 U.Use = Ref;
7913 U.Seq = Region;
7914 }
7915 }
7916 /// \brief Check whether a modification or use conflicts with a prior usage.
7917 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7918 bool IsModMod) {
7919 if (UI.Diagnosed)
7920 return;
7921
7922 const Usage &U = UI.Uses[OtherKind];
7923 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7924 return;
7925
7926 Expr *Mod = U.Use;
7927 Expr *ModOrUse = Ref;
7928 if (OtherKind == UK_Use)
7929 std::swap(Mod, ModOrUse);
7930
7931 SemaRef.Diag(Mod->getExprLoc(),
7932 IsModMod ? diag::warn_unsequenced_mod_mod
7933 : diag::warn_unsequenced_mod_use)
7934 << O << SourceRange(ModOrUse->getExprLoc());
7935 UI.Diagnosed = true;
7936 }
7937
7938 void notePreUse(Object O, Expr *Use) {
7939 UsageInfo &U = UsageMap[O];
7940 // Uses conflict with other modifications.
7941 checkUsage(O, U, Use, UK_ModAsValue, false);
7942 }
7943 void notePostUse(Object O, Expr *Use) {
7944 UsageInfo &U = UsageMap[O];
7945 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7946 addUsage(U, O, Use, UK_Use);
7947 }
7948
7949 void notePreMod(Object O, Expr *Mod) {
7950 UsageInfo &U = UsageMap[O];
7951 // Modifications conflict with other modifications and with uses.
7952 checkUsage(O, U, Mod, UK_ModAsValue, true);
7953 checkUsage(O, U, Mod, UK_Use, false);
7954 }
7955 void notePostMod(Object O, Expr *Use, UsageKind UK) {
7956 UsageInfo &U = UsageMap[O];
7957 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7958 addUsage(U, O, Use, UK);
7959 }
7960
7961public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007962 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00007963 : Base(S.Context), SemaRef(S), Region(Tree.root()),
7964 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007965 Visit(E);
7966 }
7967
7968 void VisitStmt(Stmt *S) {
7969 // Skip all statements which aren't expressions for now.
7970 }
7971
7972 void VisitExpr(Expr *E) {
7973 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00007974 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007975 }
7976
7977 void VisitCastExpr(CastExpr *E) {
7978 Object O = Object();
7979 if (E->getCastKind() == CK_LValueToRValue)
7980 O = getObject(E->getSubExpr(), false);
7981
7982 if (O)
7983 notePreUse(O, E);
7984 VisitExpr(E);
7985 if (O)
7986 notePostUse(O, E);
7987 }
7988
7989 void VisitBinComma(BinaryOperator *BO) {
7990 // C++11 [expr.comma]p1:
7991 // Every value computation and side effect associated with the left
7992 // expression is sequenced before every value computation and side
7993 // effect associated with the right expression.
7994 SequenceTree::Seq LHS = Tree.allocate(Region);
7995 SequenceTree::Seq RHS = Tree.allocate(Region);
7996 SequenceTree::Seq OldRegion = Region;
7997
7998 {
7999 SequencedSubexpression SeqLHS(*this);
8000 Region = LHS;
8001 Visit(BO->getLHS());
8002 }
8003
8004 Region = RHS;
8005 Visit(BO->getRHS());
8006
8007 Region = OldRegion;
8008
8009 // Forget that LHS and RHS are sequenced. They are both unsequenced
8010 // with respect to other stuff.
8011 Tree.merge(LHS);
8012 Tree.merge(RHS);
8013 }
8014
8015 void VisitBinAssign(BinaryOperator *BO) {
8016 // The modification is sequenced after the value computation of the LHS
8017 // and RHS, so check it before inspecting the operands and update the
8018 // map afterwards.
8019 Object O = getObject(BO->getLHS(), true);
8020 if (!O)
8021 return VisitExpr(BO);
8022
8023 notePreMod(O, BO);
8024
8025 // C++11 [expr.ass]p7:
8026 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
8027 // only once.
8028 //
8029 // Therefore, for a compound assignment operator, O is considered used
8030 // everywhere except within the evaluation of E1 itself.
8031 if (isa<CompoundAssignOperator>(BO))
8032 notePreUse(O, BO);
8033
8034 Visit(BO->getLHS());
8035
8036 if (isa<CompoundAssignOperator>(BO))
8037 notePostUse(O, BO);
8038
8039 Visit(BO->getRHS());
8040
Richard Smith83e37bee2013-06-26 23:16:51 +00008041 // C++11 [expr.ass]p1:
8042 // the assignment is sequenced [...] before the value computation of the
8043 // assignment expression.
8044 // C11 6.5.16/3 has no such rule.
8045 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8046 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008047 }
8048 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
8049 VisitBinAssign(CAO);
8050 }
8051
8052 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8053 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8054 void VisitUnaryPreIncDec(UnaryOperator *UO) {
8055 Object O = getObject(UO->getSubExpr(), true);
8056 if (!O)
8057 return VisitExpr(UO);
8058
8059 notePreMod(O, UO);
8060 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00008061 // C++11 [expr.pre.incr]p1:
8062 // the expression ++x is equivalent to x+=1
8063 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8064 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008065 }
8066
8067 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8068 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8069 void VisitUnaryPostIncDec(UnaryOperator *UO) {
8070 Object O = getObject(UO->getSubExpr(), true);
8071 if (!O)
8072 return VisitExpr(UO);
8073
8074 notePreMod(O, UO);
8075 Visit(UO->getSubExpr());
8076 notePostMod(O, UO, UK_ModAsSideEffect);
8077 }
8078
8079 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
8080 void VisitBinLOr(BinaryOperator *BO) {
8081 // The side-effects of the LHS of an '&&' are sequenced before the
8082 // value computation of the RHS, and hence before the value computation
8083 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
8084 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00008085 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008086 {
8087 SequencedSubexpression Sequenced(*this);
8088 Visit(BO->getLHS());
8089 }
8090
8091 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008092 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008093 if (!Result)
8094 Visit(BO->getRHS());
8095 } else {
8096 // Check for unsequenced operations in the RHS, treating it as an
8097 // entirely separate evaluation.
8098 //
8099 // FIXME: If there are operations in the RHS which are unsequenced
8100 // with respect to operations outside the RHS, and those operations
8101 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00008102 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008103 }
Richard Smithc406cb72013-01-17 01:17:56 +00008104 }
8105 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00008106 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008107 {
8108 SequencedSubexpression Sequenced(*this);
8109 Visit(BO->getLHS());
8110 }
8111
8112 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008113 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008114 if (Result)
8115 Visit(BO->getRHS());
8116 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00008117 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008118 }
Richard Smithc406cb72013-01-17 01:17:56 +00008119 }
8120
8121 // Only visit the condition, unless we can be sure which subexpression will
8122 // be chosen.
8123 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00008124 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00008125 {
8126 SequencedSubexpression Sequenced(*this);
8127 Visit(CO->getCond());
8128 }
Richard Smithc406cb72013-01-17 01:17:56 +00008129
8130 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008131 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00008132 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008133 else {
Richard Smithd33f5202013-01-17 23:18:09 +00008134 WorkList.push_back(CO->getTrueExpr());
8135 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008136 }
Richard Smithc406cb72013-01-17 01:17:56 +00008137 }
8138
Richard Smithe3dbfe02013-06-30 10:40:20 +00008139 void VisitCallExpr(CallExpr *CE) {
8140 // C++11 [intro.execution]p15:
8141 // When calling a function [...], every value computation and side effect
8142 // associated with any argument expression, or with the postfix expression
8143 // designating the called function, is sequenced before execution of every
8144 // expression or statement in the body of the function [and thus before
8145 // the value computation of its result].
8146 SequencedSubexpression Sequenced(*this);
8147 Base::VisitCallExpr(CE);
8148
8149 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
8150 }
8151
Richard Smithc406cb72013-01-17 01:17:56 +00008152 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008153 // This is a call, so all subexpressions are sequenced before the result.
8154 SequencedSubexpression Sequenced(*this);
8155
Richard Smithc406cb72013-01-17 01:17:56 +00008156 if (!CCE->isListInitialization())
8157 return VisitExpr(CCE);
8158
8159 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008160 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008161 SequenceTree::Seq Parent = Region;
8162 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
8163 E = CCE->arg_end();
8164 I != E; ++I) {
8165 Region = Tree.allocate(Parent);
8166 Elts.push_back(Region);
8167 Visit(*I);
8168 }
8169
8170 // Forget that the initializers are sequenced.
8171 Region = Parent;
8172 for (unsigned I = 0; I < Elts.size(); ++I)
8173 Tree.merge(Elts[I]);
8174 }
8175
8176 void VisitInitListExpr(InitListExpr *ILE) {
8177 if (!SemaRef.getLangOpts().CPlusPlus11)
8178 return VisitExpr(ILE);
8179
8180 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008181 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008182 SequenceTree::Seq Parent = Region;
8183 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
8184 Expr *E = ILE->getInit(I);
8185 if (!E) continue;
8186 Region = Tree.allocate(Parent);
8187 Elts.push_back(Region);
8188 Visit(E);
8189 }
8190
8191 // Forget that the initializers are sequenced.
8192 Region = Parent;
8193 for (unsigned I = 0; I < Elts.size(); ++I)
8194 Tree.merge(Elts[I]);
8195 }
8196};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008197}
Richard Smithc406cb72013-01-17 01:17:56 +00008198
8199void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008200 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00008201 WorkList.push_back(E);
8202 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00008203 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00008204 SequenceChecker(*this, Item, WorkList);
8205 }
Richard Smithc406cb72013-01-17 01:17:56 +00008206}
8207
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008208void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
8209 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008210 CheckImplicitConversions(E, CheckLoc);
8211 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008212 if (!IsConstexpr && !E->isValueDependent())
8213 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008214}
8215
John McCall1f425642010-11-11 03:21:53 +00008216void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
8217 FieldDecl *BitField,
8218 Expr *Init) {
8219 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
8220}
8221
David Majnemer61a5bbf2015-04-07 22:08:51 +00008222static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
8223 SourceLocation Loc) {
8224 if (!PType->isVariablyModifiedType())
8225 return;
8226 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
8227 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
8228 return;
8229 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00008230 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
8231 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
8232 return;
8233 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00008234 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
8235 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
8236 return;
8237 }
8238
8239 const ArrayType *AT = S.Context.getAsArrayType(PType);
8240 if (!AT)
8241 return;
8242
8243 if (AT->getSizeModifier() != ArrayType::Star) {
8244 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
8245 return;
8246 }
8247
8248 S.Diag(Loc, diag::err_array_star_in_function_definition);
8249}
8250
Mike Stump0c2ec772010-01-21 03:59:47 +00008251/// CheckParmsForFunctionDef - Check that the parameters of the given
8252/// function are appropriate for the definition of a function. This
8253/// takes care of any checks that cannot be performed on the
8254/// declaration itself, e.g., that the types of each of the function
8255/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00008256bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
8257 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00008258 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008259 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00008260 for (; P != PEnd; ++P) {
8261 ParmVarDecl *Param = *P;
8262
Mike Stump0c2ec772010-01-21 03:59:47 +00008263 // C99 6.7.5.3p4: the parameters in a parameter type list in a
8264 // function declarator that is part of a function definition of
8265 // that function shall not have incomplete type.
8266 //
8267 // This is also C++ [dcl.fct]p6.
8268 if (!Param->isInvalidDecl() &&
8269 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008270 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008271 Param->setInvalidDecl();
8272 HasInvalidParm = true;
8273 }
8274
8275 // C99 6.9.1p5: If the declarator includes a parameter type list, the
8276 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00008277 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00008278 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00008279 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008280 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00008281 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00008282
8283 // C99 6.7.5.3p12:
8284 // If the function declarator is not part of a definition of that
8285 // function, parameters may have incomplete type and may use the [*]
8286 // notation in their sequences of declarator specifiers to specify
8287 // variable length array types.
8288 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00008289 // FIXME: This diagnostic should point the '[*]' if source-location
8290 // information is added for it.
8291 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008292
8293 // MSVC destroys objects passed by value in the callee. Therefore a
8294 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008295 // object's destructor. However, we don't perform any direct access check
8296 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00008297 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
8298 .getCXXABI()
8299 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00008300 if (!Param->isInvalidDecl()) {
8301 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
8302 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
8303 if (!ClassDecl->isInvalidDecl() &&
8304 !ClassDecl->hasIrrelevantDestructor() &&
8305 !ClassDecl->isDependentContext()) {
8306 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8307 MarkFunctionReferenced(Param->getLocation(), Destructor);
8308 DiagnoseUseOfDecl(Destructor, Param->getLocation());
8309 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008310 }
8311 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008312 }
Mike Stump0c2ec772010-01-21 03:59:47 +00008313 }
8314
8315 return HasInvalidParm;
8316}
John McCall2b5c1b22010-08-12 21:44:57 +00008317
8318/// CheckCastAlign - Implements -Wcast-align, which warns when a
8319/// pointer cast increases the alignment requirements.
8320void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
8321 // This is actually a lot of work to potentially be doing on every
8322 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008323 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00008324 return;
8325
8326 // Ignore dependent types.
8327 if (T->isDependentType() || Op->getType()->isDependentType())
8328 return;
8329
8330 // Require that the destination be a pointer type.
8331 const PointerType *DestPtr = T->getAs<PointerType>();
8332 if (!DestPtr) return;
8333
8334 // If the destination has alignment 1, we're done.
8335 QualType DestPointee = DestPtr->getPointeeType();
8336 if (DestPointee->isIncompleteType()) return;
8337 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
8338 if (DestAlign.isOne()) return;
8339
8340 // Require that the source be a pointer type.
8341 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
8342 if (!SrcPtr) return;
8343 QualType SrcPointee = SrcPtr->getPointeeType();
8344
8345 // Whitelist casts from cv void*. We already implicitly
8346 // whitelisted casts to cv void*, since they have alignment 1.
8347 // Also whitelist casts involving incomplete types, which implicitly
8348 // includes 'void'.
8349 if (SrcPointee->isIncompleteType()) return;
8350
8351 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
8352 if (SrcAlign >= DestAlign) return;
8353
8354 Diag(TRange.getBegin(), diag::warn_cast_align)
8355 << Op->getType() << T
8356 << static_cast<unsigned>(SrcAlign.getQuantity())
8357 << static_cast<unsigned>(DestAlign.getQuantity())
8358 << TRange << Op->getSourceRange();
8359}
8360
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008361static const Type* getElementType(const Expr *BaseExpr) {
8362 const Type* EltType = BaseExpr->getType().getTypePtr();
8363 if (EltType->isAnyPointerType())
8364 return EltType->getPointeeType().getTypePtr();
8365 else if (EltType->isArrayType())
8366 return EltType->getBaseElementTypeUnsafe();
8367 return EltType;
8368}
8369
Chandler Carruth28389f02011-08-05 09:10:50 +00008370/// \brief Check whether this array fits the idiom of a size-one tail padded
8371/// array member of a struct.
8372///
8373/// We avoid emitting out-of-bounds access warnings for such arrays as they are
8374/// commonly used to emulate flexible arrays in C89 code.
8375static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
8376 const NamedDecl *ND) {
8377 if (Size != 1 || !ND) return false;
8378
8379 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
8380 if (!FD) return false;
8381
8382 // Don't consider sizes resulting from macro expansions or template argument
8383 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00008384
8385 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008386 while (TInfo) {
8387 TypeLoc TL = TInfo->getTypeLoc();
8388 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00008389 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
8390 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008391 TInfo = TDL->getTypeSourceInfo();
8392 continue;
8393 }
David Blaikie6adc78e2013-02-18 22:06:02 +00008394 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
8395 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00008396 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
8397 return false;
8398 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008399 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00008400 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008401
8402 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00008403 if (!RD) return false;
8404 if (RD->isUnion()) return false;
8405 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8406 if (!CRD->isStandardLayout()) return false;
8407 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008408
Benjamin Kramer8c543672011-08-06 03:04:42 +00008409 // See if this is the last field decl in the record.
8410 const Decl *D = FD;
8411 while ((D = D->getNextDeclInContext()))
8412 if (isa<FieldDecl>(D))
8413 return false;
8414 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00008415}
8416
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008417void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008418 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00008419 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008420 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008421 if (IndexExpr->isValueDependent())
8422 return;
8423
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00008424 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008425 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008426 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008427 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008428 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00008429 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00008430
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008431 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008432 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00008433 return;
Richard Smith13f67182011-12-16 19:31:14 +00008434 if (IndexNegated)
8435 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00008436
Craig Topperc3ec1492014-05-26 06:22:03 +00008437 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00008438 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8439 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00008440 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00008441 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00008442
Ted Kremeneke4b316c2011-02-23 23:06:04 +00008443 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008444 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00008445 if (!size.isStrictlyPositive())
8446 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008447
8448 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00008449 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008450 // Make sure we're comparing apples to apples when comparing index to size
8451 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
8452 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00008453 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00008454 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008455 if (ptrarith_typesize != array_typesize) {
8456 // There's a cast to a different size type involved
8457 uint64_t ratio = array_typesize / ptrarith_typesize;
8458 // TODO: Be smarter about handling cases where array_typesize is not a
8459 // multiple of ptrarith_typesize
8460 if (ptrarith_typesize * ratio == array_typesize)
8461 size *= llvm::APInt(size.getBitWidth(), ratio);
8462 }
8463 }
8464
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008465 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008466 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008467 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008468 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008469
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008470 // For array subscripting the index must be less than size, but for pointer
8471 // arithmetic also allow the index (offset) to be equal to size since
8472 // computing the next address after the end of the array is legal and
8473 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008474 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00008475 return;
8476
8477 // Also don't warn for arrays of size 1 which are members of some
8478 // structure. These are often used to approximate flexible arrays in C89
8479 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008480 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00008481 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008482
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008483 // Suppress the warning if the subscript expression (as identified by the
8484 // ']' location) and the index expression are both from macro expansions
8485 // within a system header.
8486 if (ASE) {
8487 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
8488 ASE->getRBracketLoc());
8489 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
8490 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
8491 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00008492 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008493 return;
8494 }
8495 }
8496
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008497 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008498 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008499 DiagID = diag::warn_array_index_exceeds_bounds;
8500
8501 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8502 PDiag(DiagID) << index.toString(10, true)
8503 << size.toString(10, true)
8504 << (unsigned)size.getLimitedValue(~0U)
8505 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008506 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008507 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008508 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008509 DiagID = diag::warn_ptr_arith_precedes_bounds;
8510 if (index.isNegative()) index = -index;
8511 }
8512
8513 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8514 PDiag(DiagID) << index.toString(10, true)
8515 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00008516 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00008517
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00008518 if (!ND) {
8519 // Try harder to find a NamedDecl to point at in the note.
8520 while (const ArraySubscriptExpr *ASE =
8521 dyn_cast<ArraySubscriptExpr>(BaseExpr))
8522 BaseExpr = ASE->getBase()->IgnoreParenCasts();
8523 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8524 ND = dyn_cast<NamedDecl>(DRE->getDecl());
8525 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8526 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8527 }
8528
Chandler Carruth1af88f12011-02-17 21:10:52 +00008529 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008530 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
8531 PDiag(diag::note_array_index_out_of_bounds)
8532 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00008533}
8534
Ted Kremenekdf26df72011-03-01 18:41:00 +00008535void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008536 int AllowOnePastEnd = 0;
8537 while (expr) {
8538 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00008539 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008540 case Stmt::ArraySubscriptExprClass: {
8541 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008542 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008543 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00008544 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008545 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008546 case Stmt::OMPArraySectionExprClass: {
8547 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
8548 if (ASE->getLowerBound())
8549 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
8550 /*ASE=*/nullptr, AllowOnePastEnd > 0);
8551 return;
8552 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008553 case Stmt::UnaryOperatorClass: {
8554 // Only unwrap the * and & unary operators
8555 const UnaryOperator *UO = cast<UnaryOperator>(expr);
8556 expr = UO->getSubExpr();
8557 switch (UO->getOpcode()) {
8558 case UO_AddrOf:
8559 AllowOnePastEnd++;
8560 break;
8561 case UO_Deref:
8562 AllowOnePastEnd--;
8563 break;
8564 default:
8565 return;
8566 }
8567 break;
8568 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008569 case Stmt::ConditionalOperatorClass: {
8570 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
8571 if (const Expr *lhs = cond->getLHS())
8572 CheckArrayAccess(lhs);
8573 if (const Expr *rhs = cond->getRHS())
8574 CheckArrayAccess(rhs);
8575 return;
8576 }
8577 default:
8578 return;
8579 }
Peter Collingbourne91147592011-04-15 00:35:48 +00008580 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008581}
John McCall31168b02011-06-15 23:02:42 +00008582
8583//===--- CHECK: Objective-C retain cycles ----------------------------------//
8584
8585namespace {
8586 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00008587 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00008588 VarDecl *Variable;
8589 SourceRange Range;
8590 SourceLocation Loc;
8591 bool Indirect;
8592
8593 void setLocsFrom(Expr *e) {
8594 Loc = e->getExprLoc();
8595 Range = e->getSourceRange();
8596 }
8597 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008598}
John McCall31168b02011-06-15 23:02:42 +00008599
8600/// Consider whether capturing the given variable can possibly lead to
8601/// a retain cycle.
8602static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00008603 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00008604 // lifetime. In MRR, it's captured strongly if the variable is
8605 // __block and has an appropriate type.
8606 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8607 return false;
8608
8609 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008610 if (ref)
8611 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00008612 return true;
8613}
8614
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008615static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00008616 while (true) {
8617 e = e->IgnoreParens();
8618 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
8619 switch (cast->getCastKind()) {
8620 case CK_BitCast:
8621 case CK_LValueBitCast:
8622 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00008623 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00008624 e = cast->getSubExpr();
8625 continue;
8626
John McCall31168b02011-06-15 23:02:42 +00008627 default:
8628 return false;
8629 }
8630 }
8631
8632 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
8633 ObjCIvarDecl *ivar = ref->getDecl();
8634 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8635 return false;
8636
8637 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008638 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00008639 return false;
8640
8641 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8642 owner.Indirect = true;
8643 return true;
8644 }
8645
8646 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8647 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8648 if (!var) return false;
8649 return considerVariable(var, ref, owner);
8650 }
8651
John McCall31168b02011-06-15 23:02:42 +00008652 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8653 if (member->isArrow()) return false;
8654
8655 // Don't count this as an indirect ownership.
8656 e = member->getBase();
8657 continue;
8658 }
8659
John McCallfe96e0b2011-11-06 09:01:30 +00008660 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8661 // Only pay attention to pseudo-objects on property references.
8662 ObjCPropertyRefExpr *pre
8663 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8664 ->IgnoreParens());
8665 if (!pre) return false;
8666 if (pre->isImplicitProperty()) return false;
8667 ObjCPropertyDecl *property = pre->getExplicitProperty();
8668 if (!property->isRetaining() &&
8669 !(property->getPropertyIvarDecl() &&
8670 property->getPropertyIvarDecl()->getType()
8671 .getObjCLifetime() == Qualifiers::OCL_Strong))
8672 return false;
8673
8674 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008675 if (pre->isSuperReceiver()) {
8676 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8677 if (!owner.Variable)
8678 return false;
8679 owner.Loc = pre->getLocation();
8680 owner.Range = pre->getSourceRange();
8681 return true;
8682 }
John McCallfe96e0b2011-11-06 09:01:30 +00008683 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8684 ->getSourceExpr());
8685 continue;
8686 }
8687
John McCall31168b02011-06-15 23:02:42 +00008688 // Array ivars?
8689
8690 return false;
8691 }
8692}
8693
8694namespace {
8695 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8696 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8697 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008698 Context(Context), Variable(variable), Capturer(nullptr),
8699 VarWillBeReased(false) {}
8700 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00008701 VarDecl *Variable;
8702 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008703 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00008704
8705 void VisitDeclRefExpr(DeclRefExpr *ref) {
8706 if (ref->getDecl() == Variable && !Capturer)
8707 Capturer = ref;
8708 }
8709
John McCall31168b02011-06-15 23:02:42 +00008710 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8711 if (Capturer) return;
8712 Visit(ref->getBase());
8713 if (Capturer && ref->isFreeIvar())
8714 Capturer = ref;
8715 }
8716
8717 void VisitBlockExpr(BlockExpr *block) {
8718 // Look inside nested blocks
8719 if (block->getBlockDecl()->capturesVariable(Variable))
8720 Visit(block->getBlockDecl()->getBody());
8721 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00008722
8723 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8724 if (Capturer) return;
8725 if (OVE->getSourceExpr())
8726 Visit(OVE->getSourceExpr());
8727 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008728 void VisitBinaryOperator(BinaryOperator *BinOp) {
8729 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8730 return;
8731 Expr *LHS = BinOp->getLHS();
8732 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8733 if (DRE->getDecl() != Variable)
8734 return;
8735 if (Expr *RHS = BinOp->getRHS()) {
8736 RHS = RHS->IgnoreParenCasts();
8737 llvm::APSInt Value;
8738 VarWillBeReased =
8739 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8740 }
8741 }
8742 }
John McCall31168b02011-06-15 23:02:42 +00008743 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008744}
John McCall31168b02011-06-15 23:02:42 +00008745
8746/// Check whether the given argument is a block which captures a
8747/// variable.
8748static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8749 assert(owner.Variable && owner.Loc.isValid());
8750
8751 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00008752
8753 // Look through [^{...} copy] and Block_copy(^{...}).
8754 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8755 Selector Cmd = ME->getSelector();
8756 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8757 e = ME->getInstanceReceiver();
8758 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00008759 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00008760 e = e->IgnoreParenCasts();
8761 }
8762 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8763 if (CE->getNumArgs() == 1) {
8764 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00008765 if (Fn) {
8766 const IdentifierInfo *FnI = Fn->getIdentifier();
8767 if (FnI && FnI->isStr("_Block_copy")) {
8768 e = CE->getArg(0)->IgnoreParenCasts();
8769 }
8770 }
Jordan Rose67e887c2012-09-17 17:54:30 +00008771 }
8772 }
8773
John McCall31168b02011-06-15 23:02:42 +00008774 BlockExpr *block = dyn_cast<BlockExpr>(e);
8775 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00008776 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00008777
8778 FindCaptureVisitor visitor(S.Context, owner.Variable);
8779 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008780 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00008781}
8782
8783static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8784 RetainCycleOwner &owner) {
8785 assert(capturer);
8786 assert(owner.Variable && owner.Loc.isValid());
8787
8788 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8789 << owner.Variable << capturer->getSourceRange();
8790 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8791 << owner.Indirect << owner.Range;
8792}
8793
8794/// Check for a keyword selector that starts with the word 'add' or
8795/// 'set'.
8796static bool isSetterLikeSelector(Selector sel) {
8797 if (sel.isUnarySelector()) return false;
8798
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008799 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00008800 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008801 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00008802 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008803 else if (str.startswith("add")) {
8804 // Specially whitelist 'addOperationWithBlock:'.
8805 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8806 return false;
8807 str = str.substr(3);
8808 }
John McCall31168b02011-06-15 23:02:42 +00008809 else
8810 return false;
8811
8812 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00008813 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00008814}
8815
Benjamin Kramer3a743452015-03-09 15:03:32 +00008816static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
8817 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00008818 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
8819 Message->getReceiverInterface(),
8820 NSAPI::ClassId_NSMutableArray);
8821 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008822 return None;
8823 }
8824
8825 Selector Sel = Message->getSelector();
8826
8827 Optional<NSAPI::NSArrayMethodKind> MKOpt =
8828 S.NSAPIObj->getNSArrayMethodKind(Sel);
8829 if (!MKOpt) {
8830 return None;
8831 }
8832
8833 NSAPI::NSArrayMethodKind MK = *MKOpt;
8834
8835 switch (MK) {
8836 case NSAPI::NSMutableArr_addObject:
8837 case NSAPI::NSMutableArr_insertObjectAtIndex:
8838 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
8839 return 0;
8840 case NSAPI::NSMutableArr_replaceObjectAtIndex:
8841 return 1;
8842
8843 default:
8844 return None;
8845 }
8846
8847 return None;
8848}
8849
8850static
8851Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
8852 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00008853 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
8854 Message->getReceiverInterface(),
8855 NSAPI::ClassId_NSMutableDictionary);
8856 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008857 return None;
8858 }
8859
8860 Selector Sel = Message->getSelector();
8861
8862 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
8863 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
8864 if (!MKOpt) {
8865 return None;
8866 }
8867
8868 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
8869
8870 switch (MK) {
8871 case NSAPI::NSMutableDict_setObjectForKey:
8872 case NSAPI::NSMutableDict_setValueForKey:
8873 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
8874 return 0;
8875
8876 default:
8877 return None;
8878 }
8879
8880 return None;
8881}
8882
8883static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00008884 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
8885 Message->getReceiverInterface(),
8886 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +00008887
Alex Denisov5dfac812015-08-06 04:51:14 +00008888 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
8889 Message->getReceiverInterface(),
8890 NSAPI::ClassId_NSMutableOrderedSet);
8891 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008892 return None;
8893 }
8894
8895 Selector Sel = Message->getSelector();
8896
8897 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
8898 if (!MKOpt) {
8899 return None;
8900 }
8901
8902 NSAPI::NSSetMethodKind MK = *MKOpt;
8903
8904 switch (MK) {
8905 case NSAPI::NSMutableSet_addObject:
8906 case NSAPI::NSOrderedSet_setObjectAtIndex:
8907 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
8908 case NSAPI::NSOrderedSet_insertObjectAtIndex:
8909 return 0;
8910 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
8911 return 1;
8912 }
8913
8914 return None;
8915}
8916
8917void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
8918 if (!Message->isInstanceMessage()) {
8919 return;
8920 }
8921
8922 Optional<int> ArgOpt;
8923
8924 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
8925 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
8926 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
8927 return;
8928 }
8929
8930 int ArgIndex = *ArgOpt;
8931
Alex Denisove1d882c2015-03-04 17:55:52 +00008932 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
8933 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
8934 Arg = OE->getSourceExpr()->IgnoreImpCasts();
8935 }
8936
Alex Denisov5dfac812015-08-06 04:51:14 +00008937 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008938 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +00008939 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008940 Diag(Message->getSourceRange().getBegin(),
8941 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +00008942 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +00008943 }
8944 }
Alex Denisov5dfac812015-08-06 04:51:14 +00008945 } else {
8946 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
8947
8948 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
8949 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
8950 }
8951
8952 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
8953 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
8954 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
8955 ValueDecl *Decl = ReceiverRE->getDecl();
8956 Diag(Message->getSourceRange().getBegin(),
8957 diag::warn_objc_circular_container)
8958 << Decl->getName() << Decl->getName();
8959 if (!ArgRE->isObjCSelfExpr()) {
8960 Diag(Decl->getLocation(),
8961 diag::note_objc_circular_container_declared_here)
8962 << Decl->getName();
8963 }
8964 }
8965 }
8966 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
8967 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
8968 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
8969 ObjCIvarDecl *Decl = IvarRE->getDecl();
8970 Diag(Message->getSourceRange().getBegin(),
8971 diag::warn_objc_circular_container)
8972 << Decl->getName() << Decl->getName();
8973 Diag(Decl->getLocation(),
8974 diag::note_objc_circular_container_declared_here)
8975 << Decl->getName();
8976 }
Alex Denisove1d882c2015-03-04 17:55:52 +00008977 }
8978 }
8979 }
8980
8981}
8982
John McCall31168b02011-06-15 23:02:42 +00008983/// Check a message send to see if it's likely to cause a retain cycle.
8984void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8985 // Only check instance methods whose selector looks like a setter.
8986 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8987 return;
8988
8989 // Try to find a variable that the receiver is strongly owned by.
8990 RetainCycleOwner owner;
8991 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008992 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00008993 return;
8994 } else {
8995 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8996 owner.Variable = getCurMethodDecl()->getSelfDecl();
8997 owner.Loc = msg->getSuperLoc();
8998 owner.Range = msg->getSuperLoc();
8999 }
9000
9001 // Check whether the receiver is captured by any of the arguments.
9002 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
9003 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
9004 return diagnoseRetainCycle(*this, capturer, owner);
9005}
9006
9007/// Check a property assign to see if it's likely to cause a retain cycle.
9008void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
9009 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009010 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00009011 return;
9012
9013 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
9014 diagnoseRetainCycle(*this, capturer, owner);
9015}
9016
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009017void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
9018 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00009019 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009020 return;
9021
9022 // Because we don't have an expression for the variable, we have to set the
9023 // location explicitly here.
9024 Owner.Loc = Var->getLocation();
9025 Owner.Range = Var->getSourceRange();
9026
9027 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
9028 diagnoseRetainCycle(*this, Capturer, Owner);
9029}
9030
Ted Kremenek9304da92012-12-21 08:04:28 +00009031static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
9032 Expr *RHS, bool isProperty) {
9033 // Check if RHS is an Objective-C object literal, which also can get
9034 // immediately zapped in a weak reference. Note that we explicitly
9035 // allow ObjCStringLiterals, since those are designed to never really die.
9036 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009037
Ted Kremenek64873352012-12-21 22:46:35 +00009038 // This enum needs to match with the 'select' in
9039 // warn_objc_arc_literal_assign (off-by-1).
9040 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
9041 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
9042 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009043
9044 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00009045 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00009046 << (isProperty ? 0 : 1)
9047 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009048
9049 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00009050}
9051
Ted Kremenekc1f014a2012-12-21 19:45:30 +00009052static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
9053 Qualifiers::ObjCLifetime LT,
9054 Expr *RHS, bool isProperty) {
9055 // Strip off any implicit cast added to get to the one ARC-specific.
9056 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9057 if (cast->getCastKind() == CK_ARCConsumeObject) {
9058 S.Diag(Loc, diag::warn_arc_retained_assign)
9059 << (LT == Qualifiers::OCL_ExplicitNone)
9060 << (isProperty ? 0 : 1)
9061 << RHS->getSourceRange();
9062 return true;
9063 }
9064 RHS = cast->getSubExpr();
9065 }
9066
9067 if (LT == Qualifiers::OCL_Weak &&
9068 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
9069 return true;
9070
9071 return false;
9072}
9073
Ted Kremenekb36234d2012-12-21 08:04:20 +00009074bool Sema::checkUnsafeAssigns(SourceLocation Loc,
9075 QualType LHS, Expr *RHS) {
9076 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
9077
9078 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
9079 return false;
9080
9081 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
9082 return true;
9083
9084 return false;
9085}
9086
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009087void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
9088 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009089 QualType LHSType;
9090 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00009091 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009092 ObjCPropertyRefExpr *PRE
9093 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
9094 if (PRE && !PRE->isImplicitProperty()) {
9095 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9096 if (PD)
9097 LHSType = PD->getType();
9098 }
9099
9100 if (LHSType.isNull())
9101 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00009102
9103 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
9104
9105 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009106 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00009107 getCurFunction()->markSafeWeakUse(LHS);
9108 }
9109
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009110 if (checkUnsafeAssigns(Loc, LHSType, RHS))
9111 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00009112
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009113 // FIXME. Check for other life times.
9114 if (LT != Qualifiers::OCL_None)
9115 return;
9116
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009117 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009118 if (PRE->isImplicitProperty())
9119 return;
9120 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9121 if (!PD)
9122 return;
9123
Bill Wendling44426052012-12-20 19:22:21 +00009124 unsigned Attributes = PD->getPropertyAttributes();
9125 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009126 // when 'assign' attribute was not explicitly specified
9127 // by user, ignore it and rely on property type itself
9128 // for lifetime info.
9129 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
9130 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
9131 LHSType->isObjCRetainableType())
9132 return;
9133
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009134 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00009135 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009136 Diag(Loc, diag::warn_arc_retained_property_assign)
9137 << RHS->getSourceRange();
9138 return;
9139 }
9140 RHS = cast->getSubExpr();
9141 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009142 }
Bill Wendling44426052012-12-20 19:22:21 +00009143 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00009144 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
9145 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00009146 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009147 }
9148}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009149
9150//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
9151
9152namespace {
9153bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
9154 SourceLocation StmtLoc,
9155 const NullStmt *Body) {
9156 // Do not warn if the body is a macro that expands to nothing, e.g:
9157 //
9158 // #define CALL(x)
9159 // if (condition)
9160 // CALL(0);
9161 //
9162 if (Body->hasLeadingEmptyMacro())
9163 return false;
9164
9165 // Get line numbers of statement and body.
9166 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +00009167 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009168 &StmtLineInvalid);
9169 if (StmtLineInvalid)
9170 return false;
9171
9172 bool BodyLineInvalid;
9173 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
9174 &BodyLineInvalid);
9175 if (BodyLineInvalid)
9176 return false;
9177
9178 // Warn if null statement and body are on the same line.
9179 if (StmtLine != BodyLine)
9180 return false;
9181
9182 return true;
9183}
9184} // Unnamed namespace
9185
9186void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
9187 const Stmt *Body,
9188 unsigned DiagID) {
9189 // Since this is a syntactic check, don't emit diagnostic for template
9190 // instantiations, this just adds noise.
9191 if (CurrentInstantiationScope)
9192 return;
9193
9194 // The body should be a null statement.
9195 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9196 if (!NBody)
9197 return;
9198
9199 // Do the usual checks.
9200 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9201 return;
9202
9203 Diag(NBody->getSemiLoc(), DiagID);
9204 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9205}
9206
9207void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
9208 const Stmt *PossibleBody) {
9209 assert(!CurrentInstantiationScope); // Ensured by caller
9210
9211 SourceLocation StmtLoc;
9212 const Stmt *Body;
9213 unsigned DiagID;
9214 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
9215 StmtLoc = FS->getRParenLoc();
9216 Body = FS->getBody();
9217 DiagID = diag::warn_empty_for_body;
9218 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
9219 StmtLoc = WS->getCond()->getSourceRange().getEnd();
9220 Body = WS->getBody();
9221 DiagID = diag::warn_empty_while_body;
9222 } else
9223 return; // Neither `for' nor `while'.
9224
9225 // The body should be a null statement.
9226 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9227 if (!NBody)
9228 return;
9229
9230 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009231 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009232 return;
9233
9234 // Do the usual checks.
9235 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9236 return;
9237
9238 // `for(...);' and `while(...);' are popular idioms, so in order to keep
9239 // noise level low, emit diagnostics only if for/while is followed by a
9240 // CompoundStmt, e.g.:
9241 // for (int i = 0; i < n; i++);
9242 // {
9243 // a(i);
9244 // }
9245 // or if for/while is followed by a statement with more indentation
9246 // than for/while itself:
9247 // for (int i = 0; i < n; i++);
9248 // a(i);
9249 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
9250 if (!ProbableTypo) {
9251 bool BodyColInvalid;
9252 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
9253 PossibleBody->getLocStart(),
9254 &BodyColInvalid);
9255 if (BodyColInvalid)
9256 return;
9257
9258 bool StmtColInvalid;
9259 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
9260 S->getLocStart(),
9261 &StmtColInvalid);
9262 if (StmtColInvalid)
9263 return;
9264
9265 if (BodyCol > StmtCol)
9266 ProbableTypo = true;
9267 }
9268
9269 if (ProbableTypo) {
9270 Diag(NBody->getSemiLoc(), DiagID);
9271 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9272 }
9273}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009274
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009275//===--- CHECK: Warn on self move with std::move. -------------------------===//
9276
9277/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
9278void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
9279 SourceLocation OpLoc) {
9280
9281 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
9282 return;
9283
9284 if (!ActiveTemplateInstantiations.empty())
9285 return;
9286
9287 // Strip parens and casts away.
9288 LHSExpr = LHSExpr->IgnoreParenImpCasts();
9289 RHSExpr = RHSExpr->IgnoreParenImpCasts();
9290
9291 // Check for a call expression
9292 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
9293 if (!CE || CE->getNumArgs() != 1)
9294 return;
9295
9296 // Check for a call to std::move
9297 const FunctionDecl *FD = CE->getDirectCallee();
9298 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
9299 !FD->getIdentifier()->isStr("move"))
9300 return;
9301
9302 // Get argument from std::move
9303 RHSExpr = CE->getArg(0);
9304
9305 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9306 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9307
9308 // Two DeclRefExpr's, check that the decls are the same.
9309 if (LHSDeclRef && RHSDeclRef) {
9310 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9311 return;
9312 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9313 RHSDeclRef->getDecl()->getCanonicalDecl())
9314 return;
9315
9316 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9317 << LHSExpr->getSourceRange()
9318 << RHSExpr->getSourceRange();
9319 return;
9320 }
9321
9322 // Member variables require a different approach to check for self moves.
9323 // MemberExpr's are the same if every nested MemberExpr refers to the same
9324 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
9325 // the base Expr's are CXXThisExpr's.
9326 const Expr *LHSBase = LHSExpr;
9327 const Expr *RHSBase = RHSExpr;
9328 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
9329 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
9330 if (!LHSME || !RHSME)
9331 return;
9332
9333 while (LHSME && RHSME) {
9334 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
9335 RHSME->getMemberDecl()->getCanonicalDecl())
9336 return;
9337
9338 LHSBase = LHSME->getBase();
9339 RHSBase = RHSME->getBase();
9340 LHSME = dyn_cast<MemberExpr>(LHSBase);
9341 RHSME = dyn_cast<MemberExpr>(RHSBase);
9342 }
9343
9344 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
9345 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
9346 if (LHSDeclRef && RHSDeclRef) {
9347 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9348 return;
9349 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9350 RHSDeclRef->getDecl()->getCanonicalDecl())
9351 return;
9352
9353 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9354 << LHSExpr->getSourceRange()
9355 << RHSExpr->getSourceRange();
9356 return;
9357 }
9358
9359 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
9360 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9361 << LHSExpr->getSourceRange()
9362 << RHSExpr->getSourceRange();
9363}
9364
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009365//===--- Layout compatibility ----------------------------------------------//
9366
9367namespace {
9368
9369bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
9370
9371/// \brief Check if two enumeration types are layout-compatible.
9372bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
9373 // C++11 [dcl.enum] p8:
9374 // Two enumeration types are layout-compatible if they have the same
9375 // underlying type.
9376 return ED1->isComplete() && ED2->isComplete() &&
9377 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
9378}
9379
9380/// \brief Check if two fields are layout-compatible.
9381bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
9382 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
9383 return false;
9384
9385 if (Field1->isBitField() != Field2->isBitField())
9386 return false;
9387
9388 if (Field1->isBitField()) {
9389 // Make sure that the bit-fields are the same length.
9390 unsigned Bits1 = Field1->getBitWidthValue(C);
9391 unsigned Bits2 = Field2->getBitWidthValue(C);
9392
9393 if (Bits1 != Bits2)
9394 return false;
9395 }
9396
9397 return true;
9398}
9399
9400/// \brief Check if two standard-layout structs are layout-compatible.
9401/// (C++11 [class.mem] p17)
9402bool isLayoutCompatibleStruct(ASTContext &C,
9403 RecordDecl *RD1,
9404 RecordDecl *RD2) {
9405 // If both records are C++ classes, check that base classes match.
9406 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
9407 // If one of records is a CXXRecordDecl we are in C++ mode,
9408 // thus the other one is a CXXRecordDecl, too.
9409 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
9410 // Check number of base classes.
9411 if (D1CXX->getNumBases() != D2CXX->getNumBases())
9412 return false;
9413
9414 // Check the base classes.
9415 for (CXXRecordDecl::base_class_const_iterator
9416 Base1 = D1CXX->bases_begin(),
9417 BaseEnd1 = D1CXX->bases_end(),
9418 Base2 = D2CXX->bases_begin();
9419 Base1 != BaseEnd1;
9420 ++Base1, ++Base2) {
9421 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
9422 return false;
9423 }
9424 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
9425 // If only RD2 is a C++ class, it should have zero base classes.
9426 if (D2CXX->getNumBases() > 0)
9427 return false;
9428 }
9429
9430 // Check the fields.
9431 RecordDecl::field_iterator Field2 = RD2->field_begin(),
9432 Field2End = RD2->field_end(),
9433 Field1 = RD1->field_begin(),
9434 Field1End = RD1->field_end();
9435 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
9436 if (!isLayoutCompatible(C, *Field1, *Field2))
9437 return false;
9438 }
9439 if (Field1 != Field1End || Field2 != Field2End)
9440 return false;
9441
9442 return true;
9443}
9444
9445/// \brief Check if two standard-layout unions are layout-compatible.
9446/// (C++11 [class.mem] p18)
9447bool isLayoutCompatibleUnion(ASTContext &C,
9448 RecordDecl *RD1,
9449 RecordDecl *RD2) {
9450 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009451 for (auto *Field2 : RD2->fields())
9452 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009453
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009454 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009455 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
9456 I = UnmatchedFields.begin(),
9457 E = UnmatchedFields.end();
9458
9459 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009460 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009461 bool Result = UnmatchedFields.erase(*I);
9462 (void) Result;
9463 assert(Result);
9464 break;
9465 }
9466 }
9467 if (I == E)
9468 return false;
9469 }
9470
9471 return UnmatchedFields.empty();
9472}
9473
9474bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
9475 if (RD1->isUnion() != RD2->isUnion())
9476 return false;
9477
9478 if (RD1->isUnion())
9479 return isLayoutCompatibleUnion(C, RD1, RD2);
9480 else
9481 return isLayoutCompatibleStruct(C, RD1, RD2);
9482}
9483
9484/// \brief Check if two types are layout-compatible in C++11 sense.
9485bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
9486 if (T1.isNull() || T2.isNull())
9487 return false;
9488
9489 // C++11 [basic.types] p11:
9490 // If two types T1 and T2 are the same type, then T1 and T2 are
9491 // layout-compatible types.
9492 if (C.hasSameType(T1, T2))
9493 return true;
9494
9495 T1 = T1.getCanonicalType().getUnqualifiedType();
9496 T2 = T2.getCanonicalType().getUnqualifiedType();
9497
9498 const Type::TypeClass TC1 = T1->getTypeClass();
9499 const Type::TypeClass TC2 = T2->getTypeClass();
9500
9501 if (TC1 != TC2)
9502 return false;
9503
9504 if (TC1 == Type::Enum) {
9505 return isLayoutCompatible(C,
9506 cast<EnumType>(T1)->getDecl(),
9507 cast<EnumType>(T2)->getDecl());
9508 } else if (TC1 == Type::Record) {
9509 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
9510 return false;
9511
9512 return isLayoutCompatible(C,
9513 cast<RecordType>(T1)->getDecl(),
9514 cast<RecordType>(T2)->getDecl());
9515 }
9516
9517 return false;
9518}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009519}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009520
9521//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
9522
9523namespace {
9524/// \brief Given a type tag expression find the type tag itself.
9525///
9526/// \param TypeExpr Type tag expression, as it appears in user's code.
9527///
9528/// \param VD Declaration of an identifier that appears in a type tag.
9529///
9530/// \param MagicValue Type tag magic value.
9531bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
9532 const ValueDecl **VD, uint64_t *MagicValue) {
9533 while(true) {
9534 if (!TypeExpr)
9535 return false;
9536
9537 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
9538
9539 switch (TypeExpr->getStmtClass()) {
9540 case Stmt::UnaryOperatorClass: {
9541 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
9542 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
9543 TypeExpr = UO->getSubExpr();
9544 continue;
9545 }
9546 return false;
9547 }
9548
9549 case Stmt::DeclRefExprClass: {
9550 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
9551 *VD = DRE->getDecl();
9552 return true;
9553 }
9554
9555 case Stmt::IntegerLiteralClass: {
9556 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
9557 llvm::APInt MagicValueAPInt = IL->getValue();
9558 if (MagicValueAPInt.getActiveBits() <= 64) {
9559 *MagicValue = MagicValueAPInt.getZExtValue();
9560 return true;
9561 } else
9562 return false;
9563 }
9564
9565 case Stmt::BinaryConditionalOperatorClass:
9566 case Stmt::ConditionalOperatorClass: {
9567 const AbstractConditionalOperator *ACO =
9568 cast<AbstractConditionalOperator>(TypeExpr);
9569 bool Result;
9570 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
9571 if (Result)
9572 TypeExpr = ACO->getTrueExpr();
9573 else
9574 TypeExpr = ACO->getFalseExpr();
9575 continue;
9576 }
9577 return false;
9578 }
9579
9580 case Stmt::BinaryOperatorClass: {
9581 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
9582 if (BO->getOpcode() == BO_Comma) {
9583 TypeExpr = BO->getRHS();
9584 continue;
9585 }
9586 return false;
9587 }
9588
9589 default:
9590 return false;
9591 }
9592 }
9593}
9594
9595/// \brief Retrieve the C type corresponding to type tag TypeExpr.
9596///
9597/// \param TypeExpr Expression that specifies a type tag.
9598///
9599/// \param MagicValues Registered magic values.
9600///
9601/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
9602/// kind.
9603///
9604/// \param TypeInfo Information about the corresponding C type.
9605///
9606/// \returns true if the corresponding C type was found.
9607bool GetMatchingCType(
9608 const IdentifierInfo *ArgumentKind,
9609 const Expr *TypeExpr, const ASTContext &Ctx,
9610 const llvm::DenseMap<Sema::TypeTagMagicValue,
9611 Sema::TypeTagData> *MagicValues,
9612 bool &FoundWrongKind,
9613 Sema::TypeTagData &TypeInfo) {
9614 FoundWrongKind = false;
9615
9616 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00009617 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009618
9619 uint64_t MagicValue;
9620
9621 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
9622 return false;
9623
9624 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00009625 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009626 if (I->getArgumentKind() != ArgumentKind) {
9627 FoundWrongKind = true;
9628 return false;
9629 }
9630 TypeInfo.Type = I->getMatchingCType();
9631 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
9632 TypeInfo.MustBeNull = I->getMustBeNull();
9633 return true;
9634 }
9635 return false;
9636 }
9637
9638 if (!MagicValues)
9639 return false;
9640
9641 llvm::DenseMap<Sema::TypeTagMagicValue,
9642 Sema::TypeTagData>::const_iterator I =
9643 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
9644 if (I == MagicValues->end())
9645 return false;
9646
9647 TypeInfo = I->second;
9648 return true;
9649}
9650} // unnamed namespace
9651
9652void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9653 uint64_t MagicValue, QualType Type,
9654 bool LayoutCompatible,
9655 bool MustBeNull) {
9656 if (!TypeTagForDatatypeMagicValues)
9657 TypeTagForDatatypeMagicValues.reset(
9658 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
9659
9660 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
9661 (*TypeTagForDatatypeMagicValues)[Magic] =
9662 TypeTagData(Type, LayoutCompatible, MustBeNull);
9663}
9664
9665namespace {
9666bool IsSameCharType(QualType T1, QualType T2) {
9667 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
9668 if (!BT1)
9669 return false;
9670
9671 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
9672 if (!BT2)
9673 return false;
9674
9675 BuiltinType::Kind T1Kind = BT1->getKind();
9676 BuiltinType::Kind T2Kind = BT2->getKind();
9677
9678 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
9679 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
9680 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
9681 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
9682}
9683} // unnamed namespace
9684
9685void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9686 const Expr * const *ExprArgs) {
9687 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
9688 bool IsPointerAttr = Attr->getIsPointer();
9689
9690 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
9691 bool FoundWrongKind;
9692 TypeTagData TypeInfo;
9693 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
9694 TypeTagForDatatypeMagicValues.get(),
9695 FoundWrongKind, TypeInfo)) {
9696 if (FoundWrongKind)
9697 Diag(TypeTagExpr->getExprLoc(),
9698 diag::warn_type_tag_for_datatype_wrong_kind)
9699 << TypeTagExpr->getSourceRange();
9700 return;
9701 }
9702
9703 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
9704 if (IsPointerAttr) {
9705 // Skip implicit cast of pointer to `void *' (as a function argument).
9706 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00009707 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00009708 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009709 ArgumentExpr = ICE->getSubExpr();
9710 }
9711 QualType ArgumentType = ArgumentExpr->getType();
9712
9713 // Passing a `void*' pointer shouldn't trigger a warning.
9714 if (IsPointerAttr && ArgumentType->isVoidPointerType())
9715 return;
9716
9717 if (TypeInfo.MustBeNull) {
9718 // Type tag with matching void type requires a null pointer.
9719 if (!ArgumentExpr->isNullPointerConstant(Context,
9720 Expr::NPC_ValueDependentIsNotNull)) {
9721 Diag(ArgumentExpr->getExprLoc(),
9722 diag::warn_type_safety_null_pointer_required)
9723 << ArgumentKind->getName()
9724 << ArgumentExpr->getSourceRange()
9725 << TypeTagExpr->getSourceRange();
9726 }
9727 return;
9728 }
9729
9730 QualType RequiredType = TypeInfo.Type;
9731 if (IsPointerAttr)
9732 RequiredType = Context.getPointerType(RequiredType);
9733
9734 bool mismatch = false;
9735 if (!TypeInfo.LayoutCompatible) {
9736 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
9737
9738 // C++11 [basic.fundamental] p1:
9739 // Plain char, signed char, and unsigned char are three distinct types.
9740 //
9741 // But we treat plain `char' as equivalent to `signed char' or `unsigned
9742 // char' depending on the current char signedness mode.
9743 if (mismatch)
9744 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
9745 RequiredType->getPointeeType())) ||
9746 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
9747 mismatch = false;
9748 } else
9749 if (IsPointerAttr)
9750 mismatch = !isLayoutCompatible(Context,
9751 ArgumentType->getPointeeType(),
9752 RequiredType->getPointeeType());
9753 else
9754 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
9755
9756 if (mismatch)
9757 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00009758 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009759 << TypeInfo.LayoutCompatible << RequiredType
9760 << ArgumentExpr->getSourceRange()
9761 << TypeTagExpr->getSourceRange();
9762}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009763