blob: d4390e53f0bcbd84dded6f1b6039acd519208f48 [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000030#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000035#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000036#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "llvm/ADT/SmallString.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000038#include "llvm/Support/ConvertUTF.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/Support/raw_ostream.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000040#include <limits>
Chris Lattnerb87b1b32007-08-10 20:18:51 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000043
Chris Lattnera26fb342009-02-18 17:49:48 +000044SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000046 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
47 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000048}
49
John McCallbebede42011-02-26 05:39:39 +000050/// Checks that a call expression's argument count is the desired number.
51/// This is useful when doing custom type-checking. Returns true on error.
52static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53 unsigned argCount = call->getNumArgs();
54 if (argCount == desiredArgCount) return false;
55
56 if (argCount < desiredArgCount)
57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58 << 0 /*function call*/ << desiredArgCount << argCount
59 << call->getSourceRange();
60
61 // Highlight all the excess arguments.
62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63 call->getArg(argCount - 1)->getLocEnd());
64
65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66 << 0 /*function call*/ << desiredArgCount << argCount
67 << call->getArg(1)->getSourceRange();
68}
69
Julien Lerouge4a5b4442012-04-28 17:39:16 +000070/// Check that the first argument to __builtin_annotation is an integer
71/// and the second argument is a non-wide string literal.
72static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73 if (checkArgCount(S, TheCall, 2))
74 return true;
75
76 // First argument should be an integer.
77 Expr *ValArg = TheCall->getArg(0);
78 QualType Ty = ValArg->getType();
79 if (!Ty->isIntegerType()) {
80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000082 return true;
83 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000084
85 // Second argument should be a constant string.
86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88 if (!Literal || !Literal->isAscii()) {
89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90 << StrArg->getSourceRange();
91 return true;
92 }
93
94 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000095 return false;
96}
97
Richard Smith6cbd65d2013-07-11 02:27:57 +000098/// Check that the argument to __builtin_addressof is a glvalue, and set the
99/// result type to the corresponding pointer type.
100static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101 if (checkArgCount(S, TheCall, 1))
102 return true;
103
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000104 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
107 return true;
108
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000109 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000110 TheCall->setType(ResultType);
111 return false;
112}
113
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000114static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
115 CallExpr *TheCall, unsigned SizeIdx,
116 unsigned DstSizeIdx) {
117 if (TheCall->getNumArgs() <= SizeIdx ||
118 TheCall->getNumArgs() <= DstSizeIdx)
119 return;
120
121 const Expr *SizeArg = TheCall->getArg(SizeIdx);
122 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
123
124 llvm::APSInt Size, DstSize;
125
126 // find out if both sizes are known at compile time
127 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
128 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
129 return;
130
131 if (Size.ule(DstSize))
132 return;
133
134 // confirmed overflow so generate the diagnostic.
135 IdentifierInfo *FnName = FDecl->getIdentifier();
136 SourceLocation SL = TheCall->getLocStart();
137 SourceRange SR = TheCall->getSourceRange();
138
139 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
140}
141
Peter Collingbournef7706832014-12-12 23:41:25 +0000142static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
143 if (checkArgCount(S, BuiltinCall, 2))
144 return true;
145
146 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
147 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
148 Expr *Call = BuiltinCall->getArg(0);
149 Expr *Chain = BuiltinCall->getArg(1);
150
151 if (Call->getStmtClass() != Stmt::CallExprClass) {
152 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
153 << Call->getSourceRange();
154 return true;
155 }
156
157 auto CE = cast<CallExpr>(Call);
158 if (CE->getCallee()->getType()->isBlockPointerType()) {
159 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
160 << Call->getSourceRange();
161 return true;
162 }
163
164 const Decl *TargetDecl = CE->getCalleeDecl();
165 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
166 if (FD->getBuiltinID()) {
167 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
168 << Call->getSourceRange();
169 return true;
170 }
171
172 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
173 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
174 << Call->getSourceRange();
175 return true;
176 }
177
178 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
179 if (ChainResult.isInvalid())
180 return true;
181 if (!ChainResult.get()->getType()->isPointerType()) {
182 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
183 << Chain->getSourceRange();
184 return true;
185 }
186
David Majnemerced8bdf2015-02-25 17:36:15 +0000187 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000188 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
189 QualType BuiltinTy = S.Context.getFunctionType(
190 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
191 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
192
193 Builtin =
194 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
195
196 BuiltinCall->setType(CE->getType());
197 BuiltinCall->setValueKind(CE->getValueKind());
198 BuiltinCall->setObjectKind(CE->getObjectKind());
199 BuiltinCall->setCallee(Builtin);
200 BuiltinCall->setArg(1, ChainResult.get());
201
202 return false;
203}
204
Reid Kleckner1d59f992015-01-22 01:36:17 +0000205static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
206 Scope::ScopeFlags NeededScopeFlags,
207 unsigned DiagID) {
208 // Scopes aren't available during instantiation. Fortunately, builtin
209 // functions cannot be template args so they cannot be formed through template
210 // instantiation. Therefore checking once during the parse is sufficient.
211 if (!SemaRef.ActiveTemplateInstantiations.empty())
212 return false;
213
214 Scope *S = SemaRef.getCurScope();
215 while (S && !S->isSEHExceptScope())
216 S = S->getParent();
217 if (!S || !(S->getFlags() & NeededScopeFlags)) {
218 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
219 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
220 << DRE->getDecl()->getIdentifier();
221 return true;
222 }
223
224 return false;
225}
226
John McCalldadc5752010-08-24 06:29:42 +0000227ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000228Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
229 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000230 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000231
Chris Lattner3be167f2010-10-01 23:23:24 +0000232 // Find out if any arguments are required to be integer constant expressions.
233 unsigned ICEArguments = 0;
234 ASTContext::GetBuiltinTypeError Error;
235 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
236 if (Error != ASTContext::GE_None)
237 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
238
239 // If any arguments are required to be ICE's, check and diagnose.
240 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
241 // Skip arguments not required to be ICE's.
242 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
243
244 llvm::APSInt Result;
245 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
246 return true;
247 ICEArguments &= ~(1 << ArgNo);
248 }
249
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000250 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000251 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000252 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000253 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000254 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000255 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000256 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000257 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000258 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000259 if (SemaBuiltinVAStart(TheCall))
260 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000261 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000262 case Builtin::BI__va_start: {
263 switch (Context.getTargetInfo().getTriple().getArch()) {
264 case llvm::Triple::arm:
265 case llvm::Triple::thumb:
266 if (SemaBuiltinVAStartARM(TheCall))
267 return ExprError();
268 break;
269 default:
270 if (SemaBuiltinVAStart(TheCall))
271 return ExprError();
272 break;
273 }
274 break;
275 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000276 case Builtin::BI__builtin_isgreater:
277 case Builtin::BI__builtin_isgreaterequal:
278 case Builtin::BI__builtin_isless:
279 case Builtin::BI__builtin_islessequal:
280 case Builtin::BI__builtin_islessgreater:
281 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000282 if (SemaBuiltinUnorderedCompare(TheCall))
283 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000284 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000285 case Builtin::BI__builtin_fpclassify:
286 if (SemaBuiltinFPClassification(TheCall, 6))
287 return ExprError();
288 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000289 case Builtin::BI__builtin_isfinite:
290 case Builtin::BI__builtin_isinf:
291 case Builtin::BI__builtin_isinf_sign:
292 case Builtin::BI__builtin_isnan:
293 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000294 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000295 return ExprError();
296 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000297 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000298 return SemaBuiltinShuffleVector(TheCall);
299 // TheCall will be freed by the smart pointer here, but that's fine, since
300 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000301 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000302 if (SemaBuiltinPrefetch(TheCall))
303 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000304 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000305 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000306 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000307 if (SemaBuiltinAssume(TheCall))
308 return ExprError();
309 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000310 case Builtin::BI__builtin_assume_aligned:
311 if (SemaBuiltinAssumeAligned(TheCall))
312 return ExprError();
313 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000314 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000315 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000316 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000317 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000318 case Builtin::BI__builtin_longjmp:
319 if (SemaBuiltinLongjmp(TheCall))
320 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000321 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000322 case Builtin::BI__builtin_setjmp:
323 if (SemaBuiltinSetjmp(TheCall))
324 return ExprError();
325 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000326 case Builtin::BI_setjmp:
327 case Builtin::BI_setjmpex:
328 if (checkArgCount(*this, TheCall, 1))
329 return true;
330 break;
John McCallbebede42011-02-26 05:39:39 +0000331
332 case Builtin::BI__builtin_classify_type:
333 if (checkArgCount(*this, TheCall, 1)) return true;
334 TheCall->setType(Context.IntTy);
335 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000336 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000337 if (checkArgCount(*this, TheCall, 1)) return true;
338 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000339 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000340 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000341 case Builtin::BI__sync_fetch_and_add_1:
342 case Builtin::BI__sync_fetch_and_add_2:
343 case Builtin::BI__sync_fetch_and_add_4:
344 case Builtin::BI__sync_fetch_and_add_8:
345 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000346 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000347 case Builtin::BI__sync_fetch_and_sub_1:
348 case Builtin::BI__sync_fetch_and_sub_2:
349 case Builtin::BI__sync_fetch_and_sub_4:
350 case Builtin::BI__sync_fetch_and_sub_8:
351 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000352 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000353 case Builtin::BI__sync_fetch_and_or_1:
354 case Builtin::BI__sync_fetch_and_or_2:
355 case Builtin::BI__sync_fetch_and_or_4:
356 case Builtin::BI__sync_fetch_and_or_8:
357 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000358 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000359 case Builtin::BI__sync_fetch_and_and_1:
360 case Builtin::BI__sync_fetch_and_and_2:
361 case Builtin::BI__sync_fetch_and_and_4:
362 case Builtin::BI__sync_fetch_and_and_8:
363 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000364 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000365 case Builtin::BI__sync_fetch_and_xor_1:
366 case Builtin::BI__sync_fetch_and_xor_2:
367 case Builtin::BI__sync_fetch_and_xor_4:
368 case Builtin::BI__sync_fetch_and_xor_8:
369 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000370 case Builtin::BI__sync_fetch_and_nand:
371 case Builtin::BI__sync_fetch_and_nand_1:
372 case Builtin::BI__sync_fetch_and_nand_2:
373 case Builtin::BI__sync_fetch_and_nand_4:
374 case Builtin::BI__sync_fetch_and_nand_8:
375 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000376 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000377 case Builtin::BI__sync_add_and_fetch_1:
378 case Builtin::BI__sync_add_and_fetch_2:
379 case Builtin::BI__sync_add_and_fetch_4:
380 case Builtin::BI__sync_add_and_fetch_8:
381 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000382 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000383 case Builtin::BI__sync_sub_and_fetch_1:
384 case Builtin::BI__sync_sub_and_fetch_2:
385 case Builtin::BI__sync_sub_and_fetch_4:
386 case Builtin::BI__sync_sub_and_fetch_8:
387 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000388 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000389 case Builtin::BI__sync_and_and_fetch_1:
390 case Builtin::BI__sync_and_and_fetch_2:
391 case Builtin::BI__sync_and_and_fetch_4:
392 case Builtin::BI__sync_and_and_fetch_8:
393 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000394 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000395 case Builtin::BI__sync_or_and_fetch_1:
396 case Builtin::BI__sync_or_and_fetch_2:
397 case Builtin::BI__sync_or_and_fetch_4:
398 case Builtin::BI__sync_or_and_fetch_8:
399 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000400 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000401 case Builtin::BI__sync_xor_and_fetch_1:
402 case Builtin::BI__sync_xor_and_fetch_2:
403 case Builtin::BI__sync_xor_and_fetch_4:
404 case Builtin::BI__sync_xor_and_fetch_8:
405 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000406 case Builtin::BI__sync_nand_and_fetch:
407 case Builtin::BI__sync_nand_and_fetch_1:
408 case Builtin::BI__sync_nand_and_fetch_2:
409 case Builtin::BI__sync_nand_and_fetch_4:
410 case Builtin::BI__sync_nand_and_fetch_8:
411 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000412 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000413 case Builtin::BI__sync_val_compare_and_swap_1:
414 case Builtin::BI__sync_val_compare_and_swap_2:
415 case Builtin::BI__sync_val_compare_and_swap_4:
416 case Builtin::BI__sync_val_compare_and_swap_8:
417 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000418 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000419 case Builtin::BI__sync_bool_compare_and_swap_1:
420 case Builtin::BI__sync_bool_compare_and_swap_2:
421 case Builtin::BI__sync_bool_compare_and_swap_4:
422 case Builtin::BI__sync_bool_compare_and_swap_8:
423 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000424 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000425 case Builtin::BI__sync_lock_test_and_set_1:
426 case Builtin::BI__sync_lock_test_and_set_2:
427 case Builtin::BI__sync_lock_test_and_set_4:
428 case Builtin::BI__sync_lock_test_and_set_8:
429 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000430 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000431 case Builtin::BI__sync_lock_release_1:
432 case Builtin::BI__sync_lock_release_2:
433 case Builtin::BI__sync_lock_release_4:
434 case Builtin::BI__sync_lock_release_8:
435 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000436 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000437 case Builtin::BI__sync_swap_1:
438 case Builtin::BI__sync_swap_2:
439 case Builtin::BI__sync_swap_4:
440 case Builtin::BI__sync_swap_8:
441 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000442 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000443#define BUILTIN(ID, TYPE, ATTRS)
444#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
445 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000446 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000447#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000448 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000449 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000450 return ExprError();
451 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000452 case Builtin::BI__builtin_addressof:
453 if (SemaBuiltinAddressof(*this, TheCall))
454 return ExprError();
455 break;
Richard Smith760520b2014-06-03 23:27:44 +0000456 case Builtin::BI__builtin_operator_new:
457 case Builtin::BI__builtin_operator_delete:
458 if (!getLangOpts().CPlusPlus) {
459 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
460 << (BuiltinID == Builtin::BI__builtin_operator_new
461 ? "__builtin_operator_new"
462 : "__builtin_operator_delete")
463 << "C++";
464 return ExprError();
465 }
466 // CodeGen assumes it can find the global new and delete to call,
467 // so ensure that they are declared.
468 DeclareGlobalNewDelete();
469 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000470
471 // check secure string manipulation functions where overflows
472 // are detectable at compile time
473 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000474 case Builtin::BI__builtin___memmove_chk:
475 case Builtin::BI__builtin___memset_chk:
476 case Builtin::BI__builtin___strlcat_chk:
477 case Builtin::BI__builtin___strlcpy_chk:
478 case Builtin::BI__builtin___strncat_chk:
479 case Builtin::BI__builtin___strncpy_chk:
480 case Builtin::BI__builtin___stpncpy_chk:
481 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
482 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000483 case Builtin::BI__builtin___memccpy_chk:
484 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
485 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000486 case Builtin::BI__builtin___snprintf_chk:
487 case Builtin::BI__builtin___vsnprintf_chk:
488 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
489 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000490
491 case Builtin::BI__builtin_call_with_static_chain:
492 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
493 return ExprError();
494 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000495
496 case Builtin::BI__exception_code:
497 case Builtin::BI_exception_code: {
498 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
499 diag::err_seh___except_block))
500 return ExprError();
501 break;
502 }
503 case Builtin::BI__exception_info:
504 case Builtin::BI_exception_info: {
505 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
506 diag::err_seh___except_filter))
507 return ExprError();
508 break;
509 }
510
David Majnemerba3e5ec2015-03-13 18:26:17 +0000511 case Builtin::BI__GetExceptionInfo:
512 if (checkArgCount(*this, TheCall, 1))
513 return ExprError();
514
515 if (CheckCXXThrowOperand(
516 TheCall->getLocStart(),
517 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
518 TheCall))
519 return ExprError();
520
521 TheCall->setType(Context.VoidPtrTy);
522 break;
523
Nate Begeman4904e322010-06-08 02:47:44 +0000524 }
Richard Smith760520b2014-06-03 23:27:44 +0000525
Nate Begeman4904e322010-06-08 02:47:44 +0000526 // Since the target specific builtins for each arch overlap, only check those
527 // of the arch we are compiling for.
528 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000529 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000530 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000531 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000532 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000533 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000534 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
535 return ExprError();
536 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000537 case llvm::Triple::aarch64:
538 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000539 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000540 return ExprError();
541 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000542 case llvm::Triple::mips:
543 case llvm::Triple::mipsel:
544 case llvm::Triple::mips64:
545 case llvm::Triple::mips64el:
546 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
547 return ExprError();
548 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +0000549 case llvm::Triple::systemz:
550 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
551 return ExprError();
552 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000553 case llvm::Triple::x86:
554 case llvm::Triple::x86_64:
555 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
556 return ExprError();
557 break;
Kit Bartone50adcb2015-03-30 19:40:59 +0000558 case llvm::Triple::ppc:
559 case llvm::Triple::ppc64:
560 case llvm::Triple::ppc64le:
561 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
562 return ExprError();
563 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000564 default:
565 break;
566 }
567 }
568
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000569 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000570}
571
Nate Begeman91e1fea2010-06-14 05:21:25 +0000572// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000573static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000574 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000575 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000576 switch (Type.getEltType()) {
577 case NeonTypeFlags::Int8:
578 case NeonTypeFlags::Poly8:
579 return shift ? 7 : (8 << IsQuad) - 1;
580 case NeonTypeFlags::Int16:
581 case NeonTypeFlags::Poly16:
582 return shift ? 15 : (4 << IsQuad) - 1;
583 case NeonTypeFlags::Int32:
584 return shift ? 31 : (2 << IsQuad) - 1;
585 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000586 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000587 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000588 case NeonTypeFlags::Poly128:
589 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000590 case NeonTypeFlags::Float16:
591 assert(!shift && "cannot shift float types!");
592 return (4 << IsQuad) - 1;
593 case NeonTypeFlags::Float32:
594 assert(!shift && "cannot shift float types!");
595 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000596 case NeonTypeFlags::Float64:
597 assert(!shift && "cannot shift float types!");
598 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000599 }
David Blaikie8a40f702012-01-17 06:56:22 +0000600 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000601}
602
Bob Wilsone4d77232011-11-08 05:04:11 +0000603/// getNeonEltType - Return the QualType corresponding to the elements of
604/// the vector type specified by the NeonTypeFlags. This is used to check
605/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000606static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000607 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000608 switch (Flags.getEltType()) {
609 case NeonTypeFlags::Int8:
610 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
611 case NeonTypeFlags::Int16:
612 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
613 case NeonTypeFlags::Int32:
614 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
615 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000616 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000617 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
618 else
619 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
620 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000621 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000622 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000623 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000624 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000625 case NeonTypeFlags::Poly64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000626 return Context.UnsignedLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000627 case NeonTypeFlags::Poly128:
628 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000629 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000630 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000631 case NeonTypeFlags::Float32:
632 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000633 case NeonTypeFlags::Float64:
634 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000635 }
David Blaikie8a40f702012-01-17 06:56:22 +0000636 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000637}
638
Tim Northover12670412014-02-19 10:37:05 +0000639bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000640 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000641 uint64_t mask = 0;
642 unsigned TV = 0;
643 int PtrArgNum = -1;
644 bool HasConstPtr = false;
645 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000646#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000647#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000648#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000649 }
650
651 // For NEON intrinsics which are overloaded on vector element type, validate
652 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000653 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000654 if (mask) {
655 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
656 return true;
657
658 TV = Result.getLimitedValue(64);
659 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
660 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000661 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000662 }
663
664 if (PtrArgNum >= 0) {
665 // Check that pointer arguments have the specified type.
666 Expr *Arg = TheCall->getArg(PtrArgNum);
667 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
668 Arg = ICE->getSubExpr();
669 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
670 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000671
Tim Northovera2ee4332014-03-29 15:09:45 +0000672 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000673 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000674 bool IsInt64Long =
675 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
676 QualType EltTy =
677 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000678 if (HasConstPtr)
679 EltTy = EltTy.withConst();
680 QualType LHSTy = Context.getPointerType(EltTy);
681 AssignConvertType ConvTy;
682 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
683 if (RHS.isInvalid())
684 return true;
685 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
686 RHS.get(), AA_Assigning))
687 return true;
688 }
689
690 // For NEON intrinsics which take an immediate value as part of the
691 // instruction, range check them here.
692 unsigned i = 0, l = 0, u = 0;
693 switch (BuiltinID) {
694 default:
695 return false;
Tim Northover12670412014-02-19 10:37:05 +0000696#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000697#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000698#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000699 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000700
Richard Sandiford28940af2014-04-16 08:47:51 +0000701 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000702}
703
Tim Northovera2ee4332014-03-29 15:09:45 +0000704bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
705 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000706 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000707 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000708 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000709 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000710 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000711 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
712 BuiltinID == AArch64::BI__builtin_arm_strex ||
713 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000714 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000715 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000716 BuiltinID == ARM::BI__builtin_arm_ldaex ||
717 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
718 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000719
720 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
721
722 // Ensure that we have the proper number of arguments.
723 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
724 return true;
725
726 // Inspect the pointer argument of the atomic builtin. This should always be
727 // a pointer type, whose element is an integral scalar or pointer type.
728 // Because it is a pointer type, we don't have to worry about any implicit
729 // casts here.
730 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
731 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
732 if (PointerArgRes.isInvalid())
733 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000734 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000735
736 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
737 if (!pointerType) {
738 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
739 << PointerArg->getType() << PointerArg->getSourceRange();
740 return true;
741 }
742
743 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
744 // task is to insert the appropriate casts into the AST. First work out just
745 // what the appropriate type is.
746 QualType ValType = pointerType->getPointeeType();
747 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
748 if (IsLdrex)
749 AddrType.addConst();
750
751 // Issue a warning if the cast is dodgy.
752 CastKind CastNeeded = CK_NoOp;
753 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
754 CastNeeded = CK_BitCast;
755 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
756 << PointerArg->getType()
757 << Context.getPointerType(AddrType)
758 << AA_Passing << PointerArg->getSourceRange();
759 }
760
761 // Finally, do the cast and replace the argument with the corrected version.
762 AddrType = Context.getPointerType(AddrType);
763 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
764 if (PointerArgRes.isInvalid())
765 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000766 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000767
768 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
769
770 // In general, we allow ints, floats and pointers to be loaded and stored.
771 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
772 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
773 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
774 << PointerArg->getType() << PointerArg->getSourceRange();
775 return true;
776 }
777
778 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000779 if (Context.getTypeSize(ValType) > MaxWidth) {
780 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000781 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
782 << PointerArg->getType() << PointerArg->getSourceRange();
783 return true;
784 }
785
786 switch (ValType.getObjCLifetime()) {
787 case Qualifiers::OCL_None:
788 case Qualifiers::OCL_ExplicitNone:
789 // okay
790 break;
791
792 case Qualifiers::OCL_Weak:
793 case Qualifiers::OCL_Strong:
794 case Qualifiers::OCL_Autoreleasing:
795 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
796 << ValType << PointerArg->getSourceRange();
797 return true;
798 }
799
800
801 if (IsLdrex) {
802 TheCall->setType(ValType);
803 return false;
804 }
805
806 // Initialize the argument to be stored.
807 ExprResult ValArg = TheCall->getArg(0);
808 InitializedEntity Entity = InitializedEntity::InitializeParameter(
809 Context, ValType, /*consume*/ false);
810 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
811 if (ValArg.isInvalid())
812 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000813 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000814
815 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
816 // but the custom checker bypasses all default analysis.
817 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000818 return false;
819}
820
Nate Begeman4904e322010-06-08 02:47:44 +0000821bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000822 llvm::APSInt Result;
823
Tim Northover6aacd492013-07-16 09:47:53 +0000824 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000825 BuiltinID == ARM::BI__builtin_arm_ldaex ||
826 BuiltinID == ARM::BI__builtin_arm_strex ||
827 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000828 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000829 }
830
Yi Kong26d104a2014-08-13 19:18:14 +0000831 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
832 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
833 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
834 }
835
Tim Northover12670412014-02-19 10:37:05 +0000836 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
837 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000838
Yi Kong4efadfb2014-07-03 16:01:25 +0000839 // For intrinsics which take an immediate value as part of the instruction,
840 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000841 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000842 switch (BuiltinID) {
843 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000844 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
845 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000846 case ARM::BI__builtin_arm_vcvtr_f:
847 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000848 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +0000849 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +0000850 case ARM::BI__builtin_arm_isb:
851 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000852 }
Nate Begemand773fe62010-06-13 04:47:52 +0000853
Nate Begemanf568b072010-08-03 21:32:34 +0000854 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000855 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000856}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000857
Tim Northover573cbee2014-05-24 12:52:07 +0000858bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000859 CallExpr *TheCall) {
860 llvm::APSInt Result;
861
Tim Northover573cbee2014-05-24 12:52:07 +0000862 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000863 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
864 BuiltinID == AArch64::BI__builtin_arm_strex ||
865 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000866 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
867 }
868
Yi Konga5548432014-08-13 19:18:20 +0000869 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
870 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
871 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
872 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
873 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
874 }
875
Tim Northovera2ee4332014-03-29 15:09:45 +0000876 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
877 return true;
878
Yi Kong19a29ac2014-07-17 10:52:06 +0000879 // For intrinsics which take an immediate value as part of the instruction,
880 // range check them here.
881 unsigned i = 0, l = 0, u = 0;
882 switch (BuiltinID) {
883 default: return false;
884 case AArch64::BI__builtin_arm_dmb:
885 case AArch64::BI__builtin_arm_dsb:
886 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
887 }
888
Yi Kong19a29ac2014-07-17 10:52:06 +0000889 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +0000890}
891
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000892bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
893 unsigned i = 0, l = 0, u = 0;
894 switch (BuiltinID) {
895 default: return false;
896 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
897 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000898 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
899 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
900 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
901 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
902 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000903 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000904
Richard Sandiford28940af2014-04-16 08:47:51 +0000905 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000906}
907
Kit Bartone50adcb2015-03-30 19:40:59 +0000908bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
909 unsigned i = 0, l = 0, u = 0;
910 switch (BuiltinID) {
911 default: return false;
912 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
913 case PPC::BI__builtin_altivec_crypto_vshasigmad:
914 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
915 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
916 case PPC::BI__builtin_tbegin:
917 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
918 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
919 case PPC::BI__builtin_tabortwc:
920 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
921 case PPC::BI__builtin_tabortwci:
922 case PPC::BI__builtin_tabortdci:
923 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
924 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
925 }
926 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
927}
928
Ulrich Weigand3a610eb2015-04-01 12:54:25 +0000929bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
930 CallExpr *TheCall) {
931 if (BuiltinID == SystemZ::BI__builtin_tabort) {
932 Expr *Arg = TheCall->getArg(0);
933 llvm::APSInt AbortCode(32);
934 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
935 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
936 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
937 << Arg->getSourceRange();
938 }
939
940 return false;
941}
942
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000943bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topperdd84ec52014-12-27 07:00:08 +0000944 unsigned i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000945 switch (BuiltinID) {
Craig Topperdd84ec52014-12-27 07:00:08 +0000946 default: return false;
947 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
Craig Topper16015252015-01-31 06:31:23 +0000948 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
Craig Topper1a8b0472015-01-31 08:57:52 +0000949 case X86::BI__builtin_ia32_vpermil2pd:
950 case X86::BI__builtin_ia32_vpermil2pd256:
951 case X86::BI__builtin_ia32_vpermil2ps:
952 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
Craig Topper95b0d732015-01-25 23:30:05 +0000953 case X86::BI__builtin_ia32_cmpb128_mask:
954 case X86::BI__builtin_ia32_cmpw128_mask:
955 case X86::BI__builtin_ia32_cmpd128_mask:
956 case X86::BI__builtin_ia32_cmpq128_mask:
957 case X86::BI__builtin_ia32_cmpb256_mask:
958 case X86::BI__builtin_ia32_cmpw256_mask:
959 case X86::BI__builtin_ia32_cmpd256_mask:
960 case X86::BI__builtin_ia32_cmpq256_mask:
961 case X86::BI__builtin_ia32_cmpb512_mask:
962 case X86::BI__builtin_ia32_cmpw512_mask:
963 case X86::BI__builtin_ia32_cmpd512_mask:
964 case X86::BI__builtin_ia32_cmpq512_mask:
965 case X86::BI__builtin_ia32_ucmpb128_mask:
966 case X86::BI__builtin_ia32_ucmpw128_mask:
967 case X86::BI__builtin_ia32_ucmpd128_mask:
968 case X86::BI__builtin_ia32_ucmpq128_mask:
969 case X86::BI__builtin_ia32_ucmpb256_mask:
970 case X86::BI__builtin_ia32_ucmpw256_mask:
971 case X86::BI__builtin_ia32_ucmpd256_mask:
972 case X86::BI__builtin_ia32_ucmpq256_mask:
973 case X86::BI__builtin_ia32_ucmpb512_mask:
974 case X86::BI__builtin_ia32_ucmpw512_mask:
975 case X86::BI__builtin_ia32_ucmpd512_mask:
976 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
Craig Topper16015252015-01-31 06:31:23 +0000977 case X86::BI__builtin_ia32_roundps:
978 case X86::BI__builtin_ia32_roundpd:
979 case X86::BI__builtin_ia32_roundps256:
980 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
981 case X86::BI__builtin_ia32_roundss:
982 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
983 case X86::BI__builtin_ia32_cmpps:
984 case X86::BI__builtin_ia32_cmpss:
985 case X86::BI__builtin_ia32_cmppd:
986 case X86::BI__builtin_ia32_cmpsd:
987 case X86::BI__builtin_ia32_cmpps256:
988 case X86::BI__builtin_ia32_cmppd256:
989 case X86::BI__builtin_ia32_cmpps512_mask:
990 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +0000991 case X86::BI__builtin_ia32_vpcomub:
992 case X86::BI__builtin_ia32_vpcomuw:
993 case X86::BI__builtin_ia32_vpcomud:
994 case X86::BI__builtin_ia32_vpcomuq:
995 case X86::BI__builtin_ia32_vpcomb:
996 case X86::BI__builtin_ia32_vpcomw:
997 case X86::BI__builtin_ia32_vpcomd:
998 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000999 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001000 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001001}
1002
Richard Smith55ce3522012-06-25 20:30:08 +00001003/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1004/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1005/// Returns true when the format fits the function and the FormatStringInfo has
1006/// been populated.
1007bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1008 FormatStringInfo *FSI) {
1009 FSI->HasVAListArg = Format->getFirstArg() == 0;
1010 FSI->FormatIdx = Format->getFormatIdx() - 1;
1011 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001012
Richard Smith55ce3522012-06-25 20:30:08 +00001013 // The way the format attribute works in GCC, the implicit this argument
1014 // of member functions is counted. However, it doesn't appear in our own
1015 // lists, so decrement format_idx in that case.
1016 if (IsCXXMember) {
1017 if(FSI->FormatIdx == 0)
1018 return false;
1019 --FSI->FormatIdx;
1020 if (FSI->FirstDataArg != 0)
1021 --FSI->FirstDataArg;
1022 }
1023 return true;
1024}
Mike Stump11289f42009-09-09 15:08:12 +00001025
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001026/// Checks if a the given expression evaluates to null.
1027///
1028/// \brief Returns true if the value evaluates to null.
1029static bool CheckNonNullExpr(Sema &S,
1030 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001031 // As a special case, transparent unions initialized with zero are
1032 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001033 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001034 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1035 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001036 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001037 if (const InitListExpr *ILE =
1038 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001039 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001040 }
1041
1042 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001043 return (!Expr->isValueDependent() &&
1044 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1045 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001046}
1047
1048static void CheckNonNullArgument(Sema &S,
1049 const Expr *ArgExpr,
1050 SourceLocation CallSiteLoc) {
1051 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001052 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
1053}
1054
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001055bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1056 FormatStringInfo FSI;
1057 if ((GetFormatStringType(Format) == FST_NSString) &&
1058 getFormatStringInfo(Format, false, &FSI)) {
1059 Idx = FSI.FormatIdx;
1060 return true;
1061 }
1062 return false;
1063}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001064/// \brief Diagnose use of %s directive in an NSString which is being passed
1065/// as formatting string to formatting method.
1066static void
1067DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1068 const NamedDecl *FDecl,
1069 Expr **Args,
1070 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001071 unsigned Idx = 0;
1072 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001073 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1074 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001075 Idx = 2;
1076 Format = true;
1077 }
1078 else
1079 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1080 if (S.GetFormatNSStringIdx(I, Idx)) {
1081 Format = true;
1082 break;
1083 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001084 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001085 if (!Format || NumArgs <= Idx)
1086 return;
1087 const Expr *FormatExpr = Args[Idx];
1088 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1089 FormatExpr = CSCE->getSubExpr();
1090 const StringLiteral *FormatString;
1091 if (const ObjCStringLiteral *OSL =
1092 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1093 FormatString = OSL->getString();
1094 else
1095 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1096 if (!FormatString)
1097 return;
1098 if (S.FormatStringHasSArg(FormatString)) {
1099 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1100 << "%s" << 1 << 1;
1101 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1102 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001103 }
1104}
1105
Ted Kremenek2bc73332014-01-17 06:24:43 +00001106static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001107 const NamedDecl *FDecl,
Richard Smith588bd9b2014-08-27 04:59:42 +00001108 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001109 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +00001110 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001111 llvm::SmallBitVector NonNullArgs;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001112 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001113 if (!NonNull->args_size()) {
1114 // Easy case: all pointer arguments are nonnull.
1115 for (const auto *Arg : Args)
Hal Finkelee90a222014-09-26 05:04:30 +00001116 if (S.isValidPointerAttrType(Arg->getType()))
Richard Smith588bd9b2014-08-27 04:59:42 +00001117 CheckNonNullArgument(S, Arg, CallSiteLoc);
1118 return;
1119 }
1120
1121 for (unsigned Val : NonNull->args()) {
1122 if (Val >= Args.size())
1123 continue;
1124 if (NonNullArgs.empty())
1125 NonNullArgs.resize(Args.size());
1126 NonNullArgs.set(Val);
1127 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001128 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001129
1130 // Check the attributes on the parameters.
1131 ArrayRef<ParmVarDecl*> parms;
1132 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1133 parms = FD->parameters();
1134 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
1135 parms = MD->parameters();
1136
Richard Smith588bd9b2014-08-27 04:59:42 +00001137 unsigned ArgIndex = 0;
Ted Kremenek9aedc152014-01-17 06:24:56 +00001138 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
Richard Smith588bd9b2014-08-27 04:59:42 +00001139 I != E; ++I, ++ArgIndex) {
Ted Kremenek9aedc152014-01-17 06:24:56 +00001140 const ParmVarDecl *PVD = *I;
Richard Smith588bd9b2014-08-27 04:59:42 +00001141 if (PVD->hasAttr<NonNullAttr>() ||
1142 (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
1143 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek9aedc152014-01-17 06:24:56 +00001144 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001145
1146 // In case this is a variadic call, check any remaining arguments.
1147 for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
1148 if (NonNullArgs[ArgIndex])
1149 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +00001150}
1151
Richard Smith55ce3522012-06-25 20:30:08 +00001152/// Handles the checks for format strings, non-POD arguments to vararg
1153/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00001154void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
1155 unsigned NumParams, bool IsMemberFunction,
1156 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001157 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001158 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001159 if (CurContext->isDependentContext())
1160 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001161
Ted Kremenekb8176da2010-09-09 04:33:05 +00001162 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001163 llvm::SmallBitVector CheckedVarArgs;
1164 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001165 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001166 // Only create vector if there are format attributes.
1167 CheckedVarArgs.resize(Args.size());
1168
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001169 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001170 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001171 }
Richard Smithd7293d72013-08-05 18:49:43 +00001172 }
Richard Smith55ce3522012-06-25 20:30:08 +00001173
1174 // Refuse POD arguments that weren't caught by the format string
1175 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001176 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001177 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001178 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001179 if (const Expr *Arg = Args[ArgIdx]) {
1180 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1181 checkVariadicArgument(Arg, CallType);
1182 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001183 }
Richard Smithd7293d72013-08-05 18:49:43 +00001184 }
Mike Stump11289f42009-09-09 15:08:12 +00001185
Richard Trieu41bc0992013-06-22 00:20:41 +00001186 if (FDecl) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001187 CheckNonNullArguments(*this, FDecl, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001188
Richard Trieu41bc0992013-06-22 00:20:41 +00001189 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001190 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1191 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001192 }
Richard Smith55ce3522012-06-25 20:30:08 +00001193}
1194
1195/// CheckConstructorCall - Check a constructor call for correctness and safety
1196/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001197void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1198 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001199 const FunctionProtoType *Proto,
1200 SourceLocation Loc) {
1201 VariadicCallType CallType =
1202 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +00001203 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +00001204 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
1205}
1206
1207/// CheckFunctionCall - Check a direct function call for various correctness
1208/// and safety properties not strictly enforced by the C type system.
1209bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1210 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001211 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1212 isa<CXXMethodDecl>(FDecl);
1213 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1214 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001215 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1216 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001217 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +00001218 Expr** Args = TheCall->getArgs();
1219 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001220 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001221 // If this is a call to a member operator, hide the first argument
1222 // from checkCall.
1223 // FIXME: Our choice of AST representation here is less than ideal.
1224 ++Args;
1225 --NumArgs;
1226 }
Craig Topper8c2a2a02014-08-30 16:55:39 +00001227 checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +00001228 IsMemberFunction, TheCall->getRParenLoc(),
1229 TheCall->getCallee()->getSourceRange(), CallType);
1230
1231 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1232 // None of the checks below are needed for functions that don't have
1233 // simple names (e.g., C++ conversion functions).
1234 if (!FnInfo)
1235 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001236
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001237 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001238 if (getLangOpts().ObjC1)
1239 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001240
Anna Zaks22122702012-01-17 00:37:07 +00001241 unsigned CMId = FDecl->getMemoryFunctionKind();
1242 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001243 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001244
Anna Zaks201d4892012-01-13 21:52:01 +00001245 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001246 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001247 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001248 else if (CMId == Builtin::BIstrncat)
1249 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001250 else
Anna Zaks22122702012-01-17 00:37:07 +00001251 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001252
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001253 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001254}
1255
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001256bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001257 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001258 VariadicCallType CallType =
1259 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001260
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001261 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +00001262 /*IsMemberFunction=*/false,
1263 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001264
1265 return false;
1266}
1267
Richard Trieu664c4c62013-06-20 21:03:13 +00001268bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1269 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001270 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
1271 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001272 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001273
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001274 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +00001275 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001276 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001277
Richard Trieu664c4c62013-06-20 21:03:13 +00001278 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001279 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001280 CallType = VariadicDoesNotApply;
1281 } else if (Ty->isBlockPointerType()) {
1282 CallType = VariadicBlock;
1283 } else { // Ty->isFunctionPointerType()
1284 CallType = VariadicFunction;
1285 }
Alp Toker9cacbab2014-01-20 20:26:09 +00001286 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001287
Craig Topper8c2a2a02014-08-30 16:55:39 +00001288 checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
1289 TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001290 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001291 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001292
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001293 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001294}
1295
Richard Trieu41bc0992013-06-22 00:20:41 +00001296/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1297/// such as function pointers returned from functions.
1298bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001299 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001300 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001301 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +00001302
Craig Topperc3ec1492014-05-26 06:22:03 +00001303 checkCall(/*FDecl=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001304 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001305 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001306 TheCall->getCallee()->getSourceRange(), CallType);
1307
1308 return false;
1309}
1310
Tim Northovere94a34c2014-03-11 10:49:14 +00001311static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1312 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1313 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1314 return false;
1315
1316 switch (Op) {
1317 case AtomicExpr::AO__c11_atomic_init:
1318 llvm_unreachable("There is no ordering argument for an init");
1319
1320 case AtomicExpr::AO__c11_atomic_load:
1321 case AtomicExpr::AO__atomic_load_n:
1322 case AtomicExpr::AO__atomic_load:
1323 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1324 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1325
1326 case AtomicExpr::AO__c11_atomic_store:
1327 case AtomicExpr::AO__atomic_store:
1328 case AtomicExpr::AO__atomic_store_n:
1329 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1330 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1331 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1332
1333 default:
1334 return true;
1335 }
1336}
1337
Richard Smithfeea8832012-04-12 05:08:17 +00001338ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1339 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001340 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1341 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001342
Richard Smithfeea8832012-04-12 05:08:17 +00001343 // All these operations take one of the following forms:
1344 enum {
1345 // C __c11_atomic_init(A *, C)
1346 Init,
1347 // C __c11_atomic_load(A *, int)
1348 Load,
1349 // void __atomic_load(A *, CP, int)
1350 Copy,
1351 // C __c11_atomic_add(A *, M, int)
1352 Arithmetic,
1353 // C __atomic_exchange_n(A *, CP, int)
1354 Xchg,
1355 // void __atomic_exchange(A *, C *, CP, int)
1356 GNUXchg,
1357 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1358 C11CmpXchg,
1359 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1360 GNUCmpXchg
1361 } Form = Init;
1362 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1363 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1364 // where:
1365 // C is an appropriate type,
1366 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1367 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1368 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1369 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001370
Gabor Horvath98bd0982015-03-16 09:59:54 +00001371 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1372 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1373 AtomicExpr::AO__atomic_load,
1374 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00001375 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1376 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1377 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1378 Op == AtomicExpr::AO__atomic_store_n ||
1379 Op == AtomicExpr::AO__atomic_exchange_n ||
1380 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1381 bool IsAddSub = false;
1382
1383 switch (Op) {
1384 case AtomicExpr::AO__c11_atomic_init:
1385 Form = Init;
1386 break;
1387
1388 case AtomicExpr::AO__c11_atomic_load:
1389 case AtomicExpr::AO__atomic_load_n:
1390 Form = Load;
1391 break;
1392
1393 case AtomicExpr::AO__c11_atomic_store:
1394 case AtomicExpr::AO__atomic_load:
1395 case AtomicExpr::AO__atomic_store:
1396 case AtomicExpr::AO__atomic_store_n:
1397 Form = Copy;
1398 break;
1399
1400 case AtomicExpr::AO__c11_atomic_fetch_add:
1401 case AtomicExpr::AO__c11_atomic_fetch_sub:
1402 case AtomicExpr::AO__atomic_fetch_add:
1403 case AtomicExpr::AO__atomic_fetch_sub:
1404 case AtomicExpr::AO__atomic_add_fetch:
1405 case AtomicExpr::AO__atomic_sub_fetch:
1406 IsAddSub = true;
1407 // Fall through.
1408 case AtomicExpr::AO__c11_atomic_fetch_and:
1409 case AtomicExpr::AO__c11_atomic_fetch_or:
1410 case AtomicExpr::AO__c11_atomic_fetch_xor:
1411 case AtomicExpr::AO__atomic_fetch_and:
1412 case AtomicExpr::AO__atomic_fetch_or:
1413 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001414 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001415 case AtomicExpr::AO__atomic_and_fetch:
1416 case AtomicExpr::AO__atomic_or_fetch:
1417 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001418 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001419 Form = Arithmetic;
1420 break;
1421
1422 case AtomicExpr::AO__c11_atomic_exchange:
1423 case AtomicExpr::AO__atomic_exchange_n:
1424 Form = Xchg;
1425 break;
1426
1427 case AtomicExpr::AO__atomic_exchange:
1428 Form = GNUXchg;
1429 break;
1430
1431 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1432 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1433 Form = C11CmpXchg;
1434 break;
1435
1436 case AtomicExpr::AO__atomic_compare_exchange:
1437 case AtomicExpr::AO__atomic_compare_exchange_n:
1438 Form = GNUCmpXchg;
1439 break;
1440 }
1441
1442 // Check we have the right number of arguments.
1443 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001444 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001445 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001446 << TheCall->getCallee()->getSourceRange();
1447 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001448 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1449 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001450 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001451 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001452 << TheCall->getCallee()->getSourceRange();
1453 return ExprError();
1454 }
1455
Richard Smithfeea8832012-04-12 05:08:17 +00001456 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001457 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001458 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1459 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1460 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001461 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001462 << Ptr->getType() << Ptr->getSourceRange();
1463 return ExprError();
1464 }
1465
Richard Smithfeea8832012-04-12 05:08:17 +00001466 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1467 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1468 QualType ValType = AtomTy; // 'C'
1469 if (IsC11) {
1470 if (!AtomTy->isAtomicType()) {
1471 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1472 << Ptr->getType() << Ptr->getSourceRange();
1473 return ExprError();
1474 }
Richard Smithe00921a2012-09-15 06:09:58 +00001475 if (AtomTy.isConstQualified()) {
1476 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1477 << Ptr->getType() << Ptr->getSourceRange();
1478 return ExprError();
1479 }
Richard Smithfeea8832012-04-12 05:08:17 +00001480 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001481 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001482
Richard Smithfeea8832012-04-12 05:08:17 +00001483 // For an arithmetic operation, the implied arithmetic must be well-formed.
1484 if (Form == Arithmetic) {
1485 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1486 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1487 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1488 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1489 return ExprError();
1490 }
1491 if (!IsAddSub && !ValType->isIntegerType()) {
1492 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1493 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1494 return ExprError();
1495 }
David Majnemere85cff82015-01-28 05:48:06 +00001496 if (IsC11 && ValType->isPointerType() &&
1497 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1498 diag::err_incomplete_type)) {
1499 return ExprError();
1500 }
Richard Smithfeea8832012-04-12 05:08:17 +00001501 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1502 // For __atomic_*_n operations, the value type must be a scalar integral or
1503 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001504 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001505 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1506 return ExprError();
1507 }
1508
Eli Friedmanaa769812013-09-11 03:49:34 +00001509 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1510 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001511 // For GNU atomics, require a trivially-copyable type. This is not part of
1512 // the GNU atomics specification, but we enforce it for sanity.
1513 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001514 << Ptr->getType() << Ptr->getSourceRange();
1515 return ExprError();
1516 }
1517
Richard Smithfeea8832012-04-12 05:08:17 +00001518 // FIXME: For any builtin other than a load, the ValType must not be
1519 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001520
1521 switch (ValType.getObjCLifetime()) {
1522 case Qualifiers::OCL_None:
1523 case Qualifiers::OCL_ExplicitNone:
1524 // okay
1525 break;
1526
1527 case Qualifiers::OCL_Weak:
1528 case Qualifiers::OCL_Strong:
1529 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001530 // FIXME: Can this happen? By this point, ValType should be known
1531 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001532 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1533 << ValType << Ptr->getSourceRange();
1534 return ExprError();
1535 }
1536
1537 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001538 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001539 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001540 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001541 ResultType = Context.BoolTy;
1542
Richard Smithfeea8832012-04-12 05:08:17 +00001543 // The type of a parameter passed 'by value'. In the GNU atomics, such
1544 // arguments are actually passed as pointers.
1545 QualType ByValType = ValType; // 'CP'
1546 if (!IsC11 && !IsN)
1547 ByValType = Ptr->getType();
1548
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001549 // The first argument --- the pointer --- has a fixed type; we
1550 // deduce the types of the rest of the arguments accordingly. Walk
1551 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001552 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001553 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001554 if (i < NumVals[Form] + 1) {
1555 switch (i) {
1556 case 1:
1557 // The second argument is the non-atomic operand. For arithmetic, this
1558 // is always passed by value, and for a compare_exchange it is always
1559 // passed by address. For the rest, GNU uses by-address and C11 uses
1560 // by-value.
1561 assert(Form != Load);
1562 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1563 Ty = ValType;
1564 else if (Form == Copy || Form == Xchg)
1565 Ty = ByValType;
1566 else if (Form == Arithmetic)
1567 Ty = Context.getPointerDiffType();
1568 else
1569 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1570 break;
1571 case 2:
1572 // The third argument to compare_exchange / GNU exchange is a
1573 // (pointer to a) desired value.
1574 Ty = ByValType;
1575 break;
1576 case 3:
1577 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1578 Ty = Context.BoolTy;
1579 break;
1580 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001581 } else {
1582 // The order(s) are always converted to int.
1583 Ty = Context.IntTy;
1584 }
Richard Smithfeea8832012-04-12 05:08:17 +00001585
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001586 InitializedEntity Entity =
1587 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001588 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001589 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1590 if (Arg.isInvalid())
1591 return true;
1592 TheCall->setArg(i, Arg.get());
1593 }
1594
Richard Smithfeea8832012-04-12 05:08:17 +00001595 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001596 SmallVector<Expr*, 5> SubExprs;
1597 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001598 switch (Form) {
1599 case Init:
1600 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001601 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001602 break;
1603 case Load:
1604 SubExprs.push_back(TheCall->getArg(1)); // Order
1605 break;
1606 case Copy:
1607 case Arithmetic:
1608 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001609 SubExprs.push_back(TheCall->getArg(2)); // Order
1610 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001611 break;
1612 case GNUXchg:
1613 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1614 SubExprs.push_back(TheCall->getArg(3)); // Order
1615 SubExprs.push_back(TheCall->getArg(1)); // Val1
1616 SubExprs.push_back(TheCall->getArg(2)); // Val2
1617 break;
1618 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001619 SubExprs.push_back(TheCall->getArg(3)); // Order
1620 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001621 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001622 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001623 break;
1624 case GNUCmpXchg:
1625 SubExprs.push_back(TheCall->getArg(4)); // Order
1626 SubExprs.push_back(TheCall->getArg(1)); // Val1
1627 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1628 SubExprs.push_back(TheCall->getArg(2)); // Val2
1629 SubExprs.push_back(TheCall->getArg(3)); // Weak
1630 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001631 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001632
1633 if (SubExprs.size() >= 2 && Form != Init) {
1634 llvm::APSInt Result(32);
1635 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1636 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001637 Diag(SubExprs[1]->getLocStart(),
1638 diag::warn_atomic_op_has_invalid_memory_order)
1639 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001640 }
1641
Fariborz Jahanian615de762013-05-28 17:37:39 +00001642 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1643 SubExprs, ResultType, Op,
1644 TheCall->getRParenLoc());
1645
1646 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1647 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1648 Context.AtomicUsesUnsupportedLibcall(AE))
1649 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1650 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001651
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001652 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001653}
1654
1655
John McCall29ad95b2011-08-27 01:09:30 +00001656/// checkBuiltinArgument - Given a call to a builtin function, perform
1657/// normal type-checking on the given argument, updating the call in
1658/// place. This is useful when a builtin function requires custom
1659/// type-checking for some of its arguments but not necessarily all of
1660/// them.
1661///
1662/// Returns true on error.
1663static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1664 FunctionDecl *Fn = E->getDirectCallee();
1665 assert(Fn && "builtin call without direct callee!");
1666
1667 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1668 InitializedEntity Entity =
1669 InitializedEntity::InitializeParameter(S.Context, Param);
1670
1671 ExprResult Arg = E->getArg(0);
1672 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1673 if (Arg.isInvalid())
1674 return true;
1675
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001676 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001677 return false;
1678}
1679
Chris Lattnerdc046542009-05-08 06:58:22 +00001680/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1681/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1682/// type of its first argument. The main ActOnCallExpr routines have already
1683/// promoted the types of arguments because all of these calls are prototyped as
1684/// void(...).
1685///
1686/// This function goes through and does final semantic checking for these
1687/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001688ExprResult
1689Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001690 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001691 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1692 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1693
1694 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001695 if (TheCall->getNumArgs() < 1) {
1696 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1697 << 0 << 1 << TheCall->getNumArgs()
1698 << TheCall->getCallee()->getSourceRange();
1699 return ExprError();
1700 }
Mike Stump11289f42009-09-09 15:08:12 +00001701
Chris Lattnerdc046542009-05-08 06:58:22 +00001702 // Inspect the first argument of the atomic builtin. This should always be
1703 // a pointer type, whose element is an integral scalar or pointer type.
1704 // Because it is a pointer type, we don't have to worry about any implicit
1705 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001706 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001707 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001708 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1709 if (FirstArgResult.isInvalid())
1710 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001711 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001712 TheCall->setArg(0, FirstArg);
1713
John McCall31168b02011-06-15 23:02:42 +00001714 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1715 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001716 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1717 << FirstArg->getType() << FirstArg->getSourceRange();
1718 return ExprError();
1719 }
Mike Stump11289f42009-09-09 15:08:12 +00001720
John McCall31168b02011-06-15 23:02:42 +00001721 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001722 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001723 !ValType->isBlockPointerType()) {
1724 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1725 << FirstArg->getType() << FirstArg->getSourceRange();
1726 return ExprError();
1727 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001728
John McCall31168b02011-06-15 23:02:42 +00001729 switch (ValType.getObjCLifetime()) {
1730 case Qualifiers::OCL_None:
1731 case Qualifiers::OCL_ExplicitNone:
1732 // okay
1733 break;
1734
1735 case Qualifiers::OCL_Weak:
1736 case Qualifiers::OCL_Strong:
1737 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001738 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001739 << ValType << FirstArg->getSourceRange();
1740 return ExprError();
1741 }
1742
John McCallb50451a2011-10-05 07:41:44 +00001743 // Strip any qualifiers off ValType.
1744 ValType = ValType.getUnqualifiedType();
1745
Chandler Carruth3973af72010-07-18 20:54:12 +00001746 // The majority of builtins return a value, but a few have special return
1747 // types, so allow them to override appropriately below.
1748 QualType ResultType = ValType;
1749
Chris Lattnerdc046542009-05-08 06:58:22 +00001750 // We need to figure out which concrete builtin this maps onto. For example,
1751 // __sync_fetch_and_add with a 2 byte object turns into
1752 // __sync_fetch_and_add_2.
1753#define BUILTIN_ROW(x) \
1754 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1755 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001756
Chris Lattnerdc046542009-05-08 06:58:22 +00001757 static const unsigned BuiltinIndices[][5] = {
1758 BUILTIN_ROW(__sync_fetch_and_add),
1759 BUILTIN_ROW(__sync_fetch_and_sub),
1760 BUILTIN_ROW(__sync_fetch_and_or),
1761 BUILTIN_ROW(__sync_fetch_and_and),
1762 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00001763 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00001764
Chris Lattnerdc046542009-05-08 06:58:22 +00001765 BUILTIN_ROW(__sync_add_and_fetch),
1766 BUILTIN_ROW(__sync_sub_and_fetch),
1767 BUILTIN_ROW(__sync_and_and_fetch),
1768 BUILTIN_ROW(__sync_or_and_fetch),
1769 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00001770 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001771
Chris Lattnerdc046542009-05-08 06:58:22 +00001772 BUILTIN_ROW(__sync_val_compare_and_swap),
1773 BUILTIN_ROW(__sync_bool_compare_and_swap),
1774 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001775 BUILTIN_ROW(__sync_lock_release),
1776 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001777 };
Mike Stump11289f42009-09-09 15:08:12 +00001778#undef BUILTIN_ROW
1779
Chris Lattnerdc046542009-05-08 06:58:22 +00001780 // Determine the index of the size.
1781 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001782 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001783 case 1: SizeIndex = 0; break;
1784 case 2: SizeIndex = 1; break;
1785 case 4: SizeIndex = 2; break;
1786 case 8: SizeIndex = 3; break;
1787 case 16: SizeIndex = 4; break;
1788 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001789 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1790 << FirstArg->getType() << FirstArg->getSourceRange();
1791 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001792 }
Mike Stump11289f42009-09-09 15:08:12 +00001793
Chris Lattnerdc046542009-05-08 06:58:22 +00001794 // Each of these builtins has one pointer argument, followed by some number of
1795 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1796 // that we ignore. Find out which row of BuiltinIndices to read from as well
1797 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001798 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001799 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00001800 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00001801 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001802 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001803 case Builtin::BI__sync_fetch_and_add:
1804 case Builtin::BI__sync_fetch_and_add_1:
1805 case Builtin::BI__sync_fetch_and_add_2:
1806 case Builtin::BI__sync_fetch_and_add_4:
1807 case Builtin::BI__sync_fetch_and_add_8:
1808 case Builtin::BI__sync_fetch_and_add_16:
1809 BuiltinIndex = 0;
1810 break;
1811
1812 case Builtin::BI__sync_fetch_and_sub:
1813 case Builtin::BI__sync_fetch_and_sub_1:
1814 case Builtin::BI__sync_fetch_and_sub_2:
1815 case Builtin::BI__sync_fetch_and_sub_4:
1816 case Builtin::BI__sync_fetch_and_sub_8:
1817 case Builtin::BI__sync_fetch_and_sub_16:
1818 BuiltinIndex = 1;
1819 break;
1820
1821 case Builtin::BI__sync_fetch_and_or:
1822 case Builtin::BI__sync_fetch_and_or_1:
1823 case Builtin::BI__sync_fetch_and_or_2:
1824 case Builtin::BI__sync_fetch_and_or_4:
1825 case Builtin::BI__sync_fetch_and_or_8:
1826 case Builtin::BI__sync_fetch_and_or_16:
1827 BuiltinIndex = 2;
1828 break;
1829
1830 case Builtin::BI__sync_fetch_and_and:
1831 case Builtin::BI__sync_fetch_and_and_1:
1832 case Builtin::BI__sync_fetch_and_and_2:
1833 case Builtin::BI__sync_fetch_and_and_4:
1834 case Builtin::BI__sync_fetch_and_and_8:
1835 case Builtin::BI__sync_fetch_and_and_16:
1836 BuiltinIndex = 3;
1837 break;
Mike Stump11289f42009-09-09 15:08:12 +00001838
Douglas Gregor73722482011-11-28 16:30:08 +00001839 case Builtin::BI__sync_fetch_and_xor:
1840 case Builtin::BI__sync_fetch_and_xor_1:
1841 case Builtin::BI__sync_fetch_and_xor_2:
1842 case Builtin::BI__sync_fetch_and_xor_4:
1843 case Builtin::BI__sync_fetch_and_xor_8:
1844 case Builtin::BI__sync_fetch_and_xor_16:
1845 BuiltinIndex = 4;
1846 break;
1847
Hal Finkeld2208b52014-10-02 20:53:50 +00001848 case Builtin::BI__sync_fetch_and_nand:
1849 case Builtin::BI__sync_fetch_and_nand_1:
1850 case Builtin::BI__sync_fetch_and_nand_2:
1851 case Builtin::BI__sync_fetch_and_nand_4:
1852 case Builtin::BI__sync_fetch_and_nand_8:
1853 case Builtin::BI__sync_fetch_and_nand_16:
1854 BuiltinIndex = 5;
1855 WarnAboutSemanticsChange = true;
1856 break;
1857
Douglas Gregor73722482011-11-28 16:30:08 +00001858 case Builtin::BI__sync_add_and_fetch:
1859 case Builtin::BI__sync_add_and_fetch_1:
1860 case Builtin::BI__sync_add_and_fetch_2:
1861 case Builtin::BI__sync_add_and_fetch_4:
1862 case Builtin::BI__sync_add_and_fetch_8:
1863 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001864 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00001865 break;
1866
1867 case Builtin::BI__sync_sub_and_fetch:
1868 case Builtin::BI__sync_sub_and_fetch_1:
1869 case Builtin::BI__sync_sub_and_fetch_2:
1870 case Builtin::BI__sync_sub_and_fetch_4:
1871 case Builtin::BI__sync_sub_and_fetch_8:
1872 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001873 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00001874 break;
1875
1876 case Builtin::BI__sync_and_and_fetch:
1877 case Builtin::BI__sync_and_and_fetch_1:
1878 case Builtin::BI__sync_and_and_fetch_2:
1879 case Builtin::BI__sync_and_and_fetch_4:
1880 case Builtin::BI__sync_and_and_fetch_8:
1881 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001882 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00001883 break;
1884
1885 case Builtin::BI__sync_or_and_fetch:
1886 case Builtin::BI__sync_or_and_fetch_1:
1887 case Builtin::BI__sync_or_and_fetch_2:
1888 case Builtin::BI__sync_or_and_fetch_4:
1889 case Builtin::BI__sync_or_and_fetch_8:
1890 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001891 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00001892 break;
1893
1894 case Builtin::BI__sync_xor_and_fetch:
1895 case Builtin::BI__sync_xor_and_fetch_1:
1896 case Builtin::BI__sync_xor_and_fetch_2:
1897 case Builtin::BI__sync_xor_and_fetch_4:
1898 case Builtin::BI__sync_xor_and_fetch_8:
1899 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001900 BuiltinIndex = 10;
1901 break;
1902
1903 case Builtin::BI__sync_nand_and_fetch:
1904 case Builtin::BI__sync_nand_and_fetch_1:
1905 case Builtin::BI__sync_nand_and_fetch_2:
1906 case Builtin::BI__sync_nand_and_fetch_4:
1907 case Builtin::BI__sync_nand_and_fetch_8:
1908 case Builtin::BI__sync_nand_and_fetch_16:
1909 BuiltinIndex = 11;
1910 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00001911 break;
Mike Stump11289f42009-09-09 15:08:12 +00001912
Chris Lattnerdc046542009-05-08 06:58:22 +00001913 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001914 case Builtin::BI__sync_val_compare_and_swap_1:
1915 case Builtin::BI__sync_val_compare_and_swap_2:
1916 case Builtin::BI__sync_val_compare_and_swap_4:
1917 case Builtin::BI__sync_val_compare_and_swap_8:
1918 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001919 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00001920 NumFixed = 2;
1921 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001922
Chris Lattnerdc046542009-05-08 06:58:22 +00001923 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001924 case Builtin::BI__sync_bool_compare_and_swap_1:
1925 case Builtin::BI__sync_bool_compare_and_swap_2:
1926 case Builtin::BI__sync_bool_compare_and_swap_4:
1927 case Builtin::BI__sync_bool_compare_and_swap_8:
1928 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001929 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001930 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001931 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001932 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001933
1934 case Builtin::BI__sync_lock_test_and_set:
1935 case Builtin::BI__sync_lock_test_and_set_1:
1936 case Builtin::BI__sync_lock_test_and_set_2:
1937 case Builtin::BI__sync_lock_test_and_set_4:
1938 case Builtin::BI__sync_lock_test_and_set_8:
1939 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001940 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00001941 break;
1942
Chris Lattnerdc046542009-05-08 06:58:22 +00001943 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001944 case Builtin::BI__sync_lock_release_1:
1945 case Builtin::BI__sync_lock_release_2:
1946 case Builtin::BI__sync_lock_release_4:
1947 case Builtin::BI__sync_lock_release_8:
1948 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001949 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00001950 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001951 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001952 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001953
1954 case Builtin::BI__sync_swap:
1955 case Builtin::BI__sync_swap_1:
1956 case Builtin::BI__sync_swap_2:
1957 case Builtin::BI__sync_swap_4:
1958 case Builtin::BI__sync_swap_8:
1959 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001960 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00001961 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001962 }
Mike Stump11289f42009-09-09 15:08:12 +00001963
Chris Lattnerdc046542009-05-08 06:58:22 +00001964 // Now that we know how many fixed arguments we expect, first check that we
1965 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001966 if (TheCall->getNumArgs() < 1+NumFixed) {
1967 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1968 << 0 << 1+NumFixed << TheCall->getNumArgs()
1969 << TheCall->getCallee()->getSourceRange();
1970 return ExprError();
1971 }
Mike Stump11289f42009-09-09 15:08:12 +00001972
Hal Finkeld2208b52014-10-02 20:53:50 +00001973 if (WarnAboutSemanticsChange) {
1974 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
1975 << TheCall->getCallee()->getSourceRange();
1976 }
1977
Chris Lattner5b9241b2009-05-08 15:36:58 +00001978 // Get the decl for the concrete builtin from this, we can tell what the
1979 // concrete integer type we should convert to is.
1980 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1981 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001982 FunctionDecl *NewBuiltinDecl;
1983 if (NewBuiltinID == BuiltinID)
1984 NewBuiltinDecl = FDecl;
1985 else {
1986 // Perform builtin lookup to avoid redeclaring it.
1987 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1988 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1989 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1990 assert(Res.getFoundDecl());
1991 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00001992 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001993 return ExprError();
1994 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001995
John McCallcf142162010-08-07 06:22:56 +00001996 // The first argument --- the pointer --- has a fixed type; we
1997 // deduce the types of the rest of the arguments accordingly. Walk
1998 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001999 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002000 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002001
Chris Lattnerdc046542009-05-08 06:58:22 +00002002 // GCC does an implicit conversion to the pointer or integer ValType. This
2003 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002004 // Initialize the argument.
2005 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2006 ValType, /*consume*/ false);
2007 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002008 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002009 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002010
Chris Lattnerdc046542009-05-08 06:58:22 +00002011 // Okay, we have something that *can* be converted to the right type. Check
2012 // to see if there is a potentially weird extension going on here. This can
2013 // happen when you do an atomic operation on something like an char* and
2014 // pass in 42. The 42 gets converted to char. This is even more strange
2015 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002016 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002017 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002018 }
Mike Stump11289f42009-09-09 15:08:12 +00002019
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002020 ASTContext& Context = this->getASTContext();
2021
2022 // Create a new DeclRefExpr to refer to the new decl.
2023 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2024 Context,
2025 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002026 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002027 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002028 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002029 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002030 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002031 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002032
Chris Lattnerdc046542009-05-08 06:58:22 +00002033 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002034 // FIXME: This loses syntactic information.
2035 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2036 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2037 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002038 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002039
Chandler Carruthbc8cab12010-07-18 07:23:17 +00002040 // Change the result type of the call to match the original value type. This
2041 // is arbitrary, but the codegen for these builtins ins design to handle it
2042 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00002043 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002044
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002045 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002046}
2047
Chris Lattner6436fb62009-02-18 06:01:06 +00002048/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002049/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002050/// Note: It might also make sense to do the UTF-16 conversion here (would
2051/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002052bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002053 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002054 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2055
Douglas Gregorfb65e592011-07-27 05:40:30 +00002056 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002057 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2058 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002059 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002060 }
Mike Stump11289f42009-09-09 15:08:12 +00002061
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002062 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002063 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002064 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002065 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002066 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002067 UTF16 *ToPtr = &ToBuf[0];
2068
2069 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2070 &ToPtr, ToPtr + NumBytes,
2071 strictConversion);
2072 // Check for conversion failure.
2073 if (Result != conversionOK)
2074 Diag(Arg->getLocStart(),
2075 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2076 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002077 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002078}
2079
Chris Lattnere202e6a2007-12-20 00:05:45 +00002080/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
2081/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00002082bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2083 Expr *Fn = TheCall->getCallee();
2084 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002085 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002086 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002087 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2088 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002089 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002090 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002091 return true;
2092 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002093
2094 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002095 return Diag(TheCall->getLocEnd(),
2096 diag::err_typecheck_call_too_few_args_at_least)
2097 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002098 }
2099
John McCall29ad95b2011-08-27 01:09:30 +00002100 // Type-check the first argument normally.
2101 if (checkBuiltinArgument(*this, TheCall, 0))
2102 return true;
2103
Chris Lattnere202e6a2007-12-20 00:05:45 +00002104 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002105 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002106 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002107 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002108 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002109 else if (FunctionDecl *FD = getCurFunctionDecl())
2110 isVariadic = FD->isVariadic();
2111 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002112 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002113
Chris Lattnere202e6a2007-12-20 00:05:45 +00002114 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002115 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2116 return true;
2117 }
Mike Stump11289f42009-09-09 15:08:12 +00002118
Chris Lattner43be2e62007-12-19 23:59:04 +00002119 // Verify that the second argument to the builtin is the last argument of the
2120 // current function or method.
2121 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002122 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002123
Nico Weber9eea7642013-05-24 23:31:57 +00002124 // These are valid if SecondArgIsLastNamedArgument is false after the next
2125 // block.
2126 QualType Type;
2127 SourceLocation ParamLoc;
2128
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002129 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2130 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002131 // FIXME: This isn't correct for methods (results in bogus warning).
2132 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002133 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002134 if (CurBlock)
2135 LastArg = *(CurBlock->TheDecl->param_end()-1);
2136 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002137 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002138 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002139 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002140 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002141
2142 Type = PV->getType();
2143 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002144 }
2145 }
Mike Stump11289f42009-09-09 15:08:12 +00002146
Chris Lattner43be2e62007-12-19 23:59:04 +00002147 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002148 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002149 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002150 else if (Type->isReferenceType()) {
2151 Diag(Arg->getLocStart(),
2152 diag::warn_va_start_of_reference_type_is_undefined);
2153 Diag(ParamLoc, diag::note_parameter_type) << Type;
2154 }
2155
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002156 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002157 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002158}
Chris Lattner43be2e62007-12-19 23:59:04 +00002159
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002160bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2161 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2162 // const char *named_addr);
2163
2164 Expr *Func = Call->getCallee();
2165
2166 if (Call->getNumArgs() < 3)
2167 return Diag(Call->getLocEnd(),
2168 diag::err_typecheck_call_too_few_args_at_least)
2169 << 0 /*function call*/ << 3 << Call->getNumArgs();
2170
2171 // Determine whether the current function is variadic or not.
2172 bool IsVariadic;
2173 if (BlockScopeInfo *CurBlock = getCurBlock())
2174 IsVariadic = CurBlock->TheDecl->isVariadic();
2175 else if (FunctionDecl *FD = getCurFunctionDecl())
2176 IsVariadic = FD->isVariadic();
2177 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2178 IsVariadic = MD->isVariadic();
2179 else
2180 llvm_unreachable("unexpected statement type");
2181
2182 if (!IsVariadic) {
2183 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2184 return true;
2185 }
2186
2187 // Type-check the first argument normally.
2188 if (checkBuiltinArgument(*this, Call, 0))
2189 return true;
2190
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002191 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002192 unsigned ArgNo;
2193 QualType Type;
2194 } ArgumentTypes[] = {
2195 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2196 { 2, Context.getSizeType() },
2197 };
2198
2199 for (const auto &AT : ArgumentTypes) {
2200 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2201 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2202 continue;
2203 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2204 << Arg->getType() << AT.Type << 1 /* different class */
2205 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2206 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2207 }
2208
2209 return false;
2210}
2211
Chris Lattner2da14fb2007-12-20 00:26:33 +00002212/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2213/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002214bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2215 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002216 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002217 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002218 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002219 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002220 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002221 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002222 << SourceRange(TheCall->getArg(2)->getLocStart(),
2223 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002224
John Wiegley01296292011-04-08 18:41:53 +00002225 ExprResult OrigArg0 = TheCall->getArg(0);
2226 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002227
Chris Lattner2da14fb2007-12-20 00:26:33 +00002228 // Do standard promotions between the two arguments, returning their common
2229 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002230 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002231 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2232 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002233
2234 // Make sure any conversions are pushed back into the call; this is
2235 // type safe since unordered compare builtins are declared as "_Bool
2236 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002237 TheCall->setArg(0, OrigArg0.get());
2238 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002239
John Wiegley01296292011-04-08 18:41:53 +00002240 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002241 return false;
2242
Chris Lattner2da14fb2007-12-20 00:26:33 +00002243 // If the common type isn't a real floating type, then the arguments were
2244 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002245 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002246 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002247 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002248 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2249 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002250
Chris Lattner2da14fb2007-12-20 00:26:33 +00002251 return false;
2252}
2253
Benjamin Kramer634fc102010-02-15 22:42:31 +00002254/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2255/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002256/// to check everything. We expect the last argument to be a floating point
2257/// value.
2258bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2259 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002260 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002261 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002262 if (TheCall->getNumArgs() > NumArgs)
2263 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002264 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002265 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002266 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002267 (*(TheCall->arg_end()-1))->getLocEnd());
2268
Benjamin Kramer64aae502010-02-16 10:07:31 +00002269 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002270
Eli Friedman7e4faac2009-08-31 20:06:00 +00002271 if (OrigArg->isTypeDependent())
2272 return false;
2273
Chris Lattner68784ef2010-05-06 05:50:07 +00002274 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002275 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002276 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002277 diag::err_typecheck_call_invalid_unary_fp)
2278 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002279
Chris Lattner68784ef2010-05-06 05:50:07 +00002280 // If this is an implicit conversion from float -> double, remove it.
2281 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2282 Expr *CastArg = Cast->getSubExpr();
2283 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2284 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2285 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002286 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002287 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002288 }
2289 }
2290
Eli Friedman7e4faac2009-08-31 20:06:00 +00002291 return false;
2292}
2293
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002294/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2295// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002296ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002297 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002298 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002299 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002300 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2301 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002302
Nate Begemana0110022010-06-08 00:16:34 +00002303 // Determine which of the following types of shufflevector we're checking:
2304 // 1) unary, vector mask: (lhs, mask)
2305 // 2) binary, vector mask: (lhs, rhs, mask)
2306 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2307 QualType resType = TheCall->getArg(0)->getType();
2308 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002309
Douglas Gregorc25f7662009-05-19 22:10:17 +00002310 if (!TheCall->getArg(0)->isTypeDependent() &&
2311 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002312 QualType LHSType = TheCall->getArg(0)->getType();
2313 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002314
Craig Topperbaca3892013-07-29 06:47:04 +00002315 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2316 return ExprError(Diag(TheCall->getLocStart(),
2317 diag::err_shufflevector_non_vector)
2318 << SourceRange(TheCall->getArg(0)->getLocStart(),
2319 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002320
Nate Begemana0110022010-06-08 00:16:34 +00002321 numElements = LHSType->getAs<VectorType>()->getNumElements();
2322 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002323
Nate Begemana0110022010-06-08 00:16:34 +00002324 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2325 // with mask. If so, verify that RHS is an integer vector type with the
2326 // same number of elts as lhs.
2327 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002328 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002329 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002330 return ExprError(Diag(TheCall->getLocStart(),
2331 diag::err_shufflevector_incompatible_vector)
2332 << SourceRange(TheCall->getArg(1)->getLocStart(),
2333 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002334 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002335 return ExprError(Diag(TheCall->getLocStart(),
2336 diag::err_shufflevector_incompatible_vector)
2337 << SourceRange(TheCall->getArg(0)->getLocStart(),
2338 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002339 } else if (numElements != numResElements) {
2340 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002341 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002342 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002343 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002344 }
2345
2346 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002347 if (TheCall->getArg(i)->isTypeDependent() ||
2348 TheCall->getArg(i)->isValueDependent())
2349 continue;
2350
Nate Begemana0110022010-06-08 00:16:34 +00002351 llvm::APSInt Result(32);
2352 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2353 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002354 diag::err_shufflevector_nonconstant_argument)
2355 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002356
Craig Topper50ad5b72013-08-03 17:40:38 +00002357 // Allow -1 which will be translated to undef in the IR.
2358 if (Result.isSigned() && Result.isAllOnesValue())
2359 continue;
2360
Chris Lattner7ab824e2008-08-10 02:05:13 +00002361 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002362 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002363 diag::err_shufflevector_argument_too_large)
2364 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002365 }
2366
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002367 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002368
Chris Lattner7ab824e2008-08-10 02:05:13 +00002369 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002370 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002371 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002372 }
2373
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002374 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2375 TheCall->getCallee()->getLocStart(),
2376 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002377}
Chris Lattner43be2e62007-12-19 23:59:04 +00002378
Hal Finkelc4d7c822013-09-18 03:29:45 +00002379/// SemaConvertVectorExpr - Handle __builtin_convertvector
2380ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2381 SourceLocation BuiltinLoc,
2382 SourceLocation RParenLoc) {
2383 ExprValueKind VK = VK_RValue;
2384 ExprObjectKind OK = OK_Ordinary;
2385 QualType DstTy = TInfo->getType();
2386 QualType SrcTy = E->getType();
2387
2388 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2389 return ExprError(Diag(BuiltinLoc,
2390 diag::err_convertvector_non_vector)
2391 << E->getSourceRange());
2392 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2393 return ExprError(Diag(BuiltinLoc,
2394 diag::err_convertvector_non_vector_type));
2395
2396 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2397 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2398 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2399 if (SrcElts != DstElts)
2400 return ExprError(Diag(BuiltinLoc,
2401 diag::err_convertvector_incompatible_vector)
2402 << E->getSourceRange());
2403 }
2404
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002405 return new (Context)
2406 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002407}
2408
Daniel Dunbarb7257262008-07-21 22:59:13 +00002409/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2410// This is declared to take (const void*, ...) and can take two
2411// optional constant int args.
2412bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002413 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002414
Chris Lattner3b054132008-11-19 05:08:23 +00002415 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002416 return Diag(TheCall->getLocEnd(),
2417 diag::err_typecheck_call_too_many_args_at_most)
2418 << 0 /*function call*/ << 3 << NumArgs
2419 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002420
2421 // Argument 0 is checked for us and the remaining arguments must be
2422 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002423 for (unsigned i = 1; i != NumArgs; ++i)
2424 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002425 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002426
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002427 return false;
2428}
2429
Hal Finkelf0417332014-07-17 14:25:55 +00002430/// SemaBuiltinAssume - Handle __assume (MS Extension).
2431// __assume does not evaluate its arguments, and should warn if its argument
2432// has side effects.
2433bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2434 Expr *Arg = TheCall->getArg(0);
2435 if (Arg->isInstantiationDependent()) return false;
2436
2437 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00002438 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002439 << Arg->getSourceRange()
2440 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2441
2442 return false;
2443}
2444
2445/// Handle __builtin_assume_aligned. This is declared
2446/// as (const void*, size_t, ...) and can take one optional constant int arg.
2447bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2448 unsigned NumArgs = TheCall->getNumArgs();
2449
2450 if (NumArgs > 3)
2451 return Diag(TheCall->getLocEnd(),
2452 diag::err_typecheck_call_too_many_args_at_most)
2453 << 0 /*function call*/ << 3 << NumArgs
2454 << TheCall->getSourceRange();
2455
2456 // The alignment must be a constant integer.
2457 Expr *Arg = TheCall->getArg(1);
2458
2459 // We can't check the value of a dependent argument.
2460 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2461 llvm::APSInt Result;
2462 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2463 return true;
2464
2465 if (!Result.isPowerOf2())
2466 return Diag(TheCall->getLocStart(),
2467 diag::err_alignment_not_power_of_two)
2468 << Arg->getSourceRange();
2469 }
2470
2471 if (NumArgs > 2) {
2472 ExprResult Arg(TheCall->getArg(2));
2473 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2474 Context.getSizeType(), false);
2475 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2476 if (Arg.isInvalid()) return true;
2477 TheCall->setArg(2, Arg.get());
2478 }
Hal Finkelf0417332014-07-17 14:25:55 +00002479
2480 return false;
2481}
2482
Eric Christopher8d0c6212010-04-17 02:26:23 +00002483/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2484/// TheCall is a constant expression.
2485bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2486 llvm::APSInt &Result) {
2487 Expr *Arg = TheCall->getArg(ArgNum);
2488 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2489 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2490
2491 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2492
2493 if (!Arg->isIntegerConstantExpr(Result, Context))
2494 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002495 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002496
Chris Lattnerd545ad12009-09-23 06:06:36 +00002497 return false;
2498}
2499
Richard Sandiford28940af2014-04-16 08:47:51 +00002500/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2501/// TheCall is a constant expression in the range [Low, High].
2502bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2503 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002504 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002505
2506 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002507 Expr *Arg = TheCall->getArg(ArgNum);
2508 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002509 return false;
2510
Eric Christopher8d0c6212010-04-17 02:26:23 +00002511 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002512 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002513 return true;
2514
Richard Sandiford28940af2014-04-16 08:47:51 +00002515 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002516 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002517 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002518
2519 return false;
2520}
2521
Eli Friedmanc97d0142009-05-03 06:04:26 +00002522/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002523/// This checks that the target supports __builtin_longjmp and
2524/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002525bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002526 if (!Context.getTargetInfo().hasSjLjLowering())
2527 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
2528 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2529
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002530 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002531 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002532
Eric Christopher8d0c6212010-04-17 02:26:23 +00002533 // TODO: This is less than ideal. Overload this to take a value.
2534 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2535 return true;
2536
2537 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002538 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2539 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2540
2541 return false;
2542}
2543
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002544
2545/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
2546/// This checks that the target supports __builtin_setjmp.
2547bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
2548 if (!Context.getTargetInfo().hasSjLjLowering())
2549 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
2550 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2551 return false;
2552}
2553
Richard Smithd7293d72013-08-05 18:49:43 +00002554namespace {
2555enum StringLiteralCheckType {
2556 SLCT_NotALiteral,
2557 SLCT_UncheckedLiteral,
2558 SLCT_CheckedLiteral
2559};
2560}
2561
Richard Smith55ce3522012-06-25 20:30:08 +00002562// Determine if an expression is a string literal or constant string.
2563// If this function returns false on the arguments to a function expecting a
2564// format string, we will usually need to emit a warning.
2565// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002566static StringLiteralCheckType
2567checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2568 bool HasVAListArg, unsigned format_idx,
2569 unsigned firstDataArg, Sema::FormatStringType Type,
2570 Sema::VariadicCallType CallType, bool InFunctionCall,
2571 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002572 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002573 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002574 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002575
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002576 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002577
Richard Smithd7293d72013-08-05 18:49:43 +00002578 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002579 // Technically -Wformat-nonliteral does not warn about this case.
2580 // The behavior of printf and friends in this case is implementation
2581 // dependent. Ideally if the format string cannot be null then
2582 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002583 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002584
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002585 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002586 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002587 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002588 // The expression is a literal if both sub-expressions were, and it was
2589 // completely checked only if both sub-expressions were checked.
2590 const AbstractConditionalOperator *C =
2591 cast<AbstractConditionalOperator>(E);
2592 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002593 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002594 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002595 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002596 if (Left == SLCT_NotALiteral)
2597 return SLCT_NotALiteral;
2598 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002599 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002600 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002601 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002602 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002603 }
2604
2605 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002606 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2607 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002608 }
2609
John McCallc07a0c72011-02-17 10:25:35 +00002610 case Stmt::OpaqueValueExprClass:
2611 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2612 E = src;
2613 goto tryAgain;
2614 }
Richard Smith55ce3522012-06-25 20:30:08 +00002615 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002616
Ted Kremeneka8890832011-02-24 23:03:04 +00002617 case Stmt::PredefinedExprClass:
2618 // While __func__, etc., are technically not string literals, they
2619 // cannot contain format specifiers and thus are not a security
2620 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002621 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002622
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002623 case Stmt::DeclRefExprClass: {
2624 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002625
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002626 // As an exception, do not flag errors for variables binding to
2627 // const string literals.
2628 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2629 bool isConstant = false;
2630 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002631
Richard Smithd7293d72013-08-05 18:49:43 +00002632 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2633 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002634 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002635 isConstant = T.isConstant(S.Context) &&
2636 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002637 } else if (T->isObjCObjectPointerType()) {
2638 // In ObjC, there is usually no "const ObjectPointer" type,
2639 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002640 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002641 }
Mike Stump11289f42009-09-09 15:08:12 +00002642
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002643 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002644 if (const Expr *Init = VD->getAnyInitializer()) {
2645 // Look through initializers like const char c[] = { "foo" }
2646 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2647 if (InitList->isStringLiteralInit())
2648 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2649 }
Richard Smithd7293d72013-08-05 18:49:43 +00002650 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002651 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002652 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002653 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002654 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002655 }
Mike Stump11289f42009-09-09 15:08:12 +00002656
Anders Carlssonb012ca92009-06-28 19:55:58 +00002657 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2658 // special check to see if the format string is a function parameter
2659 // of the function calling the printf function. If the function
2660 // has an attribute indicating it is a printf-like function, then we
2661 // should suppress warnings concerning non-literals being used in a call
2662 // to a vprintf function. For example:
2663 //
2664 // void
2665 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2666 // va_list ap;
2667 // va_start(ap, fmt);
2668 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2669 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002670 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002671 if (HasVAListArg) {
2672 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2673 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2674 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002675 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002676 // adjust for implicit parameter
2677 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2678 if (MD->isInstance())
2679 ++PVIndex;
2680 // We also check if the formats are compatible.
2681 // We can't pass a 'scanf' string to a 'printf' function.
2682 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002683 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002684 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002685 }
2686 }
2687 }
2688 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002689 }
Mike Stump11289f42009-09-09 15:08:12 +00002690
Richard Smith55ce3522012-06-25 20:30:08 +00002691 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002692 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002693
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002694 case Stmt::CallExprClass:
2695 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002696 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002697 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2698 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2699 unsigned ArgIndex = FA->getFormatIdx();
2700 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2701 if (MD->isInstance())
2702 --ArgIndex;
2703 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002704
Richard Smithd7293d72013-08-05 18:49:43 +00002705 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002706 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002707 Type, CallType, InFunctionCall,
2708 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002709 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2710 unsigned BuiltinID = FD->getBuiltinID();
2711 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2712 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2713 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002714 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002715 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002716 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002717 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002718 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002719 }
2720 }
Mike Stump11289f42009-09-09 15:08:12 +00002721
Richard Smith55ce3522012-06-25 20:30:08 +00002722 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002723 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002724 case Stmt::ObjCStringLiteralClass:
2725 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002726 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002727
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002728 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002729 StrE = ObjCFExpr->getString();
2730 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002731 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002732
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002733 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002734 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2735 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002736 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002737 }
Mike Stump11289f42009-09-09 15:08:12 +00002738
Richard Smith55ce3522012-06-25 20:30:08 +00002739 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002740 }
Mike Stump11289f42009-09-09 15:08:12 +00002741
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002742 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002743 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002744 }
2745}
2746
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002747Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002748 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002749 .Case("scanf", FST_Scanf)
2750 .Cases("printf", "printf0", FST_Printf)
2751 .Cases("NSString", "CFString", FST_NSString)
2752 .Case("strftime", FST_Strftime)
2753 .Case("strfmon", FST_Strfmon)
2754 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00002755 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00002756 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002757 .Default(FST_Unknown);
2758}
2759
Jordan Rose3e0ec582012-07-19 18:10:23 +00002760/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002761/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002762/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002763bool Sema::CheckFormatArguments(const FormatAttr *Format,
2764 ArrayRef<const Expr *> Args,
2765 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002766 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002767 SourceLocation Loc, SourceRange Range,
2768 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002769 FormatStringInfo FSI;
2770 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002771 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002772 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002773 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002774 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002775}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002776
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002777bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002778 bool HasVAListArg, unsigned format_idx,
2779 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002780 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002781 SourceLocation Loc, SourceRange Range,
2782 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002783 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002784 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002785 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002786 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002787 }
Mike Stump11289f42009-09-09 15:08:12 +00002788
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002789 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002790
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002791 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002792 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002793 // Dynamically generated format strings are difficult to
2794 // automatically vet at compile time. Requiring that format strings
2795 // are string literals: (1) permits the checking of format strings by
2796 // the compiler and thereby (2) can practically remove the source of
2797 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002798
Mike Stump11289f42009-09-09 15:08:12 +00002799 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002800 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002801 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002802 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002803 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002804 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2805 format_idx, firstDataArg, Type, CallType,
2806 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002807 if (CT != SLCT_NotALiteral)
2808 // Literal format string found, check done!
2809 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002810
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002811 // Strftime is particular as it always uses a single 'time' argument,
2812 // so it is safe to pass a non-literal string.
2813 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002814 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002815
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002816 // Do not emit diag when the string param is a macro expansion and the
2817 // format is either NSString or CFString. This is a hack to prevent
2818 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2819 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002820 if (Type == FST_NSString &&
2821 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002822 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002823
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002824 // If there are no arguments specified, warn with -Wformat-security, otherwise
2825 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002826 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002827 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002828 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002829 << OrigFormatExpr->getSourceRange();
2830 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002831 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002832 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002833 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002834 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002835}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002836
Ted Kremenekab278de2010-01-28 23:39:18 +00002837namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002838class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2839protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002840 Sema &S;
2841 const StringLiteral *FExpr;
2842 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002843 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002844 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002845 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002846 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002847 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002848 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002849 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002850 bool usesPositionalArgs;
2851 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002852 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002853 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002854 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002855public:
Ted Kremenek02087932010-07-16 02:11:22 +00002856 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002857 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002858 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002859 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002860 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002861 Sema::VariadicCallType callType,
2862 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002863 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002864 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2865 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002866 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002867 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002868 inFunctionCall(inFunctionCall), CallType(callType),
2869 CheckedVarArgs(CheckedVarArgs) {
2870 CoveredArgs.resize(numDataArgs);
2871 CoveredArgs.reset();
2872 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002873
Ted Kremenek019d2242010-01-29 01:50:07 +00002874 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002875
Ted Kremenek02087932010-07-16 02:11:22 +00002876 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002877 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002878
Jordan Rose92303592012-09-08 04:00:03 +00002879 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002880 const analyze_format_string::FormatSpecifier &FS,
2881 const analyze_format_string::ConversionSpecifier &CS,
2882 const char *startSpecifier, unsigned specifierLen,
2883 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002884
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002885 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002886 const analyze_format_string::FormatSpecifier &FS,
2887 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002888
2889 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002890 const analyze_format_string::ConversionSpecifier &CS,
2891 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002892
Craig Toppere14c0f82014-03-12 04:55:44 +00002893 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002894
Craig Toppere14c0f82014-03-12 04:55:44 +00002895 void HandleInvalidPosition(const char *startSpecifier,
2896 unsigned specifierLen,
2897 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002898
Craig Toppere14c0f82014-03-12 04:55:44 +00002899 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002900
Craig Toppere14c0f82014-03-12 04:55:44 +00002901 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002902
Richard Trieu03cf7b72011-10-28 00:41:25 +00002903 template <typename Range>
2904 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2905 const Expr *ArgumentExpr,
2906 PartialDiagnostic PDiag,
2907 SourceLocation StringLoc,
2908 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002909 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002910
Ted Kremenek02087932010-07-16 02:11:22 +00002911protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002912 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2913 const char *startSpec,
2914 unsigned specifierLen,
2915 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002916
2917 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2918 const char *startSpec,
2919 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002920
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002921 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002922 CharSourceRange getSpecifierRange(const char *startSpecifier,
2923 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002924 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002925
Ted Kremenek5739de72010-01-29 01:06:55 +00002926 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002927
2928 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2929 const analyze_format_string::ConversionSpecifier &CS,
2930 const char *startSpecifier, unsigned specifierLen,
2931 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002932
2933 template <typename Range>
2934 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2935 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002936 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002937};
2938}
2939
Ted Kremenek02087932010-07-16 02:11:22 +00002940SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002941 return OrigFormatExpr->getSourceRange();
2942}
2943
Ted Kremenek02087932010-07-16 02:11:22 +00002944CharSourceRange CheckFormatHandler::
2945getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002946 SourceLocation Start = getLocationOfByte(startSpecifier);
2947 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2948
2949 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002950 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002951
2952 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002953}
2954
Ted Kremenek02087932010-07-16 02:11:22 +00002955SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002956 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002957}
2958
Ted Kremenek02087932010-07-16 02:11:22 +00002959void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2960 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002961 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2962 getLocationOfByte(startSpecifier),
2963 /*IsStringLocation*/true,
2964 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002965}
2966
Jordan Rose92303592012-09-08 04:00:03 +00002967void CheckFormatHandler::HandleInvalidLengthModifier(
2968 const analyze_format_string::FormatSpecifier &FS,
2969 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002970 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002971 using namespace analyze_format_string;
2972
2973 const LengthModifier &LM = FS.getLengthModifier();
2974 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2975
2976 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002977 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002978 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002979 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002980 getLocationOfByte(LM.getStart()),
2981 /*IsStringLocation*/true,
2982 getSpecifierRange(startSpecifier, specifierLen));
2983
2984 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2985 << FixedLM->toString()
2986 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2987
2988 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002989 FixItHint Hint;
2990 if (DiagID == diag::warn_format_nonsensical_length)
2991 Hint = FixItHint::CreateRemoval(LMRange);
2992
2993 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002994 getLocationOfByte(LM.getStart()),
2995 /*IsStringLocation*/true,
2996 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002997 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002998 }
2999}
3000
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003001void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00003002 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003003 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003004 using namespace analyze_format_string;
3005
3006 const LengthModifier &LM = FS.getLengthModifier();
3007 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3008
3009 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003010 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00003011 if (FixedLM) {
3012 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3013 << LM.toString() << 0,
3014 getLocationOfByte(LM.getStart()),
3015 /*IsStringLocation*/true,
3016 getSpecifierRange(startSpecifier, specifierLen));
3017
3018 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3019 << FixedLM->toString()
3020 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3021
3022 } else {
3023 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3024 << LM.toString() << 0,
3025 getLocationOfByte(LM.getStart()),
3026 /*IsStringLocation*/true,
3027 getSpecifierRange(startSpecifier, specifierLen));
3028 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003029}
3030
3031void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3032 const analyze_format_string::ConversionSpecifier &CS,
3033 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00003034 using namespace analyze_format_string;
3035
3036 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00003037 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00003038 if (FixedCS) {
3039 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3040 << CS.toString() << /*conversion specifier*/1,
3041 getLocationOfByte(CS.getStart()),
3042 /*IsStringLocation*/true,
3043 getSpecifierRange(startSpecifier, specifierLen));
3044
3045 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3046 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3047 << FixedCS->toString()
3048 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3049 } else {
3050 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3051 << CS.toString() << /*conversion specifier*/1,
3052 getLocationOfByte(CS.getStart()),
3053 /*IsStringLocation*/true,
3054 getSpecifierRange(startSpecifier, specifierLen));
3055 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003056}
3057
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003058void CheckFormatHandler::HandlePosition(const char *startPos,
3059 unsigned posLen) {
3060 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3061 getLocationOfByte(startPos),
3062 /*IsStringLocation*/true,
3063 getSpecifierRange(startPos, posLen));
3064}
3065
Ted Kremenekd1668192010-02-27 01:41:03 +00003066void
Ted Kremenek02087932010-07-16 02:11:22 +00003067CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3068 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003069 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3070 << (unsigned) p,
3071 getLocationOfByte(startPos), /*IsStringLocation*/true,
3072 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003073}
3074
Ted Kremenek02087932010-07-16 02:11:22 +00003075void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003076 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003077 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3078 getLocationOfByte(startPos),
3079 /*IsStringLocation*/true,
3080 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003081}
3082
Ted Kremenek02087932010-07-16 02:11:22 +00003083void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003084 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003085 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003086 EmitFormatDiagnostic(
3087 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3088 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3089 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003090 }
Ted Kremenek02087932010-07-16 02:11:22 +00003091}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003092
Jordan Rose58bbe422012-07-19 18:10:08 +00003093// Note that this may return NULL if there was an error parsing or building
3094// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003095const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003096 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003097}
3098
3099void CheckFormatHandler::DoneProcessing() {
3100 // Does the number of data arguments exceed the number of
3101 // format conversions in the format string?
3102 if (!HasVAListArg) {
3103 // Find any arguments that weren't covered.
3104 CoveredArgs.flip();
3105 signed notCoveredArg = CoveredArgs.find_first();
3106 if (notCoveredArg >= 0) {
3107 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00003108 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3109 SourceLocation Loc = E->getLocStart();
3110 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3111 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3112 Loc, /*IsStringLocation*/false,
3113 getFormatStringRange());
3114 }
Bob Wilson23cd4342012-05-03 19:47:19 +00003115 }
Ted Kremenek02087932010-07-16 02:11:22 +00003116 }
3117 }
3118}
3119
Ted Kremenekce815422010-07-19 21:25:57 +00003120bool
3121CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3122 SourceLocation Loc,
3123 const char *startSpec,
3124 unsigned specifierLen,
3125 const char *csStart,
3126 unsigned csLen) {
3127
3128 bool keepGoing = true;
3129 if (argIndex < NumDataArgs) {
3130 // Consider the argument coverered, even though the specifier doesn't
3131 // make sense.
3132 CoveredArgs.set(argIndex);
3133 }
3134 else {
3135 // If argIndex exceeds the number of data arguments we
3136 // don't issue a warning because that is just a cascade of warnings (and
3137 // they may have intended '%%' anyway). We don't want to continue processing
3138 // the format string after this point, however, as we will like just get
3139 // gibberish when trying to match arguments.
3140 keepGoing = false;
3141 }
3142
Richard Trieu03cf7b72011-10-28 00:41:25 +00003143 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3144 << StringRef(csStart, csLen),
3145 Loc, /*IsStringLocation*/true,
3146 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003147
3148 return keepGoing;
3149}
3150
Richard Trieu03cf7b72011-10-28 00:41:25 +00003151void
3152CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3153 const char *startSpec,
3154 unsigned specifierLen) {
3155 EmitFormatDiagnostic(
3156 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3157 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3158}
3159
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003160bool
3161CheckFormatHandler::CheckNumArgs(
3162 const analyze_format_string::FormatSpecifier &FS,
3163 const analyze_format_string::ConversionSpecifier &CS,
3164 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3165
3166 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003167 PartialDiagnostic PDiag = FS.usesPositionalArg()
3168 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3169 << (argIndex+1) << NumDataArgs)
3170 : S.PDiag(diag::warn_printf_insufficient_data_args);
3171 EmitFormatDiagnostic(
3172 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3173 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003174 return false;
3175 }
3176 return true;
3177}
3178
Richard Trieu03cf7b72011-10-28 00:41:25 +00003179template<typename Range>
3180void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3181 SourceLocation Loc,
3182 bool IsStringLocation,
3183 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003184 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003185 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003186 Loc, IsStringLocation, StringRange, FixIt);
3187}
3188
3189/// \brief If the format string is not within the funcion call, emit a note
3190/// so that the function call and string are in diagnostic messages.
3191///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003192/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003193/// call and only one diagnostic message will be produced. Otherwise, an
3194/// extra note will be emitted pointing to location of the format string.
3195///
3196/// \param ArgumentExpr the expression that is passed as the format string
3197/// argument in the function call. Used for getting locations when two
3198/// diagnostics are emitted.
3199///
3200/// \param PDiag the callee should already have provided any strings for the
3201/// diagnostic message. This function only adds locations and fixits
3202/// to diagnostics.
3203///
3204/// \param Loc primary location for diagnostic. If two diagnostics are
3205/// required, one will be at Loc and a new SourceLocation will be created for
3206/// the other one.
3207///
3208/// \param IsStringLocation if true, Loc points to the format string should be
3209/// used for the note. Otherwise, Loc points to the argument list and will
3210/// be used with PDiag.
3211///
3212/// \param StringRange some or all of the string to highlight. This is
3213/// templated so it can accept either a CharSourceRange or a SourceRange.
3214///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003215/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003216template<typename Range>
3217void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3218 const Expr *ArgumentExpr,
3219 PartialDiagnostic PDiag,
3220 SourceLocation Loc,
3221 bool IsStringLocation,
3222 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003223 ArrayRef<FixItHint> FixIt) {
3224 if (InFunctionCall) {
3225 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3226 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003227 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00003228 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003229 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3230 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003231
3232 const Sema::SemaDiagnosticBuilder &Note =
3233 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3234 diag::note_format_string_defined);
3235
3236 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003237 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003238 }
3239}
3240
Ted Kremenek02087932010-07-16 02:11:22 +00003241//===--- CHECK: Printf format string checking ------------------------------===//
3242
3243namespace {
3244class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003245 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00003246public:
3247 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3248 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003249 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003250 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003251 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003252 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003253 Sema::VariadicCallType CallType,
3254 llvm::SmallBitVector &CheckedVarArgs)
3255 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3256 numDataArgs, beg, hasVAListArg, Args,
3257 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3258 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003259 {}
3260
Craig Toppere14c0f82014-03-12 04:55:44 +00003261
Ted Kremenek02087932010-07-16 02:11:22 +00003262 bool HandleInvalidPrintfConversionSpecifier(
3263 const analyze_printf::PrintfSpecifier &FS,
3264 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003265 unsigned specifierLen) override;
3266
Ted Kremenek02087932010-07-16 02:11:22 +00003267 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3268 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003269 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003270 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3271 const char *StartSpecifier,
3272 unsigned SpecifierLen,
3273 const Expr *E);
3274
Ted Kremenek02087932010-07-16 02:11:22 +00003275 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3276 const char *startSpecifier, unsigned specifierLen);
3277 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3278 const analyze_printf::OptionalAmount &Amt,
3279 unsigned type,
3280 const char *startSpecifier, unsigned specifierLen);
3281 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3282 const analyze_printf::OptionalFlag &flag,
3283 const char *startSpecifier, unsigned specifierLen);
3284 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3285 const analyze_printf::OptionalFlag &ignoredFlag,
3286 const analyze_printf::OptionalFlag &flag,
3287 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003288 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003289 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00003290
Ted Kremenek02087932010-07-16 02:11:22 +00003291};
3292}
3293
3294bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3295 const analyze_printf::PrintfSpecifier &FS,
3296 const char *startSpecifier,
3297 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003298 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003299 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003300
Ted Kremenekce815422010-07-19 21:25:57 +00003301 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3302 getLocationOfByte(CS.getStart()),
3303 startSpecifier, specifierLen,
3304 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003305}
3306
Ted Kremenek02087932010-07-16 02:11:22 +00003307bool CheckPrintfHandler::HandleAmount(
3308 const analyze_format_string::OptionalAmount &Amt,
3309 unsigned k, const char *startSpecifier,
3310 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003311
3312 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003313 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003314 unsigned argIndex = Amt.getArgIndex();
3315 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003316 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3317 << k,
3318 getLocationOfByte(Amt.getStart()),
3319 /*IsStringLocation*/true,
3320 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003321 // Don't do any more checking. We will just emit
3322 // spurious errors.
3323 return false;
3324 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003325
Ted Kremenek5739de72010-01-29 01:06:55 +00003326 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00003327 // Although not in conformance with C99, we also allow the argument to be
3328 // an 'unsigned int' as that is a reasonably safe case. GCC also
3329 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003330 CoveredArgs.set(argIndex);
3331 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003332 if (!Arg)
3333 return false;
3334
Ted Kremenek5739de72010-01-29 01:06:55 +00003335 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003336
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003337 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3338 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003339
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003340 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003341 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003342 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003343 << T << Arg->getSourceRange(),
3344 getLocationOfByte(Amt.getStart()),
3345 /*IsStringLocation*/true,
3346 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003347 // Don't do any more checking. We will just emit
3348 // spurious errors.
3349 return false;
3350 }
3351 }
3352 }
3353 return true;
3354}
Ted Kremenek5739de72010-01-29 01:06:55 +00003355
Tom Careb49ec692010-06-17 19:00:27 +00003356void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003357 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003358 const analyze_printf::OptionalAmount &Amt,
3359 unsigned type,
3360 const char *startSpecifier,
3361 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003362 const analyze_printf::PrintfConversionSpecifier &CS =
3363 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003364
Richard Trieu03cf7b72011-10-28 00:41:25 +00003365 FixItHint fixit =
3366 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3367 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3368 Amt.getConstantLength()))
3369 : FixItHint();
3370
3371 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3372 << type << CS.toString(),
3373 getLocationOfByte(Amt.getStart()),
3374 /*IsStringLocation*/true,
3375 getSpecifierRange(startSpecifier, specifierLen),
3376 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003377}
3378
Ted Kremenek02087932010-07-16 02:11:22 +00003379void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003380 const analyze_printf::OptionalFlag &flag,
3381 const char *startSpecifier,
3382 unsigned specifierLen) {
3383 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003384 const analyze_printf::PrintfConversionSpecifier &CS =
3385 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003386 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3387 << flag.toString() << CS.toString(),
3388 getLocationOfByte(flag.getPosition()),
3389 /*IsStringLocation*/true,
3390 getSpecifierRange(startSpecifier, specifierLen),
3391 FixItHint::CreateRemoval(
3392 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003393}
3394
3395void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003396 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003397 const analyze_printf::OptionalFlag &ignoredFlag,
3398 const analyze_printf::OptionalFlag &flag,
3399 const char *startSpecifier,
3400 unsigned specifierLen) {
3401 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003402 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3403 << ignoredFlag.toString() << flag.toString(),
3404 getLocationOfByte(ignoredFlag.getPosition()),
3405 /*IsStringLocation*/true,
3406 getSpecifierRange(startSpecifier, specifierLen),
3407 FixItHint::CreateRemoval(
3408 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003409}
3410
Richard Smith55ce3522012-06-25 20:30:08 +00003411// Determines if the specified is a C++ class or struct containing
3412// a member with the specified name and kind (e.g. a CXXMethodDecl named
3413// "c_str()").
3414template<typename MemberKind>
3415static llvm::SmallPtrSet<MemberKind*, 1>
3416CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3417 const RecordType *RT = Ty->getAs<RecordType>();
3418 llvm::SmallPtrSet<MemberKind*, 1> Results;
3419
3420 if (!RT)
3421 return Results;
3422 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003423 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003424 return Results;
3425
Alp Tokerb6cc5922014-05-03 03:45:55 +00003426 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003427 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003428 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003429
3430 // We just need to include all members of the right kind turned up by the
3431 // filter, at this point.
3432 if (S.LookupQualifiedName(R, RT->getDecl()))
3433 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3434 NamedDecl *decl = (*I)->getUnderlyingDecl();
3435 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3436 Results.insert(FK);
3437 }
3438 return Results;
3439}
3440
Richard Smith2868a732014-02-28 01:36:39 +00003441/// Check if we could call '.c_str()' on an object.
3442///
3443/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3444/// allow the call, or if it would be ambiguous).
3445bool Sema::hasCStrMethod(const Expr *E) {
3446 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3447 MethodSet Results =
3448 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3449 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3450 MI != ME; ++MI)
3451 if ((*MI)->getMinRequiredArguments() == 0)
3452 return true;
3453 return false;
3454}
3455
Richard Smith55ce3522012-06-25 20:30:08 +00003456// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003457// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003458// Returns true when a c_str() conversion method is found.
3459bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003460 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003461 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3462
3463 MethodSet Results =
3464 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3465
3466 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3467 MI != ME; ++MI) {
3468 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003469 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003470 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003471 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003472 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003473 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3474 << "c_str()"
3475 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3476 return true;
3477 }
3478 }
3479
3480 return false;
3481}
3482
Ted Kremenekab278de2010-01-28 23:39:18 +00003483bool
Ted Kremenek02087932010-07-16 02:11:22 +00003484CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003485 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003486 const char *startSpecifier,
3487 unsigned specifierLen) {
3488
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003489 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003490 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003491 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003492
Ted Kremenek6cd69422010-07-19 22:01:06 +00003493 if (FS.consumesDataArgument()) {
3494 if (atFirstArg) {
3495 atFirstArg = false;
3496 usesPositionalArgs = FS.usesPositionalArg();
3497 }
3498 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003499 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3500 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003501 return false;
3502 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003503 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003504
Ted Kremenekd1668192010-02-27 01:41:03 +00003505 // First check if the field width, precision, and conversion specifier
3506 // have matching data arguments.
3507 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3508 startSpecifier, specifierLen)) {
3509 return false;
3510 }
3511
3512 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3513 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003514 return false;
3515 }
3516
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003517 if (!CS.consumesDataArgument()) {
3518 // FIXME: Technically specifying a precision or field width here
3519 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003520 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003521 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003522
Ted Kremenek4a49d982010-02-26 19:18:41 +00003523 // Consume the argument.
3524 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003525 if (argIndex < NumDataArgs) {
3526 // The check to see if the argIndex is valid will come later.
3527 // We set the bit here because we may exit early from this
3528 // function if we encounter some other error.
3529 CoveredArgs.set(argIndex);
3530 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003531
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003532 // FreeBSD kernel extensions.
3533 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
3534 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
3535 // We need at least two arguments.
3536 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
3537 return false;
3538
3539 // Claim the second argument.
3540 CoveredArgs.set(argIndex + 1);
3541
3542 // Type check the first argument (int for %b, pointer for %D)
3543 const Expr *Ex = getDataArg(argIndex);
3544 const analyze_printf::ArgType &AT =
3545 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
3546 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
3547 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
3548 EmitFormatDiagnostic(
3549 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3550 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3551 << false << Ex->getSourceRange(),
3552 Ex->getLocStart(), /*IsStringLocation*/false,
3553 getSpecifierRange(startSpecifier, specifierLen));
3554
3555 // Type check the second argument (char * for both %b and %D)
3556 Ex = getDataArg(argIndex + 1);
3557 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
3558 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
3559 EmitFormatDiagnostic(
3560 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3561 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
3562 << false << Ex->getSourceRange(),
3563 Ex->getLocStart(), /*IsStringLocation*/false,
3564 getSpecifierRange(startSpecifier, specifierLen));
3565
3566 return true;
3567 }
3568
Ted Kremenek4a49d982010-02-26 19:18:41 +00003569 // Check for using an Objective-C specific conversion specifier
3570 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003571 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003572 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3573 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003574 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003575
Tom Careb49ec692010-06-17 19:00:27 +00003576 // Check for invalid use of field width
3577 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003578 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003579 startSpecifier, specifierLen);
3580 }
3581
3582 // Check for invalid use of precision
3583 if (!FS.hasValidPrecision()) {
3584 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3585 startSpecifier, specifierLen);
3586 }
3587
3588 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003589 if (!FS.hasValidThousandsGroupingPrefix())
3590 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003591 if (!FS.hasValidLeadingZeros())
3592 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3593 if (!FS.hasValidPlusPrefix())
3594 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003595 if (!FS.hasValidSpacePrefix())
3596 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003597 if (!FS.hasValidAlternativeForm())
3598 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3599 if (!FS.hasValidLeftJustified())
3600 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3601
3602 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003603 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3604 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3605 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003606 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3607 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3608 startSpecifier, specifierLen);
3609
3610 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003611 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003612 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3613 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003614 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003615 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003616 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003617 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3618 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003619
Jordan Rose92303592012-09-08 04:00:03 +00003620 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3621 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3622
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003623 // The remaining checks depend on the data arguments.
3624 if (HasVAListArg)
3625 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003626
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003627 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003628 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003629
Jordan Rose58bbe422012-07-19 18:10:08 +00003630 const Expr *Arg = getDataArg(argIndex);
3631 if (!Arg)
3632 return true;
3633
3634 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003635}
3636
Jordan Roseaee34382012-09-05 22:56:26 +00003637static bool requiresParensToAddCast(const Expr *E) {
3638 // FIXME: We should have a general way to reason about operator
3639 // precedence and whether parens are actually needed here.
3640 // Take care of a few common cases where they aren't.
3641 const Expr *Inside = E->IgnoreImpCasts();
3642 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3643 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3644
3645 switch (Inside->getStmtClass()) {
3646 case Stmt::ArraySubscriptExprClass:
3647 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003648 case Stmt::CharacterLiteralClass:
3649 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003650 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003651 case Stmt::FloatingLiteralClass:
3652 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003653 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003654 case Stmt::ObjCArrayLiteralClass:
3655 case Stmt::ObjCBoolLiteralExprClass:
3656 case Stmt::ObjCBoxedExprClass:
3657 case Stmt::ObjCDictionaryLiteralClass:
3658 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003659 case Stmt::ObjCIvarRefExprClass:
3660 case Stmt::ObjCMessageExprClass:
3661 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003662 case Stmt::ObjCStringLiteralClass:
3663 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003664 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003665 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003666 case Stmt::UnaryOperatorClass:
3667 return false;
3668 default:
3669 return true;
3670 }
3671}
3672
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003673static std::pair<QualType, StringRef>
3674shouldNotPrintDirectly(const ASTContext &Context,
3675 QualType IntendedTy,
3676 const Expr *E) {
3677 // Use a 'while' to peel off layers of typedefs.
3678 QualType TyTy = IntendedTy;
3679 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3680 StringRef Name = UserTy->getDecl()->getName();
3681 QualType CastTy = llvm::StringSwitch<QualType>(Name)
3682 .Case("NSInteger", Context.LongTy)
3683 .Case("NSUInteger", Context.UnsignedLongTy)
3684 .Case("SInt32", Context.IntTy)
3685 .Case("UInt32", Context.UnsignedIntTy)
3686 .Default(QualType());
3687
3688 if (!CastTy.isNull())
3689 return std::make_pair(CastTy, Name);
3690
3691 TyTy = UserTy->desugar();
3692 }
3693
3694 // Strip parens if necessary.
3695 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
3696 return shouldNotPrintDirectly(Context,
3697 PE->getSubExpr()->getType(),
3698 PE->getSubExpr());
3699
3700 // If this is a conditional expression, then its result type is constructed
3701 // via usual arithmetic conversions and thus there might be no necessary
3702 // typedef sugar there. Recurse to operands to check for NSInteger &
3703 // Co. usage condition.
3704 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3705 QualType TrueTy, FalseTy;
3706 StringRef TrueName, FalseName;
3707
3708 std::tie(TrueTy, TrueName) =
3709 shouldNotPrintDirectly(Context,
3710 CO->getTrueExpr()->getType(),
3711 CO->getTrueExpr());
3712 std::tie(FalseTy, FalseName) =
3713 shouldNotPrintDirectly(Context,
3714 CO->getFalseExpr()->getType(),
3715 CO->getFalseExpr());
3716
3717 if (TrueTy == FalseTy)
3718 return std::make_pair(TrueTy, TrueName);
3719 else if (TrueTy.isNull())
3720 return std::make_pair(FalseTy, FalseName);
3721 else if (FalseTy.isNull())
3722 return std::make_pair(TrueTy, TrueName);
3723 }
3724
3725 return std::make_pair(QualType(), StringRef());
3726}
3727
Richard Smith55ce3522012-06-25 20:30:08 +00003728bool
3729CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3730 const char *StartSpecifier,
3731 unsigned SpecifierLen,
3732 const Expr *E) {
3733 using namespace analyze_format_string;
3734 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003735 // Now type check the data expression that matches the
3736 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003737 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3738 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003739 if (!AT.isValid())
3740 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003741
Jordan Rose598ec092012-12-05 18:44:40 +00003742 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003743 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3744 ExprTy = TET->getUnderlyingExpr()->getType();
3745 }
3746
Seth Cantrellb4802962015-03-04 03:12:10 +00003747 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
3748
3749 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00003750 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00003751 }
Jordan Rose98709982012-06-04 22:48:57 +00003752
Jordan Rose22b74712012-09-05 22:56:19 +00003753 // Look through argument promotions for our error message's reported type.
3754 // This includes the integral and floating promotions, but excludes array
3755 // and function pointer decay; seeing that an argument intended to be a
3756 // string has type 'char [6]' is probably more confusing than 'char *'.
3757 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3758 if (ICE->getCastKind() == CK_IntegralCast ||
3759 ICE->getCastKind() == CK_FloatingCast) {
3760 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003761 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003762
3763 // Check if we didn't match because of an implicit cast from a 'char'
3764 // or 'short' to an 'int'. This is done because printf is a varargs
3765 // function.
3766 if (ICE->getType() == S.Context.IntTy ||
3767 ICE->getType() == S.Context.UnsignedIntTy) {
3768 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003769 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003770 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003771 }
Jordan Rose98709982012-06-04 22:48:57 +00003772 }
Jordan Rose598ec092012-12-05 18:44:40 +00003773 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3774 // Special case for 'a', which has type 'int' in C.
3775 // Note, however, that we do /not/ want to treat multibyte constants like
3776 // 'MooV' as characters! This form is deprecated but still exists.
3777 if (ExprTy == S.Context.IntTy)
3778 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3779 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003780 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003781
Jordan Rosebc53ed12014-05-31 04:12:14 +00003782 // Look through enums to their underlying type.
3783 bool IsEnum = false;
3784 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3785 ExprTy = EnumTy->getDecl()->getIntegerType();
3786 IsEnum = true;
3787 }
3788
Jordan Rose0e5badd2012-12-05 18:44:49 +00003789 // %C in an Objective-C context prints a unichar, not a wchar_t.
3790 // If the argument is an integer of some kind, believe the %C and suggest
3791 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003792 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003793 if (ObjCContext &&
3794 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3795 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3796 !ExprTy->isCharType()) {
3797 // 'unichar' is defined as a typedef of unsigned short, but we should
3798 // prefer using the typedef if it is visible.
3799 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003800
3801 // While we are here, check if the value is an IntegerLiteral that happens
3802 // to be within the valid range.
3803 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3804 const llvm::APInt &V = IL->getValue();
3805 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3806 return true;
3807 }
3808
Jordan Rose0e5badd2012-12-05 18:44:49 +00003809 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3810 Sema::LookupOrdinaryName);
3811 if (S.LookupName(Result, S.getCurScope())) {
3812 NamedDecl *ND = Result.getFoundDecl();
3813 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3814 if (TD->getUnderlyingType() == IntendedTy)
3815 IntendedTy = S.Context.getTypedefType(TD);
3816 }
3817 }
3818 }
3819
3820 // Special-case some of Darwin's platform-independence types by suggesting
3821 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003822 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00003823 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003824 QualType CastTy;
3825 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
3826 if (!CastTy.isNull()) {
3827 IntendedTy = CastTy;
3828 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00003829 }
3830 }
3831
Jordan Rose22b74712012-09-05 22:56:19 +00003832 // We may be able to offer a FixItHint if it is a supported type.
3833 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003834 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003835 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003836
Jordan Rose22b74712012-09-05 22:56:19 +00003837 if (success) {
3838 // Get the fix string from the fixed format specifier
3839 SmallString<16> buf;
3840 llvm::raw_svector_ostream os(buf);
3841 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003842
Jordan Roseaee34382012-09-05 22:56:26 +00003843 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3844
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003845 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00003846 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
3847 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
3848 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
3849 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00003850 // In this case, the specifier is wrong and should be changed to match
3851 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00003852 EmitFormatDiagnostic(S.PDiag(diag)
3853 << AT.getRepresentativeTypeName(S.Context)
3854 << IntendedTy << IsEnum << E->getSourceRange(),
3855 E->getLocStart(),
3856 /*IsStringLocation*/ false, SpecRange,
3857 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00003858
3859 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003860 // The canonical type for formatting this value is different from the
3861 // actual type of the expression. (This occurs, for example, with Darwin's
3862 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3863 // should be printed as 'long' for 64-bit compatibility.)
3864 // Rather than emitting a normal format/argument mismatch, we want to
3865 // add a cast to the recommended type (and correct the format string
3866 // if necessary).
3867 SmallString<16> CastBuf;
3868 llvm::raw_svector_ostream CastFix(CastBuf);
3869 CastFix << "(";
3870 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3871 CastFix << ")";
3872
3873 SmallVector<FixItHint,4> Hints;
3874 if (!AT.matchesType(S.Context, IntendedTy))
3875 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3876
3877 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3878 // If there's already a cast present, just replace it.
3879 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3880 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3881
3882 } else if (!requiresParensToAddCast(E)) {
3883 // If the expression has high enough precedence,
3884 // just write the C-style cast.
3885 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3886 CastFix.str()));
3887 } else {
3888 // Otherwise, add parens around the expression as well as the cast.
3889 CastFix << "(";
3890 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3891 CastFix.str()));
3892
Alp Tokerb6cc5922014-05-03 03:45:55 +00003893 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003894 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3895 }
3896
Jordan Rose0e5badd2012-12-05 18:44:49 +00003897 if (ShouldNotPrintDirectly) {
3898 // The expression has a type that should not be printed directly.
3899 // We extract the name from the typedef because we don't want to show
3900 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003901 StringRef Name;
3902 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
3903 Name = TypedefTy->getDecl()->getName();
3904 else
3905 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003906 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00003907 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003908 << E->getSourceRange(),
3909 E->getLocStart(), /*IsStringLocation=*/false,
3910 SpecRange, Hints);
3911 } else {
3912 // In this case, the expression could be printed using a different
3913 // specifier, but we've decided that the specifier is probably correct
3914 // and we should cast instead. Just use the normal warning message.
3915 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003916 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3917 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003918 << E->getSourceRange(),
3919 E->getLocStart(), /*IsStringLocation*/false,
3920 SpecRange, Hints);
3921 }
Jordan Roseaee34382012-09-05 22:56:26 +00003922 }
Jordan Rose22b74712012-09-05 22:56:19 +00003923 } else {
3924 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3925 SpecifierLen);
3926 // Since the warning for passing non-POD types to variadic functions
3927 // was deferred until now, we emit a warning for non-POD
3928 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003929 switch (S.isValidVarArgType(ExprTy)) {
3930 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00003931 case Sema::VAK_ValidInCXX11: {
3932 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
3933 if (match == analyze_printf::ArgType::NoMatchPedantic) {
3934 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
3935 }
Richard Smithd7293d72013-08-05 18:49:43 +00003936
Seth Cantrellb4802962015-03-04 03:12:10 +00003937 EmitFormatDiagnostic(
3938 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
3939 << IsEnum << CSR << E->getSourceRange(),
3940 E->getLocStart(), /*IsStringLocation*/ false, CSR);
3941 break;
3942 }
Richard Smithd7293d72013-08-05 18:49:43 +00003943 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00003944 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00003945 EmitFormatDiagnostic(
3946 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003947 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003948 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003949 << CallType
3950 << AT.getRepresentativeTypeName(S.Context)
3951 << CSR
3952 << E->getSourceRange(),
3953 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003954 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003955 break;
3956
3957 case Sema::VAK_Invalid:
3958 if (ExprTy->isObjCObjectType())
3959 EmitFormatDiagnostic(
3960 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3961 << S.getLangOpts().CPlusPlus11
3962 << ExprTy
3963 << CallType
3964 << AT.getRepresentativeTypeName(S.Context)
3965 << CSR
3966 << E->getSourceRange(),
3967 E->getLocStart(), /*IsStringLocation*/false, CSR);
3968 else
3969 // FIXME: If this is an initializer list, suggest removing the braces
3970 // or inserting a cast to the target type.
3971 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3972 << isa<InitListExpr>(E) << ExprTy << CallType
3973 << AT.getRepresentativeTypeName(S.Context)
3974 << E->getSourceRange();
3975 break;
3976 }
3977
3978 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3979 "format string specifier index out of range");
3980 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003981 }
3982
Ted Kremenekab278de2010-01-28 23:39:18 +00003983 return true;
3984}
3985
Ted Kremenek02087932010-07-16 02:11:22 +00003986//===--- CHECK: Scanf format string checking ------------------------------===//
3987
3988namespace {
3989class CheckScanfHandler : public CheckFormatHandler {
3990public:
3991 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3992 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003993 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003994 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003995 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003996 Sema::VariadicCallType CallType,
3997 llvm::SmallBitVector &CheckedVarArgs)
3998 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3999 numDataArgs, beg, hasVAListArg,
4000 Args, formatIdx, inFunctionCall, CallType,
4001 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004002 {}
Ted Kremenek02087932010-07-16 02:11:22 +00004003
4004 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4005 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004006 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00004007
4008 bool HandleInvalidScanfConversionSpecifier(
4009 const analyze_scanf::ScanfSpecifier &FS,
4010 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004011 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004012
Craig Toppere14c0f82014-03-12 04:55:44 +00004013 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00004014};
Ted Kremenek019d2242010-01-29 01:50:07 +00004015}
Ted Kremenekab278de2010-01-28 23:39:18 +00004016
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004017void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4018 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004019 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4020 getLocationOfByte(end), /*IsStringLocation*/true,
4021 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004022}
4023
Ted Kremenekce815422010-07-19 21:25:57 +00004024bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4025 const analyze_scanf::ScanfSpecifier &FS,
4026 const char *startSpecifier,
4027 unsigned specifierLen) {
4028
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004029 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004030 FS.getConversionSpecifier();
4031
4032 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4033 getLocationOfByte(CS.getStart()),
4034 startSpecifier, specifierLen,
4035 CS.getStart(), CS.getLength());
4036}
4037
Ted Kremenek02087932010-07-16 02:11:22 +00004038bool CheckScanfHandler::HandleScanfSpecifier(
4039 const analyze_scanf::ScanfSpecifier &FS,
4040 const char *startSpecifier,
4041 unsigned specifierLen) {
4042
4043 using namespace analyze_scanf;
4044 using namespace analyze_format_string;
4045
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004046 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004047
Ted Kremenek6cd69422010-07-19 22:01:06 +00004048 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4049 // be used to decide if we are using positional arguments consistently.
4050 if (FS.consumesDataArgument()) {
4051 if (atFirstArg) {
4052 atFirstArg = false;
4053 usesPositionalArgs = FS.usesPositionalArg();
4054 }
4055 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004056 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4057 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004058 return false;
4059 }
Ted Kremenek02087932010-07-16 02:11:22 +00004060 }
4061
4062 // Check if the field with is non-zero.
4063 const OptionalAmount &Amt = FS.getFieldWidth();
4064 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4065 if (Amt.getConstantAmount() == 0) {
4066 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4067 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00004068 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4069 getLocationOfByte(Amt.getStart()),
4070 /*IsStringLocation*/true, R,
4071 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00004072 }
4073 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004074
Ted Kremenek02087932010-07-16 02:11:22 +00004075 if (!FS.consumesDataArgument()) {
4076 // FIXME: Technically specifying a precision or field width here
4077 // makes no sense. Worth issuing a warning at some point.
4078 return true;
4079 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004080
Ted Kremenek02087932010-07-16 02:11:22 +00004081 // Consume the argument.
4082 unsigned argIndex = FS.getArgIndex();
4083 if (argIndex < NumDataArgs) {
4084 // The check to see if the argIndex is valid will come later.
4085 // We set the bit here because we may exit early from this
4086 // function if we encounter some other error.
4087 CoveredArgs.set(argIndex);
4088 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004089
Ted Kremenek4407ea42010-07-20 20:04:47 +00004090 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004091 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004092 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4093 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004094 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004095 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004096 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004097 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4098 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004099
Jordan Rose92303592012-09-08 04:00:03 +00004100 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4101 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4102
Ted Kremenek02087932010-07-16 02:11:22 +00004103 // The remaining checks depend on the data arguments.
4104 if (HasVAListArg)
4105 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004106
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004107 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004108 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00004109
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004110 // Check that the argument type matches the format specifier.
4111 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004112 if (!Ex)
4113 return true;
4114
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004115 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00004116
4117 if (!AT.isValid()) {
4118 return true;
4119 }
4120
Seth Cantrellb4802962015-03-04 03:12:10 +00004121 analyze_format_string::ArgType::MatchKind match =
4122 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00004123 if (match == analyze_format_string::ArgType::Match) {
4124 return true;
4125 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004126
Seth Cantrell79340072015-03-04 05:58:08 +00004127 ScanfSpecifier fixedFS = FS;
4128 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4129 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004130
Seth Cantrell79340072015-03-04 05:58:08 +00004131 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4132 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4133 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4134 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004135
Seth Cantrell79340072015-03-04 05:58:08 +00004136 if (success) {
4137 // Get the fix string from the fixed format specifier.
4138 SmallString<128> buf;
4139 llvm::raw_svector_ostream os(buf);
4140 fixedFS.toString(os);
4141
4142 EmitFormatDiagnostic(
4143 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4144 << Ex->getType() << false << Ex->getSourceRange(),
4145 Ex->getLocStart(),
4146 /*IsStringLocation*/ false,
4147 getSpecifierRange(startSpecifier, specifierLen),
4148 FixItHint::CreateReplacement(
4149 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4150 } else {
4151 EmitFormatDiagnostic(S.PDiag(diag)
4152 << AT.getRepresentativeTypeName(S.Context)
4153 << Ex->getType() << false << Ex->getSourceRange(),
4154 Ex->getLocStart(),
4155 /*IsStringLocation*/ false,
4156 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004157 }
4158
Ted Kremenek02087932010-07-16 02:11:22 +00004159 return true;
4160}
4161
4162void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00004163 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004164 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004165 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004166 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00004167 bool inFunctionCall, VariadicCallType CallType,
4168 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004169
Ted Kremenekab278de2010-01-28 23:39:18 +00004170 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004171 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004172 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004173 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004174 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4175 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004176 return;
4177 }
Ted Kremenek02087932010-07-16 02:11:22 +00004178
Ted Kremenekab278de2010-01-28 23:39:18 +00004179 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004180 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004181 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004182 // Account for cases where the string literal is truncated in a declaration.
4183 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4184 assert(T && "String literal not of constant array type!");
4185 size_t TypeSize = T->getSize().getZExtValue();
4186 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004187 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004188
4189 // Emit a warning if the string literal is truncated and does not contain an
4190 // embedded null character.
4191 if (TypeSize <= StrRef.size() &&
4192 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4193 CheckFormatHandler::EmitFormatDiagnostic(
4194 *this, inFunctionCall, Args[format_idx],
4195 PDiag(diag::warn_printf_format_string_not_null_terminated),
4196 FExpr->getLocStart(),
4197 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4198 return;
4199 }
4200
Ted Kremenekab278de2010-01-28 23:39:18 +00004201 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004202 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004203 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004204 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004205 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4206 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004207 return;
4208 }
Ted Kremenek02087932010-07-16 02:11:22 +00004209
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004210 if (Type == FST_Printf || Type == FST_NSString ||
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004211 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek02087932010-07-16 02:11:22 +00004212 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004213 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004214 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004215 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004216
Hans Wennborg23926bd2011-12-15 10:25:47 +00004217 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004218 getLangOpts(),
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004219 Context.getTargetInfo(),
4220 Type == FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00004221 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004222 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004223 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004224 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004225 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004226
Hans Wennborg23926bd2011-12-15 10:25:47 +00004227 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004228 getLangOpts(),
4229 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004230 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004231 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004232}
4233
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004234bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4235 // Str - The format string. NOTE: this is NOT null-terminated!
4236 StringRef StrRef = FExpr->getString();
4237 const char *Str = StrRef.data();
4238 // Account for cases where the string literal is truncated in a declaration.
4239 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4240 assert(T && "String literal not of constant array type!");
4241 size_t TypeSize = T->getSize().getZExtValue();
4242 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4243 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4244 getLangOpts(),
4245 Context.getTargetInfo());
4246}
4247
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004248//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4249
4250// Returns the related absolute value function that is larger, of 0 if one
4251// does not exist.
4252static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4253 switch (AbsFunction) {
4254 default:
4255 return 0;
4256
4257 case Builtin::BI__builtin_abs:
4258 return Builtin::BI__builtin_labs;
4259 case Builtin::BI__builtin_labs:
4260 return Builtin::BI__builtin_llabs;
4261 case Builtin::BI__builtin_llabs:
4262 return 0;
4263
4264 case Builtin::BI__builtin_fabsf:
4265 return Builtin::BI__builtin_fabs;
4266 case Builtin::BI__builtin_fabs:
4267 return Builtin::BI__builtin_fabsl;
4268 case Builtin::BI__builtin_fabsl:
4269 return 0;
4270
4271 case Builtin::BI__builtin_cabsf:
4272 return Builtin::BI__builtin_cabs;
4273 case Builtin::BI__builtin_cabs:
4274 return Builtin::BI__builtin_cabsl;
4275 case Builtin::BI__builtin_cabsl:
4276 return 0;
4277
4278 case Builtin::BIabs:
4279 return Builtin::BIlabs;
4280 case Builtin::BIlabs:
4281 return Builtin::BIllabs;
4282 case Builtin::BIllabs:
4283 return 0;
4284
4285 case Builtin::BIfabsf:
4286 return Builtin::BIfabs;
4287 case Builtin::BIfabs:
4288 return Builtin::BIfabsl;
4289 case Builtin::BIfabsl:
4290 return 0;
4291
4292 case Builtin::BIcabsf:
4293 return Builtin::BIcabs;
4294 case Builtin::BIcabs:
4295 return Builtin::BIcabsl;
4296 case Builtin::BIcabsl:
4297 return 0;
4298 }
4299}
4300
4301// Returns the argument type of the absolute value function.
4302static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4303 unsigned AbsType) {
4304 if (AbsType == 0)
4305 return QualType();
4306
4307 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4308 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4309 if (Error != ASTContext::GE_None)
4310 return QualType();
4311
4312 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4313 if (!FT)
4314 return QualType();
4315
4316 if (FT->getNumParams() != 1)
4317 return QualType();
4318
4319 return FT->getParamType(0);
4320}
4321
4322// Returns the best absolute value function, or zero, based on type and
4323// current absolute value function.
4324static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4325 unsigned AbsFunctionKind) {
4326 unsigned BestKind = 0;
4327 uint64_t ArgSize = Context.getTypeSize(ArgType);
4328 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4329 Kind = getLargerAbsoluteValueFunction(Kind)) {
4330 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4331 if (Context.getTypeSize(ParamType) >= ArgSize) {
4332 if (BestKind == 0)
4333 BestKind = Kind;
4334 else if (Context.hasSameType(ParamType, ArgType)) {
4335 BestKind = Kind;
4336 break;
4337 }
4338 }
4339 }
4340 return BestKind;
4341}
4342
4343enum AbsoluteValueKind {
4344 AVK_Integer,
4345 AVK_Floating,
4346 AVK_Complex
4347};
4348
4349static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4350 if (T->isIntegralOrEnumerationType())
4351 return AVK_Integer;
4352 if (T->isRealFloatingType())
4353 return AVK_Floating;
4354 if (T->isAnyComplexType())
4355 return AVK_Complex;
4356
4357 llvm_unreachable("Type not integer, floating, or complex");
4358}
4359
4360// Changes the absolute value function to a different type. Preserves whether
4361// the function is a builtin.
4362static unsigned changeAbsFunction(unsigned AbsKind,
4363 AbsoluteValueKind ValueKind) {
4364 switch (ValueKind) {
4365 case AVK_Integer:
4366 switch (AbsKind) {
4367 default:
4368 return 0;
4369 case Builtin::BI__builtin_fabsf:
4370 case Builtin::BI__builtin_fabs:
4371 case Builtin::BI__builtin_fabsl:
4372 case Builtin::BI__builtin_cabsf:
4373 case Builtin::BI__builtin_cabs:
4374 case Builtin::BI__builtin_cabsl:
4375 return Builtin::BI__builtin_abs;
4376 case Builtin::BIfabsf:
4377 case Builtin::BIfabs:
4378 case Builtin::BIfabsl:
4379 case Builtin::BIcabsf:
4380 case Builtin::BIcabs:
4381 case Builtin::BIcabsl:
4382 return Builtin::BIabs;
4383 }
4384 case AVK_Floating:
4385 switch (AbsKind) {
4386 default:
4387 return 0;
4388 case Builtin::BI__builtin_abs:
4389 case Builtin::BI__builtin_labs:
4390 case Builtin::BI__builtin_llabs:
4391 case Builtin::BI__builtin_cabsf:
4392 case Builtin::BI__builtin_cabs:
4393 case Builtin::BI__builtin_cabsl:
4394 return Builtin::BI__builtin_fabsf;
4395 case Builtin::BIabs:
4396 case Builtin::BIlabs:
4397 case Builtin::BIllabs:
4398 case Builtin::BIcabsf:
4399 case Builtin::BIcabs:
4400 case Builtin::BIcabsl:
4401 return Builtin::BIfabsf;
4402 }
4403 case AVK_Complex:
4404 switch (AbsKind) {
4405 default:
4406 return 0;
4407 case Builtin::BI__builtin_abs:
4408 case Builtin::BI__builtin_labs:
4409 case Builtin::BI__builtin_llabs:
4410 case Builtin::BI__builtin_fabsf:
4411 case Builtin::BI__builtin_fabs:
4412 case Builtin::BI__builtin_fabsl:
4413 return Builtin::BI__builtin_cabsf;
4414 case Builtin::BIabs:
4415 case Builtin::BIlabs:
4416 case Builtin::BIllabs:
4417 case Builtin::BIfabsf:
4418 case Builtin::BIfabs:
4419 case Builtin::BIfabsl:
4420 return Builtin::BIcabsf;
4421 }
4422 }
4423 llvm_unreachable("Unable to convert function");
4424}
4425
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004426static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004427 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4428 if (!FnInfo)
4429 return 0;
4430
4431 switch (FDecl->getBuiltinID()) {
4432 default:
4433 return 0;
4434 case Builtin::BI__builtin_abs:
4435 case Builtin::BI__builtin_fabs:
4436 case Builtin::BI__builtin_fabsf:
4437 case Builtin::BI__builtin_fabsl:
4438 case Builtin::BI__builtin_labs:
4439 case Builtin::BI__builtin_llabs:
4440 case Builtin::BI__builtin_cabs:
4441 case Builtin::BI__builtin_cabsf:
4442 case Builtin::BI__builtin_cabsl:
4443 case Builtin::BIabs:
4444 case Builtin::BIlabs:
4445 case Builtin::BIllabs:
4446 case Builtin::BIfabs:
4447 case Builtin::BIfabsf:
4448 case Builtin::BIfabsl:
4449 case Builtin::BIcabs:
4450 case Builtin::BIcabsf:
4451 case Builtin::BIcabsl:
4452 return FDecl->getBuiltinID();
4453 }
4454 llvm_unreachable("Unknown Builtin type");
4455}
4456
4457// If the replacement is valid, emit a note with replacement function.
4458// Additionally, suggest including the proper header if not already included.
4459static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004460 unsigned AbsKind, QualType ArgType) {
4461 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004462 const char *HeaderName = nullptr;
4463 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004464 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4465 FunctionName = "std::abs";
4466 if (ArgType->isIntegralOrEnumerationType()) {
4467 HeaderName = "cstdlib";
4468 } else if (ArgType->isRealFloatingType()) {
4469 HeaderName = "cmath";
4470 } else {
4471 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004472 }
Richard Trieubeffb832014-04-15 23:47:53 +00004473
4474 // Lookup all std::abs
4475 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004476 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004477 R.suppressDiagnostics();
4478 S.LookupQualifiedName(R, Std);
4479
4480 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004481 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004482 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4483 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4484 } else {
4485 FDecl = dyn_cast<FunctionDecl>(I);
4486 }
4487 if (!FDecl)
4488 continue;
4489
4490 // Found std::abs(), check that they are the right ones.
4491 if (FDecl->getNumParams() != 1)
4492 continue;
4493
4494 // Check that the parameter type can handle the argument.
4495 QualType ParamType = FDecl->getParamDecl(0)->getType();
4496 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4497 S.Context.getTypeSize(ArgType) <=
4498 S.Context.getTypeSize(ParamType)) {
4499 // Found a function, don't need the header hint.
4500 EmitHeaderHint = false;
4501 break;
4502 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004503 }
Richard Trieubeffb832014-04-15 23:47:53 +00004504 }
4505 } else {
4506 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4507 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4508
4509 if (HeaderName) {
4510 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4511 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4512 R.suppressDiagnostics();
4513 S.LookupName(R, S.getCurScope());
4514
4515 if (R.isSingleResult()) {
4516 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4517 if (FD && FD->getBuiltinID() == AbsKind) {
4518 EmitHeaderHint = false;
4519 } else {
4520 return;
4521 }
4522 } else if (!R.empty()) {
4523 return;
4524 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004525 }
4526 }
4527
4528 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00004529 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004530
Richard Trieubeffb832014-04-15 23:47:53 +00004531 if (!HeaderName)
4532 return;
4533
4534 if (!EmitHeaderHint)
4535 return;
4536
Alp Toker5d96e0a2014-07-11 20:53:51 +00004537 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4538 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00004539}
4540
4541static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4542 if (!FDecl)
4543 return false;
4544
4545 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4546 return false;
4547
4548 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4549
4550 while (ND && ND->isInlineNamespace()) {
4551 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004552 }
Richard Trieubeffb832014-04-15 23:47:53 +00004553
4554 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4555 return false;
4556
4557 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4558 return false;
4559
4560 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004561}
4562
4563// Warn when using the wrong abs() function.
4564void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4565 const FunctionDecl *FDecl,
4566 IdentifierInfo *FnInfo) {
4567 if (Call->getNumArgs() != 1)
4568 return;
4569
4570 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00004571 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4572 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004573 return;
4574
4575 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4576 QualType ParamType = Call->getArg(0)->getType();
4577
Alp Toker5d96e0a2014-07-11 20:53:51 +00004578 // Unsigned types cannot be negative. Suggest removing the absolute value
4579 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004580 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00004581 const char *FunctionName =
4582 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004583 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4584 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00004585 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004586 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4587 return;
4588 }
4589
Richard Trieubeffb832014-04-15 23:47:53 +00004590 // std::abs has overloads which prevent most of the absolute value problems
4591 // from occurring.
4592 if (IsStdAbs)
4593 return;
4594
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004595 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4596 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4597
4598 // The argument and parameter are the same kind. Check if they are the right
4599 // size.
4600 if (ArgValueKind == ParamValueKind) {
4601 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4602 return;
4603
4604 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4605 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4606 << FDecl << ArgType << ParamType;
4607
4608 if (NewAbsKind == 0)
4609 return;
4610
4611 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004612 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004613 return;
4614 }
4615
4616 // ArgValueKind != ParamValueKind
4617 // The wrong type of absolute value function was used. Attempt to find the
4618 // proper one.
4619 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4620 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4621 if (NewAbsKind == 0)
4622 return;
4623
4624 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4625 << FDecl << ParamValueKind << ArgValueKind;
4626
4627 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004628 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004629 return;
4630}
4631
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004632//===--- CHECK: Standard memory functions ---------------------------------===//
4633
Nico Weber0e6daef2013-12-26 23:38:39 +00004634/// \brief Takes the expression passed to the size_t parameter of functions
4635/// such as memcmp, strncat, etc and warns if it's a comparison.
4636///
4637/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4638static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4639 IdentifierInfo *FnName,
4640 SourceLocation FnLoc,
4641 SourceLocation RParenLoc) {
4642 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4643 if (!Size)
4644 return false;
4645
4646 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4647 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4648 return false;
4649
Nico Weber0e6daef2013-12-26 23:38:39 +00004650 SourceRange SizeRange = Size->getSourceRange();
4651 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4652 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00004653 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004654 << FnName << FixItHint::CreateInsertion(
4655 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00004656 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00004657 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00004658 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00004659 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4660 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00004661
4662 return true;
4663}
4664
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004665/// \brief Determine whether the given type is or contains a dynamic class type
4666/// (e.g., whether it has a vtable).
4667static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4668 bool &IsContained) {
4669 // Look through array types while ignoring qualifiers.
4670 const Type *Ty = T->getBaseElementTypeUnsafe();
4671 IsContained = false;
4672
4673 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4674 RD = RD ? RD->getDefinition() : nullptr;
4675 if (!RD)
4676 return nullptr;
4677
4678 if (RD->isDynamicClass())
4679 return RD;
4680
4681 // Check all the fields. If any bases were dynamic, the class is dynamic.
4682 // It's impossible for a class to transitively contain itself by value, so
4683 // infinite recursion is impossible.
4684 for (auto *FD : RD->fields()) {
4685 bool SubContained;
4686 if (const CXXRecordDecl *ContainedRD =
4687 getContainedDynamicClass(FD->getType(), SubContained)) {
4688 IsContained = true;
4689 return ContainedRD;
4690 }
4691 }
4692
4693 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004694}
4695
Chandler Carruth889ed862011-06-21 23:04:20 +00004696/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004697/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00004698static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004699 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004700 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4701 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4702 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004703
Craig Topperc3ec1492014-05-26 06:22:03 +00004704 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004705}
4706
Chandler Carruth889ed862011-06-21 23:04:20 +00004707/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00004708static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004709 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4710 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4711 if (SizeOf->getKind() == clang::UETT_SizeOf)
4712 return SizeOf->getTypeOfArgument();
4713
4714 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004715}
4716
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004717/// \brief Check for dangerous or invalid arguments to memset().
4718///
Chandler Carruthac687262011-06-03 06:23:57 +00004719/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004720/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4721/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004722///
4723/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004724void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004725 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004726 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004727 assert(BId != 0);
4728
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004729 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004730 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004731 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004732 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004733 return;
4734
Anna Zaks22122702012-01-17 00:37:07 +00004735 unsigned LastArg = (BId == Builtin::BImemset ||
4736 BId == Builtin::BIstrndup ? 1 : 2);
4737 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004738 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004739
Nico Weber0e6daef2013-12-26 23:38:39 +00004740 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4741 Call->getLocStart(), Call->getRParenLoc()))
4742 return;
4743
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004744 // We have special checking when the length is a sizeof expression.
4745 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4746 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4747 llvm::FoldingSetNodeID SizeOfArgID;
4748
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004749 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4750 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004751 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004752
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004753 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00004754 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004755 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00004756 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004757
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004758 // Never warn about void type pointers. This can be used to suppress
4759 // false positives.
4760 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004761 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004762
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004763 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4764 // actually comparing the expressions for equality. Because computing the
4765 // expression IDs can be expensive, we only do this if the diagnostic is
4766 // enabled.
4767 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004768 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4769 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004770 // We only compute IDs for expressions if the warning is enabled, and
4771 // cache the sizeof arg's ID.
4772 if (SizeOfArgID == llvm::FoldingSetNodeID())
4773 SizeOfArg->Profile(SizeOfArgID, Context, true);
4774 llvm::FoldingSetNodeID DestID;
4775 Dest->Profile(DestID, Context, true);
4776 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004777 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4778 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004779 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004780 StringRef ReadableName = FnName->getName();
4781
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004782 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004783 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004784 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004785 if (!PointeeTy->isIncompleteType() &&
4786 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004787 ActionIdx = 2; // If the pointee's size is sizeof(char),
4788 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004789
4790 // If the function is defined as a builtin macro, do not show macro
4791 // expansion.
4792 SourceLocation SL = SizeOfArg->getExprLoc();
4793 SourceRange DSR = Dest->getSourceRange();
4794 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004795 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004796
4797 if (SM.isMacroArgExpansion(SL)) {
4798 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4799 SL = SM.getSpellingLoc(SL);
4800 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4801 SM.getSpellingLoc(DSR.getEnd()));
4802 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4803 SM.getSpellingLoc(SSR.getEnd()));
4804 }
4805
Anna Zaksd08d9152012-05-30 23:14:52 +00004806 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004807 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004808 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004809 << PointeeTy
4810 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004811 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004812 << SSR);
4813 DiagRuntimeBehavior(SL, SizeOfArg,
4814 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4815 << ActionIdx
4816 << SSR);
4817
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004818 break;
4819 }
4820 }
4821
4822 // Also check for cases where the sizeof argument is the exact same
4823 // type as the memory argument, and where it points to a user-defined
4824 // record type.
4825 if (SizeOfArgTy != QualType()) {
4826 if (PointeeTy->isRecordType() &&
4827 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4828 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4829 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4830 << FnName << SizeOfArgTy << ArgIdx
4831 << PointeeTy << Dest->getSourceRange()
4832 << LenExpr->getSourceRange());
4833 break;
4834 }
Nico Weberc5e73862011-06-14 16:14:58 +00004835 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00004836 } else if (DestTy->isArrayType()) {
4837 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00004838 }
Nico Weberc5e73862011-06-14 16:14:58 +00004839
Nico Weberc44b35e2015-03-21 17:37:46 +00004840 if (PointeeTy == QualType())
4841 continue;
Anna Zaks22122702012-01-17 00:37:07 +00004842
Nico Weberc44b35e2015-03-21 17:37:46 +00004843 // Always complain about dynamic classes.
4844 bool IsContained;
4845 if (const CXXRecordDecl *ContainedRD =
4846 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00004847
Nico Weberc44b35e2015-03-21 17:37:46 +00004848 unsigned OperationType = 0;
4849 // "overwritten" if we're warning about the destination for any call
4850 // but memcmp; otherwise a verb appropriate to the call.
4851 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4852 if (BId == Builtin::BImemcpy)
4853 OperationType = 1;
4854 else if(BId == Builtin::BImemmove)
4855 OperationType = 2;
4856 else if (BId == Builtin::BImemcmp)
4857 OperationType = 3;
4858 }
4859
John McCall31168b02011-06-15 23:02:42 +00004860 DiagRuntimeBehavior(
4861 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00004862 PDiag(diag::warn_dyn_class_memaccess)
4863 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
4864 << FnName << IsContained << ContainedRD << OperationType
4865 << Call->getCallee()->getSourceRange());
4866 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4867 BId != Builtin::BImemset)
4868 DiagRuntimeBehavior(
4869 Dest->getExprLoc(), Dest,
4870 PDiag(diag::warn_arc_object_memaccess)
4871 << ArgIdx << FnName << PointeeTy
4872 << Call->getCallee()->getSourceRange());
4873 else
4874 continue;
4875
4876 DiagRuntimeBehavior(
4877 Dest->getExprLoc(), Dest,
4878 PDiag(diag::note_bad_memaccess_silence)
4879 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4880 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004881 }
Nico Weberc44b35e2015-03-21 17:37:46 +00004882
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004883}
4884
Ted Kremenek6865f772011-08-18 20:55:45 +00004885// A little helper routine: ignore addition and subtraction of integer literals.
4886// This intentionally does not ignore all integer constant expressions because
4887// we don't want to remove sizeof().
4888static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4889 Ex = Ex->IgnoreParenCasts();
4890
4891 for (;;) {
4892 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4893 if (!BO || !BO->isAdditiveOp())
4894 break;
4895
4896 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4897 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4898
4899 if (isa<IntegerLiteral>(RHS))
4900 Ex = LHS;
4901 else if (isa<IntegerLiteral>(LHS))
4902 Ex = RHS;
4903 else
4904 break;
4905 }
4906
4907 return Ex;
4908}
4909
Anna Zaks13b08572012-08-08 21:42:23 +00004910static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4911 ASTContext &Context) {
4912 // Only handle constant-sized or VLAs, but not flexible members.
4913 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4914 // Only issue the FIXIT for arrays of size > 1.
4915 if (CAT->getSize().getSExtValue() <= 1)
4916 return false;
4917 } else if (!Ty->isVariableArrayType()) {
4918 return false;
4919 }
4920 return true;
4921}
4922
Ted Kremenek6865f772011-08-18 20:55:45 +00004923// Warn if the user has made the 'size' argument to strlcpy or strlcat
4924// be the size of the source, instead of the destination.
4925void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4926 IdentifierInfo *FnName) {
4927
4928 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00004929 unsigned NumArgs = Call->getNumArgs();
4930 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00004931 return;
4932
4933 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4934 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004935 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00004936
4937 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4938 Call->getLocStart(), Call->getRParenLoc()))
4939 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004940
4941 // Look for 'strlcpy(dst, x, sizeof(x))'
4942 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4943 CompareWithSrc = Ex;
4944 else {
4945 // Look for 'strlcpy(dst, x, strlen(x))'
4946 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004947 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4948 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004949 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4950 }
4951 }
4952
4953 if (!CompareWithSrc)
4954 return;
4955
4956 // Determine if the argument to sizeof/strlen is equal to the source
4957 // argument. In principle there's all kinds of things you could do
4958 // here, for instance creating an == expression and evaluating it with
4959 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4960 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4961 if (!SrcArgDRE)
4962 return;
4963
4964 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4965 if (!CompareWithSrcDRE ||
4966 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4967 return;
4968
4969 const Expr *OriginalSizeArg = Call->getArg(2);
4970 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4971 << OriginalSizeArg->getSourceRange() << FnName;
4972
4973 // Output a FIXIT hint if the destination is an array (rather than a
4974 // pointer to an array). This could be enhanced to handle some
4975 // pointers if we know the actual size, like if DstArg is 'array+2'
4976 // we could say 'sizeof(array)-2'.
4977 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004978 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004979 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004980
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004981 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004982 llvm::raw_svector_ostream OS(sizeString);
4983 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004984 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004985 OS << ")";
4986
4987 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4988 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4989 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004990}
4991
Anna Zaks314cd092012-02-01 19:08:57 +00004992/// Check if two expressions refer to the same declaration.
4993static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4994 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4995 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4996 return D1->getDecl() == D2->getDecl();
4997 return false;
4998}
4999
5000static const Expr *getStrlenExprArg(const Expr *E) {
5001 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5002 const FunctionDecl *FD = CE->getDirectCallee();
5003 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00005004 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005005 return CE->getArg(0)->IgnoreParenCasts();
5006 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005007 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005008}
5009
5010// Warn on anti-patterns as the 'size' argument to strncat.
5011// The correct size argument should look like following:
5012// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5013void Sema::CheckStrncatArguments(const CallExpr *CE,
5014 IdentifierInfo *FnName) {
5015 // Don't crash if the user has the wrong number of arguments.
5016 if (CE->getNumArgs() < 3)
5017 return;
5018 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5019 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5020 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5021
Nico Weber0e6daef2013-12-26 23:38:39 +00005022 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5023 CE->getRParenLoc()))
5024 return;
5025
Anna Zaks314cd092012-02-01 19:08:57 +00005026 // Identify common expressions, which are wrongly used as the size argument
5027 // to strncat and may lead to buffer overflows.
5028 unsigned PatternType = 0;
5029 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5030 // - sizeof(dst)
5031 if (referToTheSameDecl(SizeOfArg, DstArg))
5032 PatternType = 1;
5033 // - sizeof(src)
5034 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5035 PatternType = 2;
5036 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5037 if (BE->getOpcode() == BO_Sub) {
5038 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5039 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5040 // - sizeof(dst) - strlen(dst)
5041 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5042 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5043 PatternType = 1;
5044 // - sizeof(src) - (anything)
5045 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5046 PatternType = 2;
5047 }
5048 }
5049
5050 if (PatternType == 0)
5051 return;
5052
Anna Zaks5069aa32012-02-03 01:27:37 +00005053 // Generate the diagnostic.
5054 SourceLocation SL = LenArg->getLocStart();
5055 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005056 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00005057
5058 // If the function is defined as a builtin macro, do not show macro expansion.
5059 if (SM.isMacroArgExpansion(SL)) {
5060 SL = SM.getSpellingLoc(SL);
5061 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5062 SM.getSpellingLoc(SR.getEnd()));
5063 }
5064
Anna Zaks13b08572012-08-08 21:42:23 +00005065 // Check if the destination is an array (rather than a pointer to an array).
5066 QualType DstTy = DstArg->getType();
5067 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5068 Context);
5069 if (!isKnownSizeArray) {
5070 if (PatternType == 1)
5071 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5072 else
5073 Diag(SL, diag::warn_strncat_src_size) << SR;
5074 return;
5075 }
5076
Anna Zaks314cd092012-02-01 19:08:57 +00005077 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00005078 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005079 else
Anna Zaks5069aa32012-02-03 01:27:37 +00005080 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005081
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005082 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00005083 llvm::raw_svector_ostream OS(sizeString);
5084 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005085 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005086 OS << ") - ";
5087 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005088 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005089 OS << ") - 1";
5090
Anna Zaks5069aa32012-02-03 01:27:37 +00005091 Diag(SL, diag::note_strncat_wrong_size)
5092 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005093}
5094
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005095//===--- CHECK: Return Address of Stack Variable --------------------------===//
5096
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005097static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5098 Decl *ParentDecl);
5099static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5100 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005101
5102/// CheckReturnStackAddr - Check if a return statement returns the address
5103/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005104static void
5105CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5106 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005107
Craig Topperc3ec1492014-05-26 06:22:03 +00005108 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005109 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005110
5111 // Perform checking for returned stack addresses, local blocks,
5112 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005113 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005114 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005115 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005116 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005117 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005118 }
5119
Craig Topperc3ec1492014-05-26 06:22:03 +00005120 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005121 return; // Nothing suspicious was found.
5122
5123 SourceLocation diagLoc;
5124 SourceRange diagRange;
5125 if (refVars.empty()) {
5126 diagLoc = stackE->getLocStart();
5127 diagRange = stackE->getSourceRange();
5128 } else {
5129 // We followed through a reference variable. 'stackE' contains the
5130 // problematic expression but we will warn at the return statement pointing
5131 // at the reference variable. We will later display the "trail" of
5132 // reference variables using notes.
5133 diagLoc = refVars[0]->getLocStart();
5134 diagRange = refVars[0]->getSourceRange();
5135 }
5136
5137 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005138 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005139 : diag::warn_ret_stack_addr)
5140 << DR->getDecl()->getDeclName() << diagRange;
5141 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005142 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005143 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005144 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005145 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005146 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
5147 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005148 << diagRange;
5149 }
5150
5151 // Display the "trail" of reference variables that we followed until we
5152 // found the problematic expression using notes.
5153 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5154 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5155 // If this var binds to another reference var, show the range of the next
5156 // var, otherwise the var binds to the problematic expression, in which case
5157 // show the range of the expression.
5158 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5159 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005160 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5161 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005162 }
5163}
5164
5165/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5166/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005167/// to a location on the stack, a local block, an address of a label, or a
5168/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005169/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005170/// encounter a subexpression that (1) clearly does not lead to one of the
5171/// above problematic expressions (2) is something we cannot determine leads to
5172/// a problematic expression based on such local checking.
5173///
5174/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5175/// the expression that they point to. Such variables are added to the
5176/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005177///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005178/// EvalAddr processes expressions that are pointers that are used as
5179/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005180/// At the base case of the recursion is a check for the above problematic
5181/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005182///
5183/// This implementation handles:
5184///
5185/// * pointer-to-pointer casts
5186/// * implicit conversions from array references to pointers
5187/// * taking the address of fields
5188/// * arbitrary interplay between "&" and "*" operators
5189/// * pointer arithmetic from an address of a stack variable
5190/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005191static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5192 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005193 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005194 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005195
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005196 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005197 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005198 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005199 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005200 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005201
Peter Collingbourne91147592011-04-15 00:35:48 +00005202 E = E->IgnoreParens();
5203
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005204 // Our "symbolic interpreter" is just a dispatch off the currently
5205 // viewed AST node. We then recursively traverse the AST by calling
5206 // EvalAddr and EvalVal appropriately.
5207 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005208 case Stmt::DeclRefExprClass: {
5209 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5210
Richard Smith40f08eb2014-01-30 22:05:38 +00005211 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005212 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005213 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005214
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005215 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5216 // If this is a reference variable, follow through to the expression that
5217 // it points to.
5218 if (V->hasLocalStorage() &&
5219 V->getType()->isReferenceType() && V->hasInit()) {
5220 // Add the reference variable to the "trail".
5221 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005222 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005223 }
5224
Craig Topperc3ec1492014-05-26 06:22:03 +00005225 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005226 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005227
Chris Lattner934edb22007-12-28 05:31:15 +00005228 case Stmt::UnaryOperatorClass: {
5229 // The only unary operator that make sense to handle here
5230 // is AddrOf. All others don't make sense as pointers.
5231 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005232
John McCalle3027922010-08-25 11:45:40 +00005233 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005234 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005235 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005236 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005237 }
Mike Stump11289f42009-09-09 15:08:12 +00005238
Chris Lattner934edb22007-12-28 05:31:15 +00005239 case Stmt::BinaryOperatorClass: {
5240 // Handle pointer arithmetic. All other binary operators are not valid
5241 // in this context.
5242 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005243 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005244
John McCalle3027922010-08-25 11:45:40 +00005245 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005246 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005247
Chris Lattner934edb22007-12-28 05:31:15 +00005248 Expr *Base = B->getLHS();
5249
5250 // Determine which argument is the real pointer base. It could be
5251 // the RHS argument instead of the LHS.
5252 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005253
Chris Lattner934edb22007-12-28 05:31:15 +00005254 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005255 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005256 }
Steve Naroff2752a172008-09-10 19:17:48 +00005257
Chris Lattner934edb22007-12-28 05:31:15 +00005258 // For conditional operators we need to see if either the LHS or RHS are
5259 // valid DeclRefExpr*s. If one of them is valid, we return it.
5260 case Stmt::ConditionalOperatorClass: {
5261 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005262
Chris Lattner934edb22007-12-28 05:31:15 +00005263 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005264 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5265 if (Expr *LHSExpr = C->getLHS()) {
5266 // In C++, we can have a throw-expression, which has 'void' type.
5267 if (!LHSExpr->getType()->isVoidType())
5268 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005269 return LHS;
5270 }
Chris Lattner934edb22007-12-28 05:31:15 +00005271
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005272 // In C++, we can have a throw-expression, which has 'void' type.
5273 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005274 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005275
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005276 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005277 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005278
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005279 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00005280 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005281 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00005282 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005283
5284 case Stmt::AddrLabelExprClass:
5285 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00005286
John McCall28fc7092011-11-10 05:35:25 +00005287 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005288 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5289 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005290
Ted Kremenekc3b4c522008-08-07 00:49:01 +00005291 // For casts, we need to handle conversions from arrays to
5292 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00005293 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00005294 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005295 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00005296 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00005297 case Stmt::CXXStaticCastExprClass:
5298 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00005299 case Stmt::CXXConstCastExprClass:
5300 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00005301 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5302 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00005303 case CK_LValueToRValue:
5304 case CK_NoOp:
5305 case CK_BaseToDerived:
5306 case CK_DerivedToBase:
5307 case CK_UncheckedDerivedToBase:
5308 case CK_Dynamic:
5309 case CK_CPointerToObjCPointerCast:
5310 case CK_BlockPointerToObjCPointerCast:
5311 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005312 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005313
5314 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005315 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005316
Richard Trieudadefde2014-07-02 04:39:38 +00005317 case CK_BitCast:
5318 if (SubExpr->getType()->isAnyPointerType() ||
5319 SubExpr->getType()->isBlockPointerType() ||
5320 SubExpr->getType()->isObjCQualifiedIdType())
5321 return EvalAddr(SubExpr, refVars, ParentDecl);
5322 else
5323 return nullptr;
5324
Eli Friedman8195ad72012-02-23 23:04:32 +00005325 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005326 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00005327 }
Chris Lattner934edb22007-12-28 05:31:15 +00005328 }
Mike Stump11289f42009-09-09 15:08:12 +00005329
Douglas Gregorfe314812011-06-21 17:03:29 +00005330 case Stmt::MaterializeTemporaryExprClass:
5331 if (Expr *Result = EvalAddr(
5332 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005333 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005334 return Result;
5335
5336 return E;
5337
Chris Lattner934edb22007-12-28 05:31:15 +00005338 // Everything else: we simply don't reason about them.
5339 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005340 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00005341 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005342}
Mike Stump11289f42009-09-09 15:08:12 +00005343
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005344
5345/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5346/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005347static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5348 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005349do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005350 // We should only be called for evaluating non-pointer expressions, or
5351 // expressions with a pointer type that are not used as references but instead
5352 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00005353
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005354 // Our "symbolic interpreter" is just a dispatch off the currently
5355 // viewed AST node. We then recursively traverse the AST by calling
5356 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00005357
5358 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005359 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005360 case Stmt::ImplicitCastExprClass: {
5361 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00005362 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005363 E = IE->getSubExpr();
5364 continue;
5365 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005366 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00005367 }
5368
John McCall28fc7092011-11-10 05:35:25 +00005369 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005370 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005371
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005372 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005373 // When we hit a DeclRefExpr we are looking at code that refers to a
5374 // variable's name. If it's not a reference variable we check if it has
5375 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005376 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005377
Richard Smith40f08eb2014-01-30 22:05:38 +00005378 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005379 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005380 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005381
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005382 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5383 // Check if it refers to itself, e.g. "int& i = i;".
5384 if (V == ParentDecl)
5385 return DR;
5386
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005387 if (V->hasLocalStorage()) {
5388 if (!V->getType()->isReferenceType())
5389 return DR;
5390
5391 // Reference variable, follow through to the expression that
5392 // it points to.
5393 if (V->hasInit()) {
5394 // Add the reference variable to the "trail".
5395 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005396 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005397 }
5398 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005399 }
Mike Stump11289f42009-09-09 15:08:12 +00005400
Craig Topperc3ec1492014-05-26 06:22:03 +00005401 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005402 }
Mike Stump11289f42009-09-09 15:08:12 +00005403
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005404 case Stmt::UnaryOperatorClass: {
5405 // The only unary operator that make sense to handle here
5406 // is Deref. All others don't resolve to a "name." This includes
5407 // handling all sorts of rvalues passed to a unary operator.
5408 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005409
John McCalle3027922010-08-25 11:45:40 +00005410 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005411 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005412
Craig Topperc3ec1492014-05-26 06:22:03 +00005413 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005414 }
Mike Stump11289f42009-09-09 15:08:12 +00005415
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005416 case Stmt::ArraySubscriptExprClass: {
5417 // Array subscripts are potential references to data on the stack. We
5418 // retrieve the DeclRefExpr* for the array variable if it indeed
5419 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005420 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005421 }
Mike Stump11289f42009-09-09 15:08:12 +00005422
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005423 case Stmt::ConditionalOperatorClass: {
5424 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005425 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005426 ConditionalOperator *C = cast<ConditionalOperator>(E);
5427
Anders Carlsson801c5c72007-11-30 19:04:31 +00005428 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005429 if (Expr *LHSExpr = C->getLHS()) {
5430 // In C++, we can have a throw-expression, which has 'void' type.
5431 if (!LHSExpr->getType()->isVoidType())
5432 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5433 return LHS;
5434 }
5435
5436 // In C++, we can have a throw-expression, which has 'void' type.
5437 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005438 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005439
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005440 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005441 }
Mike Stump11289f42009-09-09 15:08:12 +00005442
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005443 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005444 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005445 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005446
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005447 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005448 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005449 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005450
5451 // Check whether the member type is itself a reference, in which case
5452 // we're not going to refer to the member, but to what the member refers to.
5453 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005454 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005455
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005456 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005457 }
Mike Stump11289f42009-09-09 15:08:12 +00005458
Douglas Gregorfe314812011-06-21 17:03:29 +00005459 case Stmt::MaterializeTemporaryExprClass:
5460 if (Expr *Result = EvalVal(
5461 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005462 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005463 return Result;
5464
5465 return E;
5466
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005467 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005468 // Check that we don't return or take the address of a reference to a
5469 // temporary. This is only useful in C++.
5470 if (!E->isTypeDependent() && E->isRValue())
5471 return E;
5472
5473 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005474 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005475 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005476} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005477}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005478
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005479void
5480Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5481 SourceLocation ReturnLoc,
5482 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005483 const AttrVec *Attrs,
5484 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005485 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5486
5487 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00005488 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5489 CheckNonNullExpr(*this, RetValExp))
5490 Diag(ReturnLoc, diag::warn_null_ret)
5491 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00005492
5493 // C++11 [basic.stc.dynamic.allocation]p4:
5494 // If an allocation function declared with a non-throwing
5495 // exception-specification fails to allocate storage, it shall return
5496 // a null pointer. Any other allocation function that fails to allocate
5497 // storage shall indicate failure only by throwing an exception [...]
5498 if (FD) {
5499 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5500 if (Op == OO_New || Op == OO_Array_New) {
5501 const FunctionProtoType *Proto
5502 = FD->getType()->castAs<FunctionProtoType>();
5503 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5504 CheckNonNullExpr(*this, RetValExp))
5505 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5506 << FD << getLangOpts().CPlusPlus11;
5507 }
5508 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005509}
5510
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005511//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5512
5513/// Check for comparisons of floating point operands using != and ==.
5514/// Issue a warning if these are no self-comparisons, as they are not likely
5515/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00005516void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00005517 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5518 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005519
5520 // Special case: check for x == x (which is OK).
5521 // Do not emit warnings for such cases.
5522 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5523 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5524 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00005525 return;
Mike Stump11289f42009-09-09 15:08:12 +00005526
5527
Ted Kremenekeda40e22007-11-29 00:59:04 +00005528 // Special case: check for comparisons against literals that can be exactly
5529 // represented by APFloat. In such cases, do not emit a warning. This
5530 // is a heuristic: often comparison against such literals are used to
5531 // detect if a value in a variable has not changed. This clearly can
5532 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00005533 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5534 if (FLL->isExact())
5535 return;
5536 } else
5537 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5538 if (FLR->isExact())
5539 return;
Mike Stump11289f42009-09-09 15:08:12 +00005540
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005541 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00005542 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005543 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005544 return;
Mike Stump11289f42009-09-09 15:08:12 +00005545
David Blaikie1f4ff152012-07-16 20:47:22 +00005546 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005547 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005548 return;
Mike Stump11289f42009-09-09 15:08:12 +00005549
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005550 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00005551 Diag(Loc, diag::warn_floatingpoint_eq)
5552 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005553}
John McCallca01b222010-01-04 23:21:16 +00005554
John McCall70aa5392010-01-06 05:24:50 +00005555//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5556//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00005557
John McCall70aa5392010-01-06 05:24:50 +00005558namespace {
John McCallca01b222010-01-04 23:21:16 +00005559
John McCall70aa5392010-01-06 05:24:50 +00005560/// Structure recording the 'active' range of an integer-valued
5561/// expression.
5562struct IntRange {
5563 /// The number of bits active in the int.
5564 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00005565
John McCall70aa5392010-01-06 05:24:50 +00005566 /// True if the int is known not to have negative values.
5567 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00005568
John McCall70aa5392010-01-06 05:24:50 +00005569 IntRange(unsigned Width, bool NonNegative)
5570 : Width(Width), NonNegative(NonNegative)
5571 {}
John McCallca01b222010-01-04 23:21:16 +00005572
John McCall817d4af2010-11-10 23:38:19 +00005573 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00005574 static IntRange forBoolType() {
5575 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00005576 }
5577
John McCall817d4af2010-11-10 23:38:19 +00005578 /// Returns the range of an opaque value of the given integral type.
5579 static IntRange forValueOfType(ASTContext &C, QualType T) {
5580 return forValueOfCanonicalType(C,
5581 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00005582 }
5583
John McCall817d4af2010-11-10 23:38:19 +00005584 /// Returns the range of an opaque value of a canonical integral type.
5585 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00005586 assert(T->isCanonicalUnqualified());
5587
5588 if (const VectorType *VT = dyn_cast<VectorType>(T))
5589 T = VT->getElementType().getTypePtr();
5590 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5591 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005592 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5593 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00005594
David Majnemer6a426652013-06-07 22:07:20 +00005595 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00005596 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00005597 EnumDecl *Enum = ET->getDecl();
5598 if (!Enum->isCompleteDefinition())
5599 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00005600
David Majnemer6a426652013-06-07 22:07:20 +00005601 unsigned NumPositive = Enum->getNumPositiveBits();
5602 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00005603
David Majnemer6a426652013-06-07 22:07:20 +00005604 if (NumNegative == 0)
5605 return IntRange(NumPositive, true/*NonNegative*/);
5606 else
5607 return IntRange(std::max(NumPositive + 1, NumNegative),
5608 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00005609 }
John McCall70aa5392010-01-06 05:24:50 +00005610
5611 const BuiltinType *BT = cast<BuiltinType>(T);
5612 assert(BT->isInteger());
5613
5614 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5615 }
5616
John McCall817d4af2010-11-10 23:38:19 +00005617 /// Returns the "target" range of a canonical integral type, i.e.
5618 /// the range of values expressible in the type.
5619 ///
5620 /// This matches forValueOfCanonicalType except that enums have the
5621 /// full range of their type, not the range of their enumerators.
5622 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5623 assert(T->isCanonicalUnqualified());
5624
5625 if (const VectorType *VT = dyn_cast<VectorType>(T))
5626 T = VT->getElementType().getTypePtr();
5627 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5628 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005629 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5630 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005631 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00005632 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005633
5634 const BuiltinType *BT = cast<BuiltinType>(T);
5635 assert(BT->isInteger());
5636
5637 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5638 }
5639
5640 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00005641 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00005642 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00005643 L.NonNegative && R.NonNegative);
5644 }
5645
John McCall817d4af2010-11-10 23:38:19 +00005646 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00005647 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00005648 return IntRange(std::min(L.Width, R.Width),
5649 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00005650 }
5651};
5652
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005653static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5654 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005655 if (value.isSigned() && value.isNegative())
5656 return IntRange(value.getMinSignedBits(), false);
5657
5658 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005659 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005660
5661 // isNonNegative() just checks the sign bit without considering
5662 // signedness.
5663 return IntRange(value.getActiveBits(), true);
5664}
5665
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005666static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5667 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005668 if (result.isInt())
5669 return GetValueRange(C, result.getInt(), MaxWidth);
5670
5671 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00005672 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5673 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5674 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5675 R = IntRange::join(R, El);
5676 }
John McCall70aa5392010-01-06 05:24:50 +00005677 return R;
5678 }
5679
5680 if (result.isComplexInt()) {
5681 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5682 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5683 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00005684 }
5685
5686 // This can happen with lossless casts to intptr_t of "based" lvalues.
5687 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00005688 // FIXME: The only reason we need to pass the type in here is to get
5689 // the sign right on this one case. It would be nice if APValue
5690 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005691 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00005692 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005693}
John McCall70aa5392010-01-06 05:24:50 +00005694
Eli Friedmane6d33952013-07-08 20:20:06 +00005695static QualType GetExprType(Expr *E) {
5696 QualType Ty = E->getType();
5697 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5698 Ty = AtomicRHS->getValueType();
5699 return Ty;
5700}
5701
John McCall70aa5392010-01-06 05:24:50 +00005702/// Pseudo-evaluate the given integer expression, estimating the
5703/// range of values it might take.
5704///
5705/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005706static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005707 E = E->IgnoreParens();
5708
5709 // Try a full evaluation first.
5710 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005711 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005712 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005713
5714 // I think we only want to look through implicit casts here; if the
5715 // user has an explicit widening cast, we should treat the value as
5716 // being of the new, wider type.
5717 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005718 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005719 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5720
Eli Friedmane6d33952013-07-08 20:20:06 +00005721 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005722
John McCalle3027922010-08-25 11:45:40 +00005723 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005724
John McCall70aa5392010-01-06 05:24:50 +00005725 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005726 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005727 return OutputTypeRange;
5728
5729 IntRange SubRange
5730 = GetExprRange(C, CE->getSubExpr(),
5731 std::min(MaxWidth, OutputTypeRange.Width));
5732
5733 // Bail out if the subexpr's range is as wide as the cast type.
5734 if (SubRange.Width >= OutputTypeRange.Width)
5735 return OutputTypeRange;
5736
5737 // Otherwise, we take the smaller width, and we're non-negative if
5738 // either the output type or the subexpr is.
5739 return IntRange(SubRange.Width,
5740 SubRange.NonNegative || OutputTypeRange.NonNegative);
5741 }
5742
5743 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5744 // If we can fold the condition, just take that operand.
5745 bool CondResult;
5746 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5747 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5748 : CO->getFalseExpr(),
5749 MaxWidth);
5750
5751 // Otherwise, conservatively merge.
5752 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5753 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5754 return IntRange::join(L, R);
5755 }
5756
5757 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5758 switch (BO->getOpcode()) {
5759
5760 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005761 case BO_LAnd:
5762 case BO_LOr:
5763 case BO_LT:
5764 case BO_GT:
5765 case BO_LE:
5766 case BO_GE:
5767 case BO_EQ:
5768 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005769 return IntRange::forBoolType();
5770
John McCallc3688382011-07-13 06:35:24 +00005771 // The type of the assignments is the type of the LHS, so the RHS
5772 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005773 case BO_MulAssign:
5774 case BO_DivAssign:
5775 case BO_RemAssign:
5776 case BO_AddAssign:
5777 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005778 case BO_XorAssign:
5779 case BO_OrAssign:
5780 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005781 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005782
John McCallc3688382011-07-13 06:35:24 +00005783 // Simple assignments just pass through the RHS, which will have
5784 // been coerced to the LHS type.
5785 case BO_Assign:
5786 // TODO: bitfields?
5787 return GetExprRange(C, BO->getRHS(), MaxWidth);
5788
John McCall70aa5392010-01-06 05:24:50 +00005789 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005790 case BO_PtrMemD:
5791 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005792 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005793
John McCall2ce81ad2010-01-06 22:07:33 +00005794 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005795 case BO_And:
5796 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005797 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5798 GetExprRange(C, BO->getRHS(), MaxWidth));
5799
John McCall70aa5392010-01-06 05:24:50 +00005800 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005801 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005802 // ...except that we want to treat '1 << (blah)' as logically
5803 // positive. It's an important idiom.
5804 if (IntegerLiteral *I
5805 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5806 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005807 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005808 return IntRange(R.Width, /*NonNegative*/ true);
5809 }
5810 }
5811 // fallthrough
5812
John McCalle3027922010-08-25 11:45:40 +00005813 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005814 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005815
John McCall2ce81ad2010-01-06 22:07:33 +00005816 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005817 case BO_Shr:
5818 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005819 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5820
5821 // If the shift amount is a positive constant, drop the width by
5822 // that much.
5823 llvm::APSInt shift;
5824 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5825 shift.isNonNegative()) {
5826 unsigned zext = shift.getZExtValue();
5827 if (zext >= L.Width)
5828 L.Width = (L.NonNegative ? 0 : 1);
5829 else
5830 L.Width -= zext;
5831 }
5832
5833 return L;
5834 }
5835
5836 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005837 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005838 return GetExprRange(C, BO->getRHS(), MaxWidth);
5839
John McCall2ce81ad2010-01-06 22:07:33 +00005840 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005841 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005842 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005843 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005844 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005845
John McCall51431812011-07-14 22:39:48 +00005846 // The width of a division result is mostly determined by the size
5847 // of the LHS.
5848 case BO_Div: {
5849 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005850 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005851 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5852
5853 // If the divisor is constant, use that.
5854 llvm::APSInt divisor;
5855 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5856 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5857 if (log2 >= L.Width)
5858 L.Width = (L.NonNegative ? 0 : 1);
5859 else
5860 L.Width = std::min(L.Width - log2, MaxWidth);
5861 return L;
5862 }
5863
5864 // Otherwise, just use the LHS's width.
5865 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5866 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5867 }
5868
5869 // The result of a remainder can't be larger than the result of
5870 // either side.
5871 case BO_Rem: {
5872 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005873 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005874 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5875 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5876
5877 IntRange meet = IntRange::meet(L, R);
5878 meet.Width = std::min(meet.Width, MaxWidth);
5879 return meet;
5880 }
5881
5882 // The default behavior is okay for these.
5883 case BO_Mul:
5884 case BO_Add:
5885 case BO_Xor:
5886 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005887 break;
5888 }
5889
John McCall51431812011-07-14 22:39:48 +00005890 // The default case is to treat the operation as if it were closed
5891 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005892 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5893 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5894 return IntRange::join(L, R);
5895 }
5896
5897 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5898 switch (UO->getOpcode()) {
5899 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005900 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005901 return IntRange::forBoolType();
5902
5903 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005904 case UO_Deref:
5905 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005906 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005907
5908 default:
5909 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5910 }
5911 }
5912
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005913 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5914 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5915
John McCalld25db7e2013-05-06 21:39:12 +00005916 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005917 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005918 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005919
Eli Friedmane6d33952013-07-08 20:20:06 +00005920 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005921}
John McCall263a48b2010-01-04 23:31:57 +00005922
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005923static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005924 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005925}
5926
John McCall263a48b2010-01-04 23:31:57 +00005927/// Checks whether the given value, which currently has the given
5928/// source semantics, has the same value when coerced through the
5929/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005930static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5931 const llvm::fltSemantics &Src,
5932 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005933 llvm::APFloat truncated = value;
5934
5935 bool ignored;
5936 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5937 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5938
5939 return truncated.bitwiseIsEqual(value);
5940}
5941
5942/// Checks whether the given value, which currently has the given
5943/// source semantics, has the same value when coerced through the
5944/// target semantics.
5945///
5946/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005947static bool IsSameFloatAfterCast(const APValue &value,
5948 const llvm::fltSemantics &Src,
5949 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005950 if (value.isFloat())
5951 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5952
5953 if (value.isVector()) {
5954 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5955 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5956 return false;
5957 return true;
5958 }
5959
5960 assert(value.isComplexFloat());
5961 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5962 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5963}
5964
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005965static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005966
Ted Kremenek6274be42010-09-23 21:43:44 +00005967static bool IsZero(Sema &S, Expr *E) {
5968 // Suppress cases where we are comparing against an enum constant.
5969 if (const DeclRefExpr *DR =
5970 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5971 if (isa<EnumConstantDecl>(DR->getDecl()))
5972 return false;
5973
5974 // Suppress cases where the '0' value is expanded from a macro.
5975 if (E->getLocStart().isMacroID())
5976 return false;
5977
John McCallcc7e5bf2010-05-06 08:58:33 +00005978 llvm::APSInt Value;
5979 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5980}
5981
John McCall2551c1b2010-10-06 00:25:24 +00005982static bool HasEnumType(Expr *E) {
5983 // Strip off implicit integral promotions.
5984 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005985 if (ICE->getCastKind() != CK_IntegralCast &&
5986 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005987 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005988 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005989 }
5990
5991 return E->getType()->isEnumeralType();
5992}
5993
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005994static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005995 // Disable warning in template instantiations.
5996 if (!S.ActiveTemplateInstantiations.empty())
5997 return;
5998
John McCalle3027922010-08-25 11:45:40 +00005999 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00006000 if (E->isValueDependent())
6001 return;
6002
John McCalle3027922010-08-25 11:45:40 +00006003 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006004 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006005 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006006 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006007 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006008 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006009 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006010 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006011 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006012 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006013 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006014 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006015 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006016 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006017 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006018 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6019 }
6020}
6021
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006022static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006023 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006024 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006025 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00006026 // Disable warning in template instantiations.
6027 if (!S.ActiveTemplateInstantiations.empty())
6028 return;
6029
Richard Trieu0f097742014-04-04 04:13:47 +00006030 // TODO: Investigate using GetExprRange() to get tighter bounds
6031 // on the bit ranges.
6032 QualType OtherT = Other->getType();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006033 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
6034 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00006035 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6036 unsigned OtherWidth = OtherRange.Width;
6037
6038 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6039
Richard Trieu560910c2012-11-14 22:50:24 +00006040 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00006041 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00006042 return;
6043
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006044 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00006045 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006046
Richard Trieu0f097742014-04-04 04:13:47 +00006047 // Used for diagnostic printout.
6048 enum {
6049 LiteralConstant = 0,
6050 CXXBoolLiteralTrue,
6051 CXXBoolLiteralFalse
6052 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006053
Richard Trieu0f097742014-04-04 04:13:47 +00006054 if (!OtherIsBooleanType) {
6055 QualType ConstantT = Constant->getType();
6056 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00006057
Richard Trieu0f097742014-04-04 04:13:47 +00006058 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6059 return;
6060 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6061 "comparison with non-integer type");
6062
6063 bool ConstantSigned = ConstantT->isSignedIntegerType();
6064 bool CommonSigned = CommonT->isSignedIntegerType();
6065
6066 bool EqualityOnly = false;
6067
6068 if (CommonSigned) {
6069 // The common type is signed, therefore no signed to unsigned conversion.
6070 if (!OtherRange.NonNegative) {
6071 // Check that the constant is representable in type OtherT.
6072 if (ConstantSigned) {
6073 if (OtherWidth >= Value.getMinSignedBits())
6074 return;
6075 } else { // !ConstantSigned
6076 if (OtherWidth >= Value.getActiveBits() + 1)
6077 return;
6078 }
6079 } else { // !OtherSigned
6080 // Check that the constant is representable in type OtherT.
6081 // Negative values are out of range.
6082 if (ConstantSigned) {
6083 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6084 return;
6085 } else { // !ConstantSigned
6086 if (OtherWidth >= Value.getActiveBits())
6087 return;
6088 }
Richard Trieu560910c2012-11-14 22:50:24 +00006089 }
Richard Trieu0f097742014-04-04 04:13:47 +00006090 } else { // !CommonSigned
6091 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006092 if (OtherWidth >= Value.getActiveBits())
6093 return;
Craig Toppercf360162014-06-18 05:13:11 +00006094 } else { // OtherSigned
6095 assert(!ConstantSigned &&
6096 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006097 // Check to see if the constant is representable in OtherT.
6098 if (OtherWidth > Value.getActiveBits())
6099 return;
6100 // Check to see if the constant is equivalent to a negative value
6101 // cast to CommonT.
6102 if (S.Context.getIntWidth(ConstantT) ==
6103 S.Context.getIntWidth(CommonT) &&
6104 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6105 return;
6106 // The constant value rests between values that OtherT can represent
6107 // after conversion. Relational comparison still works, but equality
6108 // comparisons will be tautological.
6109 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006110 }
6111 }
Richard Trieu0f097742014-04-04 04:13:47 +00006112
6113 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6114
6115 if (op == BO_EQ || op == BO_NE) {
6116 IsTrue = op == BO_NE;
6117 } else if (EqualityOnly) {
6118 return;
6119 } else if (RhsConstant) {
6120 if (op == BO_GT || op == BO_GE)
6121 IsTrue = !PositiveConstant;
6122 else // op == BO_LT || op == BO_LE
6123 IsTrue = PositiveConstant;
6124 } else {
6125 if (op == BO_LT || op == BO_LE)
6126 IsTrue = !PositiveConstant;
6127 else // op == BO_GT || op == BO_GE
6128 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006129 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006130 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00006131 // Other isKnownToHaveBooleanValue
6132 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6133 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6134 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6135
6136 static const struct LinkedConditions {
6137 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6138 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6139 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6140 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6141 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6142 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6143
6144 } TruthTable = {
6145 // Constant on LHS. | Constant on RHS. |
6146 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6147 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6148 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6149 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6150 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6151 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6152 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6153 };
6154
6155 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6156
6157 enum ConstantValue ConstVal = Zero;
6158 if (Value.isUnsigned() || Value.isNonNegative()) {
6159 if (Value == 0) {
6160 LiteralOrBoolConstant =
6161 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6162 ConstVal = Zero;
6163 } else if (Value == 1) {
6164 LiteralOrBoolConstant =
6165 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6166 ConstVal = One;
6167 } else {
6168 LiteralOrBoolConstant = LiteralConstant;
6169 ConstVal = GT_One;
6170 }
6171 } else {
6172 ConstVal = LT_Zero;
6173 }
6174
6175 CompareBoolWithConstantResult CmpRes;
6176
6177 switch (op) {
6178 case BO_LT:
6179 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6180 break;
6181 case BO_GT:
6182 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6183 break;
6184 case BO_LE:
6185 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6186 break;
6187 case BO_GE:
6188 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6189 break;
6190 case BO_EQ:
6191 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6192 break;
6193 case BO_NE:
6194 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6195 break;
6196 default:
6197 CmpRes = Unkwn;
6198 break;
6199 }
6200
6201 if (CmpRes == AFals) {
6202 IsTrue = false;
6203 } else if (CmpRes == ATrue) {
6204 IsTrue = true;
6205 } else {
6206 return;
6207 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006208 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006209
6210 // If this is a comparison to an enum constant, include that
6211 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006212 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006213 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6214 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6215
6216 SmallString<64> PrettySourceValue;
6217 llvm::raw_svector_ostream OS(PrettySourceValue);
6218 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00006219 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006220 else
6221 OS << Value;
6222
Richard Trieu0f097742014-04-04 04:13:47 +00006223 S.DiagRuntimeBehavior(
6224 E->getOperatorLoc(), E,
6225 S.PDiag(diag::warn_out_of_range_compare)
6226 << OS.str() << LiteralOrBoolConstant
6227 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6228 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006229}
6230
John McCallcc7e5bf2010-05-06 08:58:33 +00006231/// Analyze the operands of the given comparison. Implements the
6232/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006233static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00006234 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6235 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006236}
John McCall263a48b2010-01-04 23:31:57 +00006237
John McCallca01b222010-01-04 23:21:16 +00006238/// \brief Implements -Wsign-compare.
6239///
Richard Trieu82402a02011-09-15 21:56:47 +00006240/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006241static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006242 // The type the comparison is being performed in.
6243 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006244
6245 // Only analyze comparison operators where both sides have been converted to
6246 // the same type.
6247 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6248 return AnalyzeImpConvsInComparison(S, E);
6249
6250 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006251 if (E->isValueDependent())
6252 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006253
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006254 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6255 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006256
6257 bool IsComparisonConstant = false;
6258
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006259 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006260 // of 'true' or 'false'.
6261 if (T->isIntegralType(S.Context)) {
6262 llvm::APSInt RHSValue;
6263 bool IsRHSIntegralLiteral =
6264 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6265 llvm::APSInt LHSValue;
6266 bool IsLHSIntegralLiteral =
6267 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6268 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6269 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6270 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6271 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6272 else
6273 IsComparisonConstant =
6274 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006275 } else if (!T->hasUnsignedIntegerRepresentation())
6276 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006277
John McCallcc7e5bf2010-05-06 08:58:33 +00006278 // We don't do anything special if this isn't an unsigned integral
6279 // comparison: we're only interested in integral comparisons, and
6280 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00006281 //
6282 // We also don't care about value-dependent expressions or expressions
6283 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006284 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00006285 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006286
John McCallcc7e5bf2010-05-06 08:58:33 +00006287 // Check to see if one of the (unmodified) operands is of different
6288 // signedness.
6289 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00006290 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6291 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00006292 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00006293 signedOperand = LHS;
6294 unsignedOperand = RHS;
6295 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6296 signedOperand = RHS;
6297 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00006298 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00006299 CheckTrivialUnsignedComparison(S, E);
6300 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006301 }
6302
John McCallcc7e5bf2010-05-06 08:58:33 +00006303 // Otherwise, calculate the effective range of the signed operand.
6304 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00006305
John McCallcc7e5bf2010-05-06 08:58:33 +00006306 // Go ahead and analyze implicit conversions in the operands. Note
6307 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00006308 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6309 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00006310
John McCallcc7e5bf2010-05-06 08:58:33 +00006311 // If the signed range is non-negative, -Wsign-compare won't fire,
6312 // but we should still check for comparisons which are always true
6313 // or false.
6314 if (signedRange.NonNegative)
6315 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006316
6317 // For (in)equality comparisons, if the unsigned operand is a
6318 // constant which cannot collide with a overflowed signed operand,
6319 // then reinterpreting the signed operand as unsigned will not
6320 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00006321 if (E->isEqualityOp()) {
6322 unsigned comparisonWidth = S.Context.getIntWidth(T);
6323 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00006324
John McCallcc7e5bf2010-05-06 08:58:33 +00006325 // We should never be unable to prove that the unsigned operand is
6326 // non-negative.
6327 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6328
6329 if (unsignedRange.Width < comparisonWidth)
6330 return;
6331 }
6332
Douglas Gregorbfb4a212012-05-01 01:53:49 +00006333 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6334 S.PDiag(diag::warn_mixed_sign_comparison)
6335 << LHS->getType() << RHS->getType()
6336 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00006337}
6338
John McCall1f425642010-11-11 03:21:53 +00006339/// Analyzes an attempt to assign the given value to a bitfield.
6340///
6341/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006342static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6343 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00006344 assert(Bitfield->isBitField());
6345 if (Bitfield->isInvalidDecl())
6346 return false;
6347
John McCalldeebbcf2010-11-11 05:33:51 +00006348 // White-list bool bitfields.
6349 if (Bitfield->getType()->isBooleanType())
6350 return false;
6351
Douglas Gregor789adec2011-02-04 13:09:01 +00006352 // Ignore value- or type-dependent expressions.
6353 if (Bitfield->getBitWidth()->isValueDependent() ||
6354 Bitfield->getBitWidth()->isTypeDependent() ||
6355 Init->isValueDependent() ||
6356 Init->isTypeDependent())
6357 return false;
6358
John McCall1f425642010-11-11 03:21:53 +00006359 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6360
Richard Smith5fab0c92011-12-28 19:48:30 +00006361 llvm::APSInt Value;
6362 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00006363 return false;
6364
John McCall1f425642010-11-11 03:21:53 +00006365 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00006366 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00006367
6368 if (OriginalWidth <= FieldWidth)
6369 return false;
6370
Eli Friedmanc267a322012-01-26 23:11:39 +00006371 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006372 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00006373 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00006374
Eli Friedmanc267a322012-01-26 23:11:39 +00006375 // Check whether the stored value is equal to the original value.
6376 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00006377 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00006378 return false;
6379
Eli Friedmanc267a322012-01-26 23:11:39 +00006380 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00006381 // therefore don't strictly fit into a signed bitfield of width 1.
6382 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00006383 return false;
6384
John McCall1f425642010-11-11 03:21:53 +00006385 std::string PrettyValue = Value.toString(10);
6386 std::string PrettyTrunc = TruncatedValue.toString(10);
6387
6388 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6389 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6390 << Init->getSourceRange();
6391
6392 return true;
6393}
6394
John McCalld2a53122010-11-09 23:24:47 +00006395/// Analyze the given simple or compound assignment for warning-worthy
6396/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006397static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006398 // Just recurse on the LHS.
6399 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6400
6401 // We want to recurse on the RHS as normal unless we're assigning to
6402 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006403 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006404 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006405 E->getOperatorLoc())) {
6406 // Recurse, ignoring any implicit conversions on the RHS.
6407 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6408 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006409 }
6410 }
6411
6412 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6413}
6414
John McCall263a48b2010-01-04 23:31:57 +00006415/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006416static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006417 SourceLocation CContext, unsigned diag,
6418 bool pruneControlFlow = false) {
6419 if (pruneControlFlow) {
6420 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6421 S.PDiag(diag)
6422 << SourceType << T << E->getSourceRange()
6423 << SourceRange(CContext));
6424 return;
6425 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006426 S.Diag(E->getExprLoc(), diag)
6427 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6428}
6429
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006430/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006431static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006432 SourceLocation CContext, unsigned diag,
6433 bool pruneControlFlow = false) {
6434 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006435}
6436
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006437/// Diagnose an implicit cast from a literal expression. Does not warn when the
6438/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006439void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6440 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006441 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006442 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006443 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006444 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6445 T->hasUnsignedIntegerRepresentation());
6446 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006447 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006448 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006449 return;
6450
Eli Friedman07185912013-08-29 23:44:43 +00006451 // FIXME: Force the precision of the source value down so we don't print
6452 // digits which are usually useless (we don't really care here if we
6453 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6454 // would automatically print the shortest representation, but it's a bit
6455 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006456 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006457 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6458 precision = (precision * 59 + 195) / 196;
6459 Value.toString(PrettySourceValue, precision);
6460
David Blaikie9b88cc02012-05-15 17:18:27 +00006461 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006462 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6463 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6464 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006465 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006466
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006467 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006468 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6469 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006470}
6471
John McCall18a2c2c2010-11-09 22:22:12 +00006472std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6473 if (!Range.Width) return "0";
6474
6475 llvm::APSInt ValueInRange = Value;
6476 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006477 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006478 return ValueInRange.toString(10);
6479}
6480
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006481static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6482 if (!isa<ImplicitCastExpr>(Ex))
6483 return false;
6484
6485 Expr *InnerE = Ex->IgnoreParenImpCasts();
6486 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6487 const Type *Source =
6488 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6489 if (Target->isDependentType())
6490 return false;
6491
6492 const BuiltinType *FloatCandidateBT =
6493 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6494 const Type *BoolCandidateType = ToBool ? Target : Source;
6495
6496 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6497 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6498}
6499
6500void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6501 SourceLocation CC) {
6502 unsigned NumArgs = TheCall->getNumArgs();
6503 for (unsigned i = 0; i < NumArgs; ++i) {
6504 Expr *CurrA = TheCall->getArg(i);
6505 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6506 continue;
6507
6508 bool IsSwapped = ((i > 0) &&
6509 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6510 IsSwapped |= ((i < (NumArgs - 1)) &&
6511 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6512 if (IsSwapped) {
6513 // Warn on this floating-point to bool conversion.
6514 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6515 CurrA->getType(), CC,
6516 diag::warn_impcast_floating_point_to_bool);
6517 }
6518 }
6519}
6520
Richard Trieu5b993502014-10-15 03:42:06 +00006521static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6522 SourceLocation CC) {
6523 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6524 E->getExprLoc()))
6525 return;
6526
6527 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6528 const Expr::NullPointerConstantKind NullKind =
6529 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6530 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6531 return;
6532
6533 // Return if target type is a safe conversion.
6534 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6535 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6536 return;
6537
6538 SourceLocation Loc = E->getSourceRange().getBegin();
6539
6540 // __null is usually wrapped in a macro. Go up a macro if that is the case.
6541 if (NullKind == Expr::NPCK_GNUNull) {
6542 if (Loc.isMacroID())
6543 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6544 }
6545
6546 // Only warn if the null and context location are in the same macro expansion.
6547 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6548 return;
6549
6550 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6551 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6552 << FixItHint::CreateReplacement(Loc,
6553 S.getFixItZeroLiteralForType(T, Loc));
6554}
6555
John McCallcc7e5bf2010-05-06 08:58:33 +00006556void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00006557 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006558 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00006559
John McCallcc7e5bf2010-05-06 08:58:33 +00006560 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6561 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6562 if (Source == Target) return;
6563 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00006564
Chandler Carruthc22845a2011-07-26 05:40:03 +00006565 // If the conversion context location is invalid don't complain. We also
6566 // don't want to emit a warning if the issue occurs from the expansion of
6567 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6568 // delay this check as long as possible. Once we detect we are in that
6569 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006570 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00006571 return;
6572
Richard Trieu021baa32011-09-23 20:10:00 +00006573 // Diagnose implicit casts to bool.
6574 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6575 if (isa<StringLiteral>(E))
6576 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00006577 // and expressions, for instance, assert(0 && "error here"), are
6578 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00006579 return DiagnoseImpCast(S, E, T, CC,
6580 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00006581 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6582 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6583 // This covers the literal expressions that evaluate to Objective-C
6584 // objects.
6585 return DiagnoseImpCast(S, E, T, CC,
6586 diag::warn_impcast_objective_c_literal_to_bool);
6587 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006588 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6589 // Warn on pointer to bool conversion that is always true.
6590 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6591 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00006592 }
Richard Trieu021baa32011-09-23 20:10:00 +00006593 }
John McCall263a48b2010-01-04 23:31:57 +00006594
6595 // Strip vector types.
6596 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006597 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006598 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006599 return;
John McCallacf0ee52010-10-08 02:01:28 +00006600 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006601 }
Chris Lattneree7286f2011-06-14 04:51:15 +00006602
6603 // If the vector cast is cast between two vectors of the same size, it is
6604 // a bitcast, not a conversion.
6605 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6606 return;
John McCall263a48b2010-01-04 23:31:57 +00006607
6608 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6609 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6610 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00006611 if (auto VecTy = dyn_cast<VectorType>(Target))
6612 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00006613
6614 // Strip complex types.
6615 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006616 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006617 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006618 return;
6619
John McCallacf0ee52010-10-08 02:01:28 +00006620 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006621 }
John McCall263a48b2010-01-04 23:31:57 +00006622
6623 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6624 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6625 }
6626
6627 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6628 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6629
6630 // If the source is floating point...
6631 if (SourceBT && SourceBT->isFloatingPoint()) {
6632 // ...and the target is floating point...
6633 if (TargetBT && TargetBT->isFloatingPoint()) {
6634 // ...then warn if we're dropping FP rank.
6635
6636 // Builtin FP kinds are ordered by increasing FP rank.
6637 if (SourceBT->getKind() > TargetBT->getKind()) {
6638 // Don't warn about float constants that are precisely
6639 // representable in the target type.
6640 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006641 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00006642 // Value might be a float, a float vector, or a float complex.
6643 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00006644 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6645 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00006646 return;
6647 }
6648
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006649 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006650 return;
6651
John McCallacf0ee52010-10-08 02:01:28 +00006652 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00006653 }
6654 return;
6655 }
6656
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006657 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00006658 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006659 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006660 return;
6661
Chandler Carruth22c7a792011-02-17 11:05:49 +00006662 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00006663 // We also want to warn on, e.g., "int i = -1.234"
6664 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6665 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6666 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6667
Chandler Carruth016ef402011-04-10 08:36:24 +00006668 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6669 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00006670 } else {
6671 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6672 }
6673 }
John McCall263a48b2010-01-04 23:31:57 +00006674
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006675 // If the target is bool, warn if expr is a function or method call.
6676 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6677 isa<CallExpr>(E)) {
6678 // Check last argument of function call to see if it is an
6679 // implicit cast from a type matching the type the result
6680 // is being cast to.
6681 CallExpr *CEx = cast<CallExpr>(E);
6682 unsigned NumArgs = CEx->getNumArgs();
6683 if (NumArgs > 0) {
6684 Expr *LastA = CEx->getArg(NumArgs - 1);
6685 Expr *InnerE = LastA->IgnoreParenImpCasts();
6686 const Type *InnerType =
6687 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6688 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6689 // Warn on this floating-point to bool conversion
6690 DiagnoseImpCast(S, E, T, CC,
6691 diag::warn_impcast_floating_point_to_bool);
6692 }
6693 }
6694 }
John McCall263a48b2010-01-04 23:31:57 +00006695 return;
6696 }
6697
Richard Trieu5b993502014-10-15 03:42:06 +00006698 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00006699
David Blaikie9366d2b2012-06-19 21:19:06 +00006700 if (!Source->isIntegerType() || !Target->isIntegerType())
6701 return;
6702
David Blaikie7555b6a2012-05-15 16:56:36 +00006703 // TODO: remove this early return once the false positives for constant->bool
6704 // in templates, macros, etc, are reduced or removed.
6705 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6706 return;
6707
John McCallcc7e5bf2010-05-06 08:58:33 +00006708 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00006709 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00006710
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006711 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00006712 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006713 // TODO: this should happen for bitfield stores, too.
6714 llvm::APSInt Value(32);
6715 if (E->isIntegerConstantExpr(Value, S.Context)) {
6716 if (S.SourceMgr.isInSystemMacro(CC))
6717 return;
6718
John McCall18a2c2c2010-11-09 22:22:12 +00006719 std::string PrettySourceValue = Value.toString(10);
6720 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006721
Ted Kremenek33ba9952011-10-22 02:37:33 +00006722 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6723 S.PDiag(diag::warn_impcast_integer_precision_constant)
6724 << PrettySourceValue << PrettyTargetValue
6725 << E->getType() << T << E->getSourceRange()
6726 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006727 return;
6728 }
6729
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006730 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6731 if (S.SourceMgr.isInSystemMacro(CC))
6732 return;
6733
David Blaikie9455da02012-04-12 22:40:54 +00006734 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006735 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6736 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006737 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006738 }
6739
6740 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6741 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6742 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006743
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006744 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006745 return;
6746
John McCallcc7e5bf2010-05-06 08:58:33 +00006747 unsigned DiagID = diag::warn_impcast_integer_sign;
6748
6749 // Traditionally, gcc has warned about this under -Wsign-compare.
6750 // We also want to warn about it in -Wconversion.
6751 // So if -Wconversion is off, use a completely identical diagnostic
6752 // in the sign-compare group.
6753 // The conditional-checking code will
6754 if (ICContext) {
6755 DiagID = diag::warn_impcast_integer_sign_conditional;
6756 *ICContext = true;
6757 }
6758
John McCallacf0ee52010-10-08 02:01:28 +00006759 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006760 }
6761
Douglas Gregora78f1932011-02-22 02:45:07 +00006762 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006763 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6764 // type, to give us better diagnostics.
6765 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006766 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006767 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6768 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6769 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6770 SourceType = S.Context.getTypeDeclType(Enum);
6771 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6772 }
6773 }
6774
Douglas Gregora78f1932011-02-22 02:45:07 +00006775 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6776 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006777 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6778 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006779 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006780 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006781 return;
6782
Douglas Gregor364f7db2011-03-12 00:14:31 +00006783 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006784 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006785 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006786
John McCall263a48b2010-01-04 23:31:57 +00006787 return;
6788}
6789
David Blaikie18e9ac72012-05-15 21:57:38 +00006790void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6791 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006792
6793void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006794 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006795 E = E->IgnoreParenImpCasts();
6796
6797 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006798 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006799
John McCallacf0ee52010-10-08 02:01:28 +00006800 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006801 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006802 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006803 return;
6804}
6805
David Blaikie18e9ac72012-05-15 21:57:38 +00006806void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6807 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00006808 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006809
6810 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006811 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6812 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006813
6814 // If -Wconversion would have warned about either of the candidates
6815 // for a signedness conversion to the context type...
6816 if (!Suspicious) return;
6817
6818 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006819 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006820 return;
6821
John McCallcc7e5bf2010-05-06 08:58:33 +00006822 // ...then check whether it would have warned about either of the
6823 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006824 if (E->getType() == T) return;
6825
6826 Suspicious = false;
6827 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6828 E->getType(), CC, &Suspicious);
6829 if (!Suspicious)
6830 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006831 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006832}
6833
Richard Trieu65724892014-11-15 06:37:39 +00006834/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6835/// Input argument E is a logical expression.
6836static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
6837 if (S.getLangOpts().Bool)
6838 return;
6839 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
6840}
6841
John McCallcc7e5bf2010-05-06 08:58:33 +00006842/// AnalyzeImplicitConversions - Find and report any interesting
6843/// implicit conversions in the given expression. There are a couple
6844/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006845void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006846 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006847 Expr *E = OrigE->IgnoreParenImpCasts();
6848
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006849 if (E->isTypeDependent() || E->isValueDependent())
6850 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006851
John McCallcc7e5bf2010-05-06 08:58:33 +00006852 // For conditional operators, we analyze the arguments as if they
6853 // were being fed directly into the output.
6854 if (isa<ConditionalOperator>(E)) {
6855 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006856 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006857 return;
6858 }
6859
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006860 // Check implicit argument conversions for function calls.
6861 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6862 CheckImplicitArgumentConversions(S, Call, CC);
6863
John McCallcc7e5bf2010-05-06 08:58:33 +00006864 // Go ahead and check any implicit conversions we might have skipped.
6865 // The non-canonical typecheck is just an optimization;
6866 // CheckImplicitConversion will filter out dead implicit conversions.
6867 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006868 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006869
6870 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006871
6872 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006873 if (POE->getResultExpr())
6874 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006875 }
6876
Fariborz Jahanian947efbc2015-02-26 17:59:54 +00006877 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
6878 if (OVE->getSourceExpr())
6879 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6880 return;
6881 }
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006882
John McCallcc7e5bf2010-05-06 08:58:33 +00006883 // Skip past explicit casts.
6884 if (isa<ExplicitCastExpr>(E)) {
6885 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006886 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006887 }
6888
John McCalld2a53122010-11-09 23:24:47 +00006889 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6890 // Do a somewhat different check with comparison operators.
6891 if (BO->isComparisonOp())
6892 return AnalyzeComparison(S, BO);
6893
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006894 // And with simple assignments.
6895 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006896 return AnalyzeAssignment(S, BO);
6897 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006898
6899 // These break the otherwise-useful invariant below. Fortunately,
6900 // we don't really need to recurse into them, because any internal
6901 // expressions should have been analyzed already when they were
6902 // built into statements.
6903 if (isa<StmtExpr>(E)) return;
6904
6905 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006906 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006907
6908 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006909 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006910 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006911 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006912 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006913 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006914 if (!ChildExpr)
6915 continue;
6916
Richard Trieu955231d2014-01-25 01:10:35 +00006917 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006918 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006919 // Ignore checking string literals that are in logical and operators.
6920 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006921 continue;
6922 AnalyzeImplicitConversions(S, ChildExpr, CC);
6923 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006924
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006925 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00006926 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
6927 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006928 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00006929
6930 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
6931 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006932 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006933 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006934
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006935 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
6936 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00006937 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006938}
6939
6940} // end anonymous namespace
6941
Richard Trieu3bb8b562014-02-26 02:36:06 +00006942enum {
6943 AddressOf,
6944 FunctionPointer,
6945 ArrayPointer
6946};
6947
Richard Trieuc1888e02014-06-28 23:25:37 +00006948// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6949// Returns true when emitting a warning about taking the address of a reference.
6950static bool CheckForReference(Sema &SemaRef, const Expr *E,
6951 PartialDiagnostic PD) {
6952 E = E->IgnoreParenImpCasts();
6953
6954 const FunctionDecl *FD = nullptr;
6955
6956 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6957 if (!DRE->getDecl()->getType()->isReferenceType())
6958 return false;
6959 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6960 if (!M->getMemberDecl()->getType()->isReferenceType())
6961 return false;
6962 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00006963 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00006964 return false;
6965 FD = Call->getDirectCallee();
6966 } else {
6967 return false;
6968 }
6969
6970 SemaRef.Diag(E->getExprLoc(), PD);
6971
6972 // If possible, point to location of function.
6973 if (FD) {
6974 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6975 }
6976
6977 return true;
6978}
6979
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006980// Returns true if the SourceLocation is expanded from any macro body.
6981// Returns false if the SourceLocation is invalid, is from not in a macro
6982// expansion, or is from expanded from a top-level macro argument.
6983static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
6984 if (Loc.isInvalid())
6985 return false;
6986
6987 while (Loc.isMacroID()) {
6988 if (SM.isMacroBodyExpansion(Loc))
6989 return true;
6990 Loc = SM.getImmediateMacroCallerLoc(Loc);
6991 }
6992
6993 return false;
6994}
6995
Richard Trieu3bb8b562014-02-26 02:36:06 +00006996/// \brief Diagnose pointers that are always non-null.
6997/// \param E the expression containing the pointer
6998/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6999/// compared to a null pointer
7000/// \param IsEqual True when the comparison is equal to a null pointer
7001/// \param Range Extra SourceRange to highlight in the diagnostic
7002void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
7003 Expr::NullPointerConstantKind NullKind,
7004 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00007005 if (!E)
7006 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007007
7008 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007009 if (E->getExprLoc().isMacroID()) {
7010 const SourceManager &SM = getSourceManager();
7011 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
7012 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00007013 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007014 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007015 E = E->IgnoreImpCasts();
7016
7017 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
7018
Richard Trieuf7432752014-06-06 21:39:26 +00007019 if (isa<CXXThisExpr>(E)) {
7020 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
7021 : diag::warn_this_bool_conversion;
7022 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
7023 return;
7024 }
7025
Richard Trieu3bb8b562014-02-26 02:36:06 +00007026 bool IsAddressOf = false;
7027
7028 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7029 if (UO->getOpcode() != UO_AddrOf)
7030 return;
7031 IsAddressOf = true;
7032 E = UO->getSubExpr();
7033 }
7034
Richard Trieuc1888e02014-06-28 23:25:37 +00007035 if (IsAddressOf) {
7036 unsigned DiagID = IsCompare
7037 ? diag::warn_address_of_reference_null_compare
7038 : diag::warn_address_of_reference_bool_conversion;
7039 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
7040 << IsEqual;
7041 if (CheckForReference(*this, E, PD)) {
7042 return;
7043 }
7044 }
7045
Richard Trieu3bb8b562014-02-26 02:36:06 +00007046 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00007047 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007048 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
7049 D = R->getDecl();
7050 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7051 D = M->getMemberDecl();
7052 }
7053
7054 // Weak Decls can be null.
7055 if (!D || D->isWeak())
7056 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007057
7058 // Check for parameter decl with nonnull attribute
7059 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
7060 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
7061 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
7062 unsigned NumArgs = FD->getNumParams();
7063 llvm::SmallBitVector AttrNonNull(NumArgs);
7064 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
7065 if (!NonNull->args_size()) {
7066 AttrNonNull.set(0, NumArgs);
7067 break;
7068 }
7069 for (unsigned Val : NonNull->args()) {
7070 if (Val >= NumArgs)
7071 continue;
7072 AttrNonNull.set(Val);
7073 }
7074 }
7075 if (!AttrNonNull.empty())
7076 for (unsigned i = 0; i < NumArgs; ++i)
Aaron Ballman2521f362014-12-11 19:35:42 +00007077 if (FD->getParamDecl(i) == PV &&
7078 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007079 std::string Str;
7080 llvm::raw_string_ostream S(Str);
7081 E->printPretty(S, nullptr, getPrintingPolicy());
7082 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
7083 : diag::warn_cast_nonnull_to_bool;
7084 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
7085 << Range << IsEqual;
7086 return;
7087 }
7088 }
7089 }
7090
Richard Trieu3bb8b562014-02-26 02:36:06 +00007091 QualType T = D->getType();
7092 const bool IsArray = T->isArrayType();
7093 const bool IsFunction = T->isFunctionType();
7094
Richard Trieuc1888e02014-06-28 23:25:37 +00007095 // Address of function is used to silence the function warning.
7096 if (IsAddressOf && IsFunction) {
7097 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007098 }
7099
7100 // Found nothing.
7101 if (!IsAddressOf && !IsFunction && !IsArray)
7102 return;
7103
7104 // Pretty print the expression for the diagnostic.
7105 std::string Str;
7106 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00007107 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00007108
7109 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7110 : diag::warn_impcast_pointer_to_bool;
7111 unsigned DiagType;
7112 if (IsAddressOf)
7113 DiagType = AddressOf;
7114 else if (IsFunction)
7115 DiagType = FunctionPointer;
7116 else if (IsArray)
7117 DiagType = ArrayPointer;
7118 else
7119 llvm_unreachable("Could not determine diagnostic.");
7120 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7121 << Range << IsEqual;
7122
7123 if (!IsFunction)
7124 return;
7125
7126 // Suggest '&' to silence the function warning.
7127 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7128 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7129
7130 // Check to see if '()' fixit should be emitted.
7131 QualType ReturnType;
7132 UnresolvedSet<4> NonTemplateOverloads;
7133 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7134 if (ReturnType.isNull())
7135 return;
7136
7137 if (IsCompare) {
7138 // There are two cases here. If there is null constant, the only suggest
7139 // for a pointer return type. If the null is 0, then suggest if the return
7140 // type is a pointer or an integer type.
7141 if (!ReturnType->isPointerType()) {
7142 if (NullKind == Expr::NPCK_ZeroExpression ||
7143 NullKind == Expr::NPCK_ZeroLiteral) {
7144 if (!ReturnType->isIntegerType())
7145 return;
7146 } else {
7147 return;
7148 }
7149 }
7150 } else { // !IsCompare
7151 // For function to bool, only suggest if the function pointer has bool
7152 // return type.
7153 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7154 return;
7155 }
7156 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007157 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00007158}
7159
7160
John McCallcc7e5bf2010-05-06 08:58:33 +00007161/// Diagnoses "dangerous" implicit conversions within the given
7162/// expression (which is a full expression). Implements -Wconversion
7163/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007164///
7165/// \param CC the "context" location of the implicit conversion, i.e.
7166/// the most location of the syntactic entity requiring the implicit
7167/// conversion
7168void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007169 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00007170 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00007171 return;
7172
7173 // Don't diagnose for value- or type-dependent expressions.
7174 if (E->isTypeDependent() || E->isValueDependent())
7175 return;
7176
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007177 // Check for array bounds violations in cases where the check isn't triggered
7178 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7179 // ArraySubscriptExpr is on the RHS of a variable initialization.
7180 CheckArrayAccess(E);
7181
John McCallacf0ee52010-10-08 02:01:28 +00007182 // This is not the right CC for (e.g.) a variable initialization.
7183 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007184}
7185
Richard Trieu65724892014-11-15 06:37:39 +00007186/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7187/// Input argument E is a logical expression.
7188void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7189 ::CheckBoolLikeConversion(*this, E, CC);
7190}
7191
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007192/// Diagnose when expression is an integer constant expression and its evaluation
7193/// results in integer overflow
7194void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00007195 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7196 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007197}
7198
Richard Smithc406cb72013-01-17 01:17:56 +00007199namespace {
7200/// \brief Visitor for expressions which looks for unsequenced operations on the
7201/// same object.
7202class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007203 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7204
Richard Smithc406cb72013-01-17 01:17:56 +00007205 /// \brief A tree of sequenced regions within an expression. Two regions are
7206 /// unsequenced if one is an ancestor or a descendent of the other. When we
7207 /// finish processing an expression with sequencing, such as a comma
7208 /// expression, we fold its tree nodes into its parent, since they are
7209 /// unsequenced with respect to nodes we will visit later.
7210 class SequenceTree {
7211 struct Value {
7212 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7213 unsigned Parent : 31;
7214 bool Merged : 1;
7215 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007216 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00007217
7218 public:
7219 /// \brief A region within an expression which may be sequenced with respect
7220 /// to some other region.
7221 class Seq {
7222 explicit Seq(unsigned N) : Index(N) {}
7223 unsigned Index;
7224 friend class SequenceTree;
7225 public:
7226 Seq() : Index(0) {}
7227 };
7228
7229 SequenceTree() { Values.push_back(Value(0)); }
7230 Seq root() const { return Seq(0); }
7231
7232 /// \brief Create a new sequence of operations, which is an unsequenced
7233 /// subset of \p Parent. This sequence of operations is sequenced with
7234 /// respect to other children of \p Parent.
7235 Seq allocate(Seq Parent) {
7236 Values.push_back(Value(Parent.Index));
7237 return Seq(Values.size() - 1);
7238 }
7239
7240 /// \brief Merge a sequence of operations into its parent.
7241 void merge(Seq S) {
7242 Values[S.Index].Merged = true;
7243 }
7244
7245 /// \brief Determine whether two operations are unsequenced. This operation
7246 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7247 /// should have been merged into its parent as appropriate.
7248 bool isUnsequenced(Seq Cur, Seq Old) {
7249 unsigned C = representative(Cur.Index);
7250 unsigned Target = representative(Old.Index);
7251 while (C >= Target) {
7252 if (C == Target)
7253 return true;
7254 C = Values[C].Parent;
7255 }
7256 return false;
7257 }
7258
7259 private:
7260 /// \brief Pick a representative for a sequence.
7261 unsigned representative(unsigned K) {
7262 if (Values[K].Merged)
7263 // Perform path compression as we go.
7264 return Values[K].Parent = representative(Values[K].Parent);
7265 return K;
7266 }
7267 };
7268
7269 /// An object for which we can track unsequenced uses.
7270 typedef NamedDecl *Object;
7271
7272 /// Different flavors of object usage which we track. We only track the
7273 /// least-sequenced usage of each kind.
7274 enum UsageKind {
7275 /// A read of an object. Multiple unsequenced reads are OK.
7276 UK_Use,
7277 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00007278 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00007279 UK_ModAsValue,
7280 /// A modification of an object which is not sequenced before the value
7281 /// computation of the expression, such as n++.
7282 UK_ModAsSideEffect,
7283
7284 UK_Count = UK_ModAsSideEffect + 1
7285 };
7286
7287 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00007288 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00007289 Expr *Use;
7290 SequenceTree::Seq Seq;
7291 };
7292
7293 struct UsageInfo {
7294 UsageInfo() : Diagnosed(false) {}
7295 Usage Uses[UK_Count];
7296 /// Have we issued a diagnostic for this variable already?
7297 bool Diagnosed;
7298 };
7299 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7300
7301 Sema &SemaRef;
7302 /// Sequenced regions within the expression.
7303 SequenceTree Tree;
7304 /// Declaration modifications and references which we have seen.
7305 UsageInfoMap UsageMap;
7306 /// The region we are currently within.
7307 SequenceTree::Seq Region;
7308 /// Filled in with declarations which were modified as a side-effect
7309 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007310 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00007311 /// Expressions to check later. We defer checking these to reduce
7312 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007313 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00007314
7315 /// RAII object wrapping the visitation of a sequenced subexpression of an
7316 /// expression. At the end of this process, the side-effects of the evaluation
7317 /// become sequenced with respect to the value computation of the result, so
7318 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7319 /// UK_ModAsValue.
7320 struct SequencedSubexpression {
7321 SequencedSubexpression(SequenceChecker &Self)
7322 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7323 Self.ModAsSideEffect = &ModAsSideEffect;
7324 }
7325 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00007326 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7327 MI != ME; ++MI) {
7328 UsageInfo &U = Self.UsageMap[MI->first];
7329 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7330 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7331 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00007332 }
7333 Self.ModAsSideEffect = OldModAsSideEffect;
7334 }
7335
7336 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007337 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7338 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00007339 };
7340
Richard Smith40238f02013-06-20 22:21:56 +00007341 /// RAII object wrapping the visitation of a subexpression which we might
7342 /// choose to evaluate as a constant. If any subexpression is evaluated and
7343 /// found to be non-constant, this allows us to suppress the evaluation of
7344 /// the outer expression.
7345 class EvaluationTracker {
7346 public:
7347 EvaluationTracker(SequenceChecker &Self)
7348 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7349 Self.EvalTracker = this;
7350 }
7351 ~EvaluationTracker() {
7352 Self.EvalTracker = Prev;
7353 if (Prev)
7354 Prev->EvalOK &= EvalOK;
7355 }
7356
7357 bool evaluate(const Expr *E, bool &Result) {
7358 if (!EvalOK || E->isValueDependent())
7359 return false;
7360 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7361 return EvalOK;
7362 }
7363
7364 private:
7365 SequenceChecker &Self;
7366 EvaluationTracker *Prev;
7367 bool EvalOK;
7368 } *EvalTracker;
7369
Richard Smithc406cb72013-01-17 01:17:56 +00007370 /// \brief Find the object which is produced by the specified expression,
7371 /// if any.
7372 Object getObject(Expr *E, bool Mod) const {
7373 E = E->IgnoreParenCasts();
7374 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7375 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7376 return getObject(UO->getSubExpr(), Mod);
7377 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7378 if (BO->getOpcode() == BO_Comma)
7379 return getObject(BO->getRHS(), Mod);
7380 if (Mod && BO->isAssignmentOp())
7381 return getObject(BO->getLHS(), Mod);
7382 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7383 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7384 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7385 return ME->getMemberDecl();
7386 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7387 // FIXME: If this is a reference, map through to its value.
7388 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00007389 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00007390 }
7391
7392 /// \brief Note that an object was modified or used by an expression.
7393 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7394 Usage &U = UI.Uses[UK];
7395 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7396 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7397 ModAsSideEffect->push_back(std::make_pair(O, U));
7398 U.Use = Ref;
7399 U.Seq = Region;
7400 }
7401 }
7402 /// \brief Check whether a modification or use conflicts with a prior usage.
7403 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7404 bool IsModMod) {
7405 if (UI.Diagnosed)
7406 return;
7407
7408 const Usage &U = UI.Uses[OtherKind];
7409 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7410 return;
7411
7412 Expr *Mod = U.Use;
7413 Expr *ModOrUse = Ref;
7414 if (OtherKind == UK_Use)
7415 std::swap(Mod, ModOrUse);
7416
7417 SemaRef.Diag(Mod->getExprLoc(),
7418 IsModMod ? diag::warn_unsequenced_mod_mod
7419 : diag::warn_unsequenced_mod_use)
7420 << O << SourceRange(ModOrUse->getExprLoc());
7421 UI.Diagnosed = true;
7422 }
7423
7424 void notePreUse(Object O, Expr *Use) {
7425 UsageInfo &U = UsageMap[O];
7426 // Uses conflict with other modifications.
7427 checkUsage(O, U, Use, UK_ModAsValue, false);
7428 }
7429 void notePostUse(Object O, Expr *Use) {
7430 UsageInfo &U = UsageMap[O];
7431 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7432 addUsage(U, O, Use, UK_Use);
7433 }
7434
7435 void notePreMod(Object O, Expr *Mod) {
7436 UsageInfo &U = UsageMap[O];
7437 // Modifications conflict with other modifications and with uses.
7438 checkUsage(O, U, Mod, UK_ModAsValue, true);
7439 checkUsage(O, U, Mod, UK_Use, false);
7440 }
7441 void notePostMod(Object O, Expr *Use, UsageKind UK) {
7442 UsageInfo &U = UsageMap[O];
7443 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7444 addUsage(U, O, Use, UK);
7445 }
7446
7447public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007448 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00007449 : Base(S.Context), SemaRef(S), Region(Tree.root()),
7450 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007451 Visit(E);
7452 }
7453
7454 void VisitStmt(Stmt *S) {
7455 // Skip all statements which aren't expressions for now.
7456 }
7457
7458 void VisitExpr(Expr *E) {
7459 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00007460 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007461 }
7462
7463 void VisitCastExpr(CastExpr *E) {
7464 Object O = Object();
7465 if (E->getCastKind() == CK_LValueToRValue)
7466 O = getObject(E->getSubExpr(), false);
7467
7468 if (O)
7469 notePreUse(O, E);
7470 VisitExpr(E);
7471 if (O)
7472 notePostUse(O, E);
7473 }
7474
7475 void VisitBinComma(BinaryOperator *BO) {
7476 // C++11 [expr.comma]p1:
7477 // Every value computation and side effect associated with the left
7478 // expression is sequenced before every value computation and side
7479 // effect associated with the right expression.
7480 SequenceTree::Seq LHS = Tree.allocate(Region);
7481 SequenceTree::Seq RHS = Tree.allocate(Region);
7482 SequenceTree::Seq OldRegion = Region;
7483
7484 {
7485 SequencedSubexpression SeqLHS(*this);
7486 Region = LHS;
7487 Visit(BO->getLHS());
7488 }
7489
7490 Region = RHS;
7491 Visit(BO->getRHS());
7492
7493 Region = OldRegion;
7494
7495 // Forget that LHS and RHS are sequenced. They are both unsequenced
7496 // with respect to other stuff.
7497 Tree.merge(LHS);
7498 Tree.merge(RHS);
7499 }
7500
7501 void VisitBinAssign(BinaryOperator *BO) {
7502 // The modification is sequenced after the value computation of the LHS
7503 // and RHS, so check it before inspecting the operands and update the
7504 // map afterwards.
7505 Object O = getObject(BO->getLHS(), true);
7506 if (!O)
7507 return VisitExpr(BO);
7508
7509 notePreMod(O, BO);
7510
7511 // C++11 [expr.ass]p7:
7512 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7513 // only once.
7514 //
7515 // Therefore, for a compound assignment operator, O is considered used
7516 // everywhere except within the evaluation of E1 itself.
7517 if (isa<CompoundAssignOperator>(BO))
7518 notePreUse(O, BO);
7519
7520 Visit(BO->getLHS());
7521
7522 if (isa<CompoundAssignOperator>(BO))
7523 notePostUse(O, BO);
7524
7525 Visit(BO->getRHS());
7526
Richard Smith83e37bee2013-06-26 23:16:51 +00007527 // C++11 [expr.ass]p1:
7528 // the assignment is sequenced [...] before the value computation of the
7529 // assignment expression.
7530 // C11 6.5.16/3 has no such rule.
7531 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7532 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007533 }
7534 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7535 VisitBinAssign(CAO);
7536 }
7537
7538 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7539 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7540 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7541 Object O = getObject(UO->getSubExpr(), true);
7542 if (!O)
7543 return VisitExpr(UO);
7544
7545 notePreMod(O, UO);
7546 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00007547 // C++11 [expr.pre.incr]p1:
7548 // the expression ++x is equivalent to x+=1
7549 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7550 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007551 }
7552
7553 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7554 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7555 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7556 Object O = getObject(UO->getSubExpr(), true);
7557 if (!O)
7558 return VisitExpr(UO);
7559
7560 notePreMod(O, UO);
7561 Visit(UO->getSubExpr());
7562 notePostMod(O, UO, UK_ModAsSideEffect);
7563 }
7564
7565 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7566 void VisitBinLOr(BinaryOperator *BO) {
7567 // The side-effects of the LHS of an '&&' are sequenced before the
7568 // value computation of the RHS, and hence before the value computation
7569 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7570 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00007571 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007572 {
7573 SequencedSubexpression Sequenced(*this);
7574 Visit(BO->getLHS());
7575 }
7576
7577 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007578 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007579 if (!Result)
7580 Visit(BO->getRHS());
7581 } else {
7582 // Check for unsequenced operations in the RHS, treating it as an
7583 // entirely separate evaluation.
7584 //
7585 // FIXME: If there are operations in the RHS which are unsequenced
7586 // with respect to operations outside the RHS, and those operations
7587 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00007588 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007589 }
Richard Smithc406cb72013-01-17 01:17:56 +00007590 }
7591 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00007592 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007593 {
7594 SequencedSubexpression Sequenced(*this);
7595 Visit(BO->getLHS());
7596 }
7597
7598 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007599 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007600 if (Result)
7601 Visit(BO->getRHS());
7602 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00007603 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007604 }
Richard Smithc406cb72013-01-17 01:17:56 +00007605 }
7606
7607 // Only visit the condition, unless we can be sure which subexpression will
7608 // be chosen.
7609 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00007610 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00007611 {
7612 SequencedSubexpression Sequenced(*this);
7613 Visit(CO->getCond());
7614 }
Richard Smithc406cb72013-01-17 01:17:56 +00007615
7616 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007617 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00007618 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007619 else {
Richard Smithd33f5202013-01-17 23:18:09 +00007620 WorkList.push_back(CO->getTrueExpr());
7621 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007622 }
Richard Smithc406cb72013-01-17 01:17:56 +00007623 }
7624
Richard Smithe3dbfe02013-06-30 10:40:20 +00007625 void VisitCallExpr(CallExpr *CE) {
7626 // C++11 [intro.execution]p15:
7627 // When calling a function [...], every value computation and side effect
7628 // associated with any argument expression, or with the postfix expression
7629 // designating the called function, is sequenced before execution of every
7630 // expression or statement in the body of the function [and thus before
7631 // the value computation of its result].
7632 SequencedSubexpression Sequenced(*this);
7633 Base::VisitCallExpr(CE);
7634
7635 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7636 }
7637
Richard Smithc406cb72013-01-17 01:17:56 +00007638 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007639 // This is a call, so all subexpressions are sequenced before the result.
7640 SequencedSubexpression Sequenced(*this);
7641
Richard Smithc406cb72013-01-17 01:17:56 +00007642 if (!CCE->isListInitialization())
7643 return VisitExpr(CCE);
7644
7645 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007646 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007647 SequenceTree::Seq Parent = Region;
7648 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7649 E = CCE->arg_end();
7650 I != E; ++I) {
7651 Region = Tree.allocate(Parent);
7652 Elts.push_back(Region);
7653 Visit(*I);
7654 }
7655
7656 // Forget that the initializers are sequenced.
7657 Region = Parent;
7658 for (unsigned I = 0; I < Elts.size(); ++I)
7659 Tree.merge(Elts[I]);
7660 }
7661
7662 void VisitInitListExpr(InitListExpr *ILE) {
7663 if (!SemaRef.getLangOpts().CPlusPlus11)
7664 return VisitExpr(ILE);
7665
7666 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007667 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007668 SequenceTree::Seq Parent = Region;
7669 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7670 Expr *E = ILE->getInit(I);
7671 if (!E) continue;
7672 Region = Tree.allocate(Parent);
7673 Elts.push_back(Region);
7674 Visit(E);
7675 }
7676
7677 // Forget that the initializers are sequenced.
7678 Region = Parent;
7679 for (unsigned I = 0; I < Elts.size(); ++I)
7680 Tree.merge(Elts[I]);
7681 }
7682};
7683}
7684
7685void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007686 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00007687 WorkList.push_back(E);
7688 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00007689 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00007690 SequenceChecker(*this, Item, WorkList);
7691 }
Richard Smithc406cb72013-01-17 01:17:56 +00007692}
7693
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007694void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7695 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007696 CheckImplicitConversions(E, CheckLoc);
7697 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007698 if (!IsConstexpr && !E->isValueDependent())
7699 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007700}
7701
John McCall1f425642010-11-11 03:21:53 +00007702void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7703 FieldDecl *BitField,
7704 Expr *Init) {
7705 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7706}
7707
David Majnemer61a5bbf2015-04-07 22:08:51 +00007708static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
7709 SourceLocation Loc) {
7710 if (!PType->isVariablyModifiedType())
7711 return;
7712 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
7713 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
7714 return;
7715 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00007716 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
7717 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
7718 return;
7719 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00007720 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
7721 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
7722 return;
7723 }
7724
7725 const ArrayType *AT = S.Context.getAsArrayType(PType);
7726 if (!AT)
7727 return;
7728
7729 if (AT->getSizeModifier() != ArrayType::Star) {
7730 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
7731 return;
7732 }
7733
7734 S.Diag(Loc, diag::err_array_star_in_function_definition);
7735}
7736
Mike Stump0c2ec772010-01-21 03:59:47 +00007737/// CheckParmsForFunctionDef - Check that the parameters of the given
7738/// function are appropriate for the definition of a function. This
7739/// takes care of any checks that cannot be performed on the
7740/// declaration itself, e.g., that the types of each of the function
7741/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00007742bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7743 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00007744 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007745 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00007746 for (; P != PEnd; ++P) {
7747 ParmVarDecl *Param = *P;
7748
Mike Stump0c2ec772010-01-21 03:59:47 +00007749 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7750 // function declarator that is part of a function definition of
7751 // that function shall not have incomplete type.
7752 //
7753 // This is also C++ [dcl.fct]p6.
7754 if (!Param->isInvalidDecl() &&
7755 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007756 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007757 Param->setInvalidDecl();
7758 HasInvalidParm = true;
7759 }
7760
7761 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7762 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00007763 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00007764 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00007765 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007766 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00007767 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00007768
7769 // C99 6.7.5.3p12:
7770 // If the function declarator is not part of a definition of that
7771 // function, parameters may have incomplete type and may use the [*]
7772 // notation in their sequences of declarator specifiers to specify
7773 // variable length array types.
7774 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00007775 // FIXME: This diagnostic should point the '[*]' if source-location
7776 // information is added for it.
7777 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007778
7779 // MSVC destroys objects passed by value in the callee. Therefore a
7780 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007781 // object's destructor. However, we don't perform any direct access check
7782 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00007783 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7784 .getCXXABI()
7785 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00007786 if (!Param->isInvalidDecl()) {
7787 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7788 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7789 if (!ClassDecl->isInvalidDecl() &&
7790 !ClassDecl->hasIrrelevantDestructor() &&
7791 !ClassDecl->isDependentContext()) {
7792 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7793 MarkFunctionReferenced(Param->getLocation(), Destructor);
7794 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7795 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007796 }
7797 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007798 }
Mike Stump0c2ec772010-01-21 03:59:47 +00007799 }
7800
7801 return HasInvalidParm;
7802}
John McCall2b5c1b22010-08-12 21:44:57 +00007803
7804/// CheckCastAlign - Implements -Wcast-align, which warns when a
7805/// pointer cast increases the alignment requirements.
7806void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7807 // This is actually a lot of work to potentially be doing on every
7808 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007809 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00007810 return;
7811
7812 // Ignore dependent types.
7813 if (T->isDependentType() || Op->getType()->isDependentType())
7814 return;
7815
7816 // Require that the destination be a pointer type.
7817 const PointerType *DestPtr = T->getAs<PointerType>();
7818 if (!DestPtr) return;
7819
7820 // If the destination has alignment 1, we're done.
7821 QualType DestPointee = DestPtr->getPointeeType();
7822 if (DestPointee->isIncompleteType()) return;
7823 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7824 if (DestAlign.isOne()) return;
7825
7826 // Require that the source be a pointer type.
7827 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7828 if (!SrcPtr) return;
7829 QualType SrcPointee = SrcPtr->getPointeeType();
7830
7831 // Whitelist casts from cv void*. We already implicitly
7832 // whitelisted casts to cv void*, since they have alignment 1.
7833 // Also whitelist casts involving incomplete types, which implicitly
7834 // includes 'void'.
7835 if (SrcPointee->isIncompleteType()) return;
7836
7837 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7838 if (SrcAlign >= DestAlign) return;
7839
7840 Diag(TRange.getBegin(), diag::warn_cast_align)
7841 << Op->getType() << T
7842 << static_cast<unsigned>(SrcAlign.getQuantity())
7843 << static_cast<unsigned>(DestAlign.getQuantity())
7844 << TRange << Op->getSourceRange();
7845}
7846
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007847static const Type* getElementType(const Expr *BaseExpr) {
7848 const Type* EltType = BaseExpr->getType().getTypePtr();
7849 if (EltType->isAnyPointerType())
7850 return EltType->getPointeeType().getTypePtr();
7851 else if (EltType->isArrayType())
7852 return EltType->getBaseElementTypeUnsafe();
7853 return EltType;
7854}
7855
Chandler Carruth28389f02011-08-05 09:10:50 +00007856/// \brief Check whether this array fits the idiom of a size-one tail padded
7857/// array member of a struct.
7858///
7859/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7860/// commonly used to emulate flexible arrays in C89 code.
7861static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7862 const NamedDecl *ND) {
7863 if (Size != 1 || !ND) return false;
7864
7865 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7866 if (!FD) return false;
7867
7868 // Don't consider sizes resulting from macro expansions or template argument
7869 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00007870
7871 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007872 while (TInfo) {
7873 TypeLoc TL = TInfo->getTypeLoc();
7874 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007875 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7876 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007877 TInfo = TDL->getTypeSourceInfo();
7878 continue;
7879 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007880 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7881 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007882 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7883 return false;
7884 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007885 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007886 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007887
7888 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007889 if (!RD) return false;
7890 if (RD->isUnion()) return false;
7891 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7892 if (!CRD->isStandardLayout()) return false;
7893 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007894
Benjamin Kramer8c543672011-08-06 03:04:42 +00007895 // See if this is the last field decl in the record.
7896 const Decl *D = FD;
7897 while ((D = D->getNextDeclInContext()))
7898 if (isa<FieldDecl>(D))
7899 return false;
7900 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007901}
7902
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007903void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007904 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007905 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007906 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007907 if (IndexExpr->isValueDependent())
7908 return;
7909
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007910 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007911 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007912 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007913 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007914 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007915 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007916
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007917 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007918 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007919 return;
Richard Smith13f67182011-12-16 19:31:14 +00007920 if (IndexNegated)
7921 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007922
Craig Topperc3ec1492014-05-26 06:22:03 +00007923 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007924 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7925 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007926 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007927 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007928
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007929 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007930 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007931 if (!size.isStrictlyPositive())
7932 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007933
7934 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007935 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007936 // Make sure we're comparing apples to apples when comparing index to size
7937 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7938 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007939 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007940 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007941 if (ptrarith_typesize != array_typesize) {
7942 // There's a cast to a different size type involved
7943 uint64_t ratio = array_typesize / ptrarith_typesize;
7944 // TODO: Be smarter about handling cases where array_typesize is not a
7945 // multiple of ptrarith_typesize
7946 if (ptrarith_typesize * ratio == array_typesize)
7947 size *= llvm::APInt(size.getBitWidth(), ratio);
7948 }
7949 }
7950
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007951 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007952 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007953 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007954 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007955
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007956 // For array subscripting the index must be less than size, but for pointer
7957 // arithmetic also allow the index (offset) to be equal to size since
7958 // computing the next address after the end of the array is legal and
7959 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007960 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007961 return;
7962
7963 // Also don't warn for arrays of size 1 which are members of some
7964 // structure. These are often used to approximate flexible arrays in C89
7965 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007966 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007967 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007968
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007969 // Suppress the warning if the subscript expression (as identified by the
7970 // ']' location) and the index expression are both from macro expansions
7971 // within a system header.
7972 if (ASE) {
7973 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7974 ASE->getRBracketLoc());
7975 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7976 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7977 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007978 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007979 return;
7980 }
7981 }
7982
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007983 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007984 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007985 DiagID = diag::warn_array_index_exceeds_bounds;
7986
7987 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7988 PDiag(DiagID) << index.toString(10, true)
7989 << size.toString(10, true)
7990 << (unsigned)size.getLimitedValue(~0U)
7991 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007992 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007993 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007994 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007995 DiagID = diag::warn_ptr_arith_precedes_bounds;
7996 if (index.isNegative()) index = -index;
7997 }
7998
7999 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8000 PDiag(DiagID) << index.toString(10, true)
8001 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00008002 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00008003
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00008004 if (!ND) {
8005 // Try harder to find a NamedDecl to point at in the note.
8006 while (const ArraySubscriptExpr *ASE =
8007 dyn_cast<ArraySubscriptExpr>(BaseExpr))
8008 BaseExpr = ASE->getBase()->IgnoreParenCasts();
8009 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8010 ND = dyn_cast<NamedDecl>(DRE->getDecl());
8011 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8012 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8013 }
8014
Chandler Carruth1af88f12011-02-17 21:10:52 +00008015 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008016 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
8017 PDiag(diag::note_array_index_out_of_bounds)
8018 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00008019}
8020
Ted Kremenekdf26df72011-03-01 18:41:00 +00008021void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008022 int AllowOnePastEnd = 0;
8023 while (expr) {
8024 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00008025 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008026 case Stmt::ArraySubscriptExprClass: {
8027 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008028 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008029 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00008030 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008031 }
8032 case Stmt::UnaryOperatorClass: {
8033 // Only unwrap the * and & unary operators
8034 const UnaryOperator *UO = cast<UnaryOperator>(expr);
8035 expr = UO->getSubExpr();
8036 switch (UO->getOpcode()) {
8037 case UO_AddrOf:
8038 AllowOnePastEnd++;
8039 break;
8040 case UO_Deref:
8041 AllowOnePastEnd--;
8042 break;
8043 default:
8044 return;
8045 }
8046 break;
8047 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008048 case Stmt::ConditionalOperatorClass: {
8049 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
8050 if (const Expr *lhs = cond->getLHS())
8051 CheckArrayAccess(lhs);
8052 if (const Expr *rhs = cond->getRHS())
8053 CheckArrayAccess(rhs);
8054 return;
8055 }
8056 default:
8057 return;
8058 }
Peter Collingbourne91147592011-04-15 00:35:48 +00008059 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008060}
John McCall31168b02011-06-15 23:02:42 +00008061
8062//===--- CHECK: Objective-C retain cycles ----------------------------------//
8063
8064namespace {
8065 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00008066 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00008067 VarDecl *Variable;
8068 SourceRange Range;
8069 SourceLocation Loc;
8070 bool Indirect;
8071
8072 void setLocsFrom(Expr *e) {
8073 Loc = e->getExprLoc();
8074 Range = e->getSourceRange();
8075 }
8076 };
8077}
8078
8079/// Consider whether capturing the given variable can possibly lead to
8080/// a retain cycle.
8081static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00008082 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00008083 // lifetime. In MRR, it's captured strongly if the variable is
8084 // __block and has an appropriate type.
8085 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8086 return false;
8087
8088 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008089 if (ref)
8090 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00008091 return true;
8092}
8093
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008094static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00008095 while (true) {
8096 e = e->IgnoreParens();
8097 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
8098 switch (cast->getCastKind()) {
8099 case CK_BitCast:
8100 case CK_LValueBitCast:
8101 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00008102 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00008103 e = cast->getSubExpr();
8104 continue;
8105
John McCall31168b02011-06-15 23:02:42 +00008106 default:
8107 return false;
8108 }
8109 }
8110
8111 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
8112 ObjCIvarDecl *ivar = ref->getDecl();
8113 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8114 return false;
8115
8116 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008117 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00008118 return false;
8119
8120 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8121 owner.Indirect = true;
8122 return true;
8123 }
8124
8125 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8126 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8127 if (!var) return false;
8128 return considerVariable(var, ref, owner);
8129 }
8130
John McCall31168b02011-06-15 23:02:42 +00008131 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8132 if (member->isArrow()) return false;
8133
8134 // Don't count this as an indirect ownership.
8135 e = member->getBase();
8136 continue;
8137 }
8138
John McCallfe96e0b2011-11-06 09:01:30 +00008139 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8140 // Only pay attention to pseudo-objects on property references.
8141 ObjCPropertyRefExpr *pre
8142 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8143 ->IgnoreParens());
8144 if (!pre) return false;
8145 if (pre->isImplicitProperty()) return false;
8146 ObjCPropertyDecl *property = pre->getExplicitProperty();
8147 if (!property->isRetaining() &&
8148 !(property->getPropertyIvarDecl() &&
8149 property->getPropertyIvarDecl()->getType()
8150 .getObjCLifetime() == Qualifiers::OCL_Strong))
8151 return false;
8152
8153 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008154 if (pre->isSuperReceiver()) {
8155 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8156 if (!owner.Variable)
8157 return false;
8158 owner.Loc = pre->getLocation();
8159 owner.Range = pre->getSourceRange();
8160 return true;
8161 }
John McCallfe96e0b2011-11-06 09:01:30 +00008162 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8163 ->getSourceExpr());
8164 continue;
8165 }
8166
John McCall31168b02011-06-15 23:02:42 +00008167 // Array ivars?
8168
8169 return false;
8170 }
8171}
8172
8173namespace {
8174 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8175 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8176 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008177 Context(Context), Variable(variable), Capturer(nullptr),
8178 VarWillBeReased(false) {}
8179 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00008180 VarDecl *Variable;
8181 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008182 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00008183
8184 void VisitDeclRefExpr(DeclRefExpr *ref) {
8185 if (ref->getDecl() == Variable && !Capturer)
8186 Capturer = ref;
8187 }
8188
John McCall31168b02011-06-15 23:02:42 +00008189 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8190 if (Capturer) return;
8191 Visit(ref->getBase());
8192 if (Capturer && ref->isFreeIvar())
8193 Capturer = ref;
8194 }
8195
8196 void VisitBlockExpr(BlockExpr *block) {
8197 // Look inside nested blocks
8198 if (block->getBlockDecl()->capturesVariable(Variable))
8199 Visit(block->getBlockDecl()->getBody());
8200 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00008201
8202 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8203 if (Capturer) return;
8204 if (OVE->getSourceExpr())
8205 Visit(OVE->getSourceExpr());
8206 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008207 void VisitBinaryOperator(BinaryOperator *BinOp) {
8208 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8209 return;
8210 Expr *LHS = BinOp->getLHS();
8211 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8212 if (DRE->getDecl() != Variable)
8213 return;
8214 if (Expr *RHS = BinOp->getRHS()) {
8215 RHS = RHS->IgnoreParenCasts();
8216 llvm::APSInt Value;
8217 VarWillBeReased =
8218 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8219 }
8220 }
8221 }
John McCall31168b02011-06-15 23:02:42 +00008222 };
8223}
8224
8225/// Check whether the given argument is a block which captures a
8226/// variable.
8227static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8228 assert(owner.Variable && owner.Loc.isValid());
8229
8230 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00008231
8232 // Look through [^{...} copy] and Block_copy(^{...}).
8233 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8234 Selector Cmd = ME->getSelector();
8235 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8236 e = ME->getInstanceReceiver();
8237 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00008238 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00008239 e = e->IgnoreParenCasts();
8240 }
8241 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8242 if (CE->getNumArgs() == 1) {
8243 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00008244 if (Fn) {
8245 const IdentifierInfo *FnI = Fn->getIdentifier();
8246 if (FnI && FnI->isStr("_Block_copy")) {
8247 e = CE->getArg(0)->IgnoreParenCasts();
8248 }
8249 }
Jordan Rose67e887c2012-09-17 17:54:30 +00008250 }
8251 }
8252
John McCall31168b02011-06-15 23:02:42 +00008253 BlockExpr *block = dyn_cast<BlockExpr>(e);
8254 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00008255 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00008256
8257 FindCaptureVisitor visitor(S.Context, owner.Variable);
8258 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008259 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00008260}
8261
8262static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8263 RetainCycleOwner &owner) {
8264 assert(capturer);
8265 assert(owner.Variable && owner.Loc.isValid());
8266
8267 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8268 << owner.Variable << capturer->getSourceRange();
8269 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8270 << owner.Indirect << owner.Range;
8271}
8272
8273/// Check for a keyword selector that starts with the word 'add' or
8274/// 'set'.
8275static bool isSetterLikeSelector(Selector sel) {
8276 if (sel.isUnarySelector()) return false;
8277
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008278 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00008279 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008280 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00008281 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008282 else if (str.startswith("add")) {
8283 // Specially whitelist 'addOperationWithBlock:'.
8284 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8285 return false;
8286 str = str.substr(3);
8287 }
John McCall31168b02011-06-15 23:02:42 +00008288 else
8289 return false;
8290
8291 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00008292 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00008293}
8294
Benjamin Kramer3a743452015-03-09 15:03:32 +00008295static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
8296 ObjCMessageExpr *Message) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008297 if (S.NSMutableArrayPointer.isNull()) {
8298 IdentifierInfo *NSMutableArrayId =
8299 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableArray);
8300 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableArrayId,
8301 Message->getLocStart(),
8302 Sema::LookupOrdinaryName);
8303 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8304 if (!InterfaceDecl) {
8305 return None;
8306 }
8307 QualType NSMutableArrayObject =
8308 S.Context.getObjCInterfaceType(InterfaceDecl);
8309 S.NSMutableArrayPointer =
8310 S.Context.getObjCObjectPointerType(NSMutableArrayObject);
8311 }
8312
8313 if (S.NSMutableArrayPointer != Message->getReceiverType()) {
8314 return None;
8315 }
8316
8317 Selector Sel = Message->getSelector();
8318
8319 Optional<NSAPI::NSArrayMethodKind> MKOpt =
8320 S.NSAPIObj->getNSArrayMethodKind(Sel);
8321 if (!MKOpt) {
8322 return None;
8323 }
8324
8325 NSAPI::NSArrayMethodKind MK = *MKOpt;
8326
8327 switch (MK) {
8328 case NSAPI::NSMutableArr_addObject:
8329 case NSAPI::NSMutableArr_insertObjectAtIndex:
8330 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
8331 return 0;
8332 case NSAPI::NSMutableArr_replaceObjectAtIndex:
8333 return 1;
8334
8335 default:
8336 return None;
8337 }
8338
8339 return None;
8340}
8341
8342static
8343Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
8344 ObjCMessageExpr *Message) {
8345
8346 if (S.NSMutableDictionaryPointer.isNull()) {
8347 IdentifierInfo *NSMutableDictionaryId =
8348 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableDictionary);
8349 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableDictionaryId,
8350 Message->getLocStart(),
8351 Sema::LookupOrdinaryName);
8352 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8353 if (!InterfaceDecl) {
8354 return None;
8355 }
8356 QualType NSMutableDictionaryObject =
8357 S.Context.getObjCInterfaceType(InterfaceDecl);
8358 S.NSMutableDictionaryPointer =
8359 S.Context.getObjCObjectPointerType(NSMutableDictionaryObject);
8360 }
8361
8362 if (S.NSMutableDictionaryPointer != Message->getReceiverType()) {
8363 return None;
8364 }
8365
8366 Selector Sel = Message->getSelector();
8367
8368 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
8369 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
8370 if (!MKOpt) {
8371 return None;
8372 }
8373
8374 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
8375
8376 switch (MK) {
8377 case NSAPI::NSMutableDict_setObjectForKey:
8378 case NSAPI::NSMutableDict_setValueForKey:
8379 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
8380 return 0;
8381
8382 default:
8383 return None;
8384 }
8385
8386 return None;
8387}
8388
8389static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
8390
8391 ObjCInterfaceDecl *InterfaceDecl;
8392 if (S.NSMutableSetPointer.isNull()) {
8393 IdentifierInfo *NSMutableSetId =
8394 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableSet);
8395 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableSetId,
8396 Message->getLocStart(),
8397 Sema::LookupOrdinaryName);
8398 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8399 if (InterfaceDecl) {
8400 QualType NSMutableSetObject =
8401 S.Context.getObjCInterfaceType(InterfaceDecl);
8402 S.NSMutableSetPointer =
8403 S.Context.getObjCObjectPointerType(NSMutableSetObject);
8404 }
8405 }
8406
8407 if (S.NSCountedSetPointer.isNull()) {
8408 IdentifierInfo *NSCountedSetId =
8409 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSCountedSet);
8410 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSCountedSetId,
8411 Message->getLocStart(),
8412 Sema::LookupOrdinaryName);
8413 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8414 if (InterfaceDecl) {
8415 QualType NSCountedSetObject =
8416 S.Context.getObjCInterfaceType(InterfaceDecl);
8417 S.NSCountedSetPointer =
8418 S.Context.getObjCObjectPointerType(NSCountedSetObject);
8419 }
8420 }
8421
8422 if (S.NSMutableOrderedSetPointer.isNull()) {
8423 IdentifierInfo *NSOrderedSetId =
8424 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableOrderedSet);
8425 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSOrderedSetId,
8426 Message->getLocStart(),
8427 Sema::LookupOrdinaryName);
8428 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8429 if (InterfaceDecl) {
8430 QualType NSOrderedSetObject =
8431 S.Context.getObjCInterfaceType(InterfaceDecl);
8432 S.NSMutableOrderedSetPointer =
8433 S.Context.getObjCObjectPointerType(NSOrderedSetObject);
8434 }
8435 }
8436
8437 QualType ReceiverType = Message->getReceiverType();
8438
8439 bool IsMutableSet = !S.NSMutableSetPointer.isNull() &&
8440 ReceiverType == S.NSMutableSetPointer;
8441 bool IsMutableOrderedSet = !S.NSMutableOrderedSetPointer.isNull() &&
8442 ReceiverType == S.NSMutableOrderedSetPointer;
8443 bool IsCountedSet = !S.NSCountedSetPointer.isNull() &&
8444 ReceiverType == S.NSCountedSetPointer;
8445
8446 if (!IsMutableSet && !IsMutableOrderedSet && !IsCountedSet) {
8447 return None;
8448 }
8449
8450 Selector Sel = Message->getSelector();
8451
8452 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
8453 if (!MKOpt) {
8454 return None;
8455 }
8456
8457 NSAPI::NSSetMethodKind MK = *MKOpt;
8458
8459 switch (MK) {
8460 case NSAPI::NSMutableSet_addObject:
8461 case NSAPI::NSOrderedSet_setObjectAtIndex:
8462 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
8463 case NSAPI::NSOrderedSet_insertObjectAtIndex:
8464 return 0;
8465 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
8466 return 1;
8467 }
8468
8469 return None;
8470}
8471
8472void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
8473 if (!Message->isInstanceMessage()) {
8474 return;
8475 }
8476
8477 Optional<int> ArgOpt;
8478
8479 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
8480 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
8481 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
8482 return;
8483 }
8484
8485 int ArgIndex = *ArgOpt;
8486
8487 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
8488 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
8489 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
8490 }
8491
8492 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
8493 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
8494 Arg = OE->getSourceExpr()->IgnoreImpCasts();
8495 }
8496
8497 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
8498 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
8499 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
8500 ValueDecl *Decl = ReceiverRE->getDecl();
8501 Diag(Message->getSourceRange().getBegin(),
8502 diag::warn_objc_circular_container)
8503 << Decl->getName();
8504 Diag(Decl->getLocation(),
8505 diag::note_objc_circular_container_declared_here)
8506 << Decl->getName();
8507 }
8508 }
8509 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
8510 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
8511 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
8512 ObjCIvarDecl *Decl = IvarRE->getDecl();
8513 Diag(Message->getSourceRange().getBegin(),
8514 diag::warn_objc_circular_container)
8515 << Decl->getName();
8516 Diag(Decl->getLocation(),
8517 diag::note_objc_circular_container_declared_here)
8518 << Decl->getName();
8519 }
8520 }
8521 }
8522
8523}
8524
John McCall31168b02011-06-15 23:02:42 +00008525/// Check a message send to see if it's likely to cause a retain cycle.
8526void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8527 // Only check instance methods whose selector looks like a setter.
8528 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8529 return;
8530
8531 // Try to find a variable that the receiver is strongly owned by.
8532 RetainCycleOwner owner;
8533 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008534 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00008535 return;
8536 } else {
8537 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8538 owner.Variable = getCurMethodDecl()->getSelfDecl();
8539 owner.Loc = msg->getSuperLoc();
8540 owner.Range = msg->getSuperLoc();
8541 }
8542
8543 // Check whether the receiver is captured by any of the arguments.
8544 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
8545 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
8546 return diagnoseRetainCycle(*this, capturer, owner);
8547}
8548
8549/// Check a property assign to see if it's likely to cause a retain cycle.
8550void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
8551 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008552 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00008553 return;
8554
8555 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
8556 diagnoseRetainCycle(*this, capturer, owner);
8557}
8558
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008559void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
8560 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00008561 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008562 return;
8563
8564 // Because we don't have an expression for the variable, we have to set the
8565 // location explicitly here.
8566 Owner.Loc = Var->getLocation();
8567 Owner.Range = Var->getSourceRange();
8568
8569 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8570 diagnoseRetainCycle(*this, Capturer, Owner);
8571}
8572
Ted Kremenek9304da92012-12-21 08:04:28 +00008573static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8574 Expr *RHS, bool isProperty) {
8575 // Check if RHS is an Objective-C object literal, which also can get
8576 // immediately zapped in a weak reference. Note that we explicitly
8577 // allow ObjCStringLiterals, since those are designed to never really die.
8578 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008579
Ted Kremenek64873352012-12-21 22:46:35 +00008580 // This enum needs to match with the 'select' in
8581 // warn_objc_arc_literal_assign (off-by-1).
8582 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8583 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8584 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008585
8586 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00008587 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00008588 << (isProperty ? 0 : 1)
8589 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008590
8591 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00008592}
8593
Ted Kremenekc1f014a2012-12-21 19:45:30 +00008594static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8595 Qualifiers::ObjCLifetime LT,
8596 Expr *RHS, bool isProperty) {
8597 // Strip off any implicit cast added to get to the one ARC-specific.
8598 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8599 if (cast->getCastKind() == CK_ARCConsumeObject) {
8600 S.Diag(Loc, diag::warn_arc_retained_assign)
8601 << (LT == Qualifiers::OCL_ExplicitNone)
8602 << (isProperty ? 0 : 1)
8603 << RHS->getSourceRange();
8604 return true;
8605 }
8606 RHS = cast->getSubExpr();
8607 }
8608
8609 if (LT == Qualifiers::OCL_Weak &&
8610 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8611 return true;
8612
8613 return false;
8614}
8615
Ted Kremenekb36234d2012-12-21 08:04:20 +00008616bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8617 QualType LHS, Expr *RHS) {
8618 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8619
8620 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8621 return false;
8622
8623 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8624 return true;
8625
8626 return false;
8627}
8628
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008629void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8630 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008631 QualType LHSType;
8632 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00008633 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008634 ObjCPropertyRefExpr *PRE
8635 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8636 if (PRE && !PRE->isImplicitProperty()) {
8637 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8638 if (PD)
8639 LHSType = PD->getType();
8640 }
8641
8642 if (LHSType.isNull())
8643 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00008644
8645 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8646
8647 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008648 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00008649 getCurFunction()->markSafeWeakUse(LHS);
8650 }
8651
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008652 if (checkUnsafeAssigns(Loc, LHSType, RHS))
8653 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00008654
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008655 // FIXME. Check for other life times.
8656 if (LT != Qualifiers::OCL_None)
8657 return;
8658
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008659 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008660 if (PRE->isImplicitProperty())
8661 return;
8662 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8663 if (!PD)
8664 return;
8665
Bill Wendling44426052012-12-20 19:22:21 +00008666 unsigned Attributes = PD->getPropertyAttributes();
8667 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008668 // when 'assign' attribute was not explicitly specified
8669 // by user, ignore it and rely on property type itself
8670 // for lifetime info.
8671 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
8672 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
8673 LHSType->isObjCRetainableType())
8674 return;
8675
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008676 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00008677 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008678 Diag(Loc, diag::warn_arc_retained_property_assign)
8679 << RHS->getSourceRange();
8680 return;
8681 }
8682 RHS = cast->getSubExpr();
8683 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008684 }
Bill Wendling44426052012-12-20 19:22:21 +00008685 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00008686 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
8687 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00008688 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008689 }
8690}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008691
8692//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8693
8694namespace {
8695bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8696 SourceLocation StmtLoc,
8697 const NullStmt *Body) {
8698 // Do not warn if the body is a macro that expands to nothing, e.g:
8699 //
8700 // #define CALL(x)
8701 // if (condition)
8702 // CALL(0);
8703 //
8704 if (Body->hasLeadingEmptyMacro())
8705 return false;
8706
8707 // Get line numbers of statement and body.
8708 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +00008709 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008710 &StmtLineInvalid);
8711 if (StmtLineInvalid)
8712 return false;
8713
8714 bool BodyLineInvalid;
8715 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8716 &BodyLineInvalid);
8717 if (BodyLineInvalid)
8718 return false;
8719
8720 // Warn if null statement and body are on the same line.
8721 if (StmtLine != BodyLine)
8722 return false;
8723
8724 return true;
8725}
8726} // Unnamed namespace
8727
8728void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8729 const Stmt *Body,
8730 unsigned DiagID) {
8731 // Since this is a syntactic check, don't emit diagnostic for template
8732 // instantiations, this just adds noise.
8733 if (CurrentInstantiationScope)
8734 return;
8735
8736 // The body should be a null statement.
8737 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8738 if (!NBody)
8739 return;
8740
8741 // Do the usual checks.
8742 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8743 return;
8744
8745 Diag(NBody->getSemiLoc(), DiagID);
8746 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8747}
8748
8749void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8750 const Stmt *PossibleBody) {
8751 assert(!CurrentInstantiationScope); // Ensured by caller
8752
8753 SourceLocation StmtLoc;
8754 const Stmt *Body;
8755 unsigned DiagID;
8756 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8757 StmtLoc = FS->getRParenLoc();
8758 Body = FS->getBody();
8759 DiagID = diag::warn_empty_for_body;
8760 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8761 StmtLoc = WS->getCond()->getSourceRange().getEnd();
8762 Body = WS->getBody();
8763 DiagID = diag::warn_empty_while_body;
8764 } else
8765 return; // Neither `for' nor `while'.
8766
8767 // The body should be a null statement.
8768 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8769 if (!NBody)
8770 return;
8771
8772 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008773 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008774 return;
8775
8776 // Do the usual checks.
8777 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8778 return;
8779
8780 // `for(...);' and `while(...);' are popular idioms, so in order to keep
8781 // noise level low, emit diagnostics only if for/while is followed by a
8782 // CompoundStmt, e.g.:
8783 // for (int i = 0; i < n; i++);
8784 // {
8785 // a(i);
8786 // }
8787 // or if for/while is followed by a statement with more indentation
8788 // than for/while itself:
8789 // for (int i = 0; i < n; i++);
8790 // a(i);
8791 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8792 if (!ProbableTypo) {
8793 bool BodyColInvalid;
8794 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8795 PossibleBody->getLocStart(),
8796 &BodyColInvalid);
8797 if (BodyColInvalid)
8798 return;
8799
8800 bool StmtColInvalid;
8801 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8802 S->getLocStart(),
8803 &StmtColInvalid);
8804 if (StmtColInvalid)
8805 return;
8806
8807 if (BodyCol > StmtCol)
8808 ProbableTypo = true;
8809 }
8810
8811 if (ProbableTypo) {
8812 Diag(NBody->getSemiLoc(), DiagID);
8813 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8814 }
8815}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008816
Richard Trieu36d0b2b2015-01-13 02:32:02 +00008817//===--- CHECK: Warn on self move with std::move. -------------------------===//
8818
8819/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
8820void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
8821 SourceLocation OpLoc) {
8822
8823 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
8824 return;
8825
8826 if (!ActiveTemplateInstantiations.empty())
8827 return;
8828
8829 // Strip parens and casts away.
8830 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8831 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8832
8833 // Check for a call expression
8834 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
8835 if (!CE || CE->getNumArgs() != 1)
8836 return;
8837
8838 // Check for a call to std::move
8839 const FunctionDecl *FD = CE->getDirectCallee();
8840 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
8841 !FD->getIdentifier()->isStr("move"))
8842 return;
8843
8844 // Get argument from std::move
8845 RHSExpr = CE->getArg(0);
8846
8847 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8848 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8849
8850 // Two DeclRefExpr's, check that the decls are the same.
8851 if (LHSDeclRef && RHSDeclRef) {
8852 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8853 return;
8854 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8855 RHSDeclRef->getDecl()->getCanonicalDecl())
8856 return;
8857
8858 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8859 << LHSExpr->getSourceRange()
8860 << RHSExpr->getSourceRange();
8861 return;
8862 }
8863
8864 // Member variables require a different approach to check for self moves.
8865 // MemberExpr's are the same if every nested MemberExpr refers to the same
8866 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
8867 // the base Expr's are CXXThisExpr's.
8868 const Expr *LHSBase = LHSExpr;
8869 const Expr *RHSBase = RHSExpr;
8870 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
8871 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
8872 if (!LHSME || !RHSME)
8873 return;
8874
8875 while (LHSME && RHSME) {
8876 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
8877 RHSME->getMemberDecl()->getCanonicalDecl())
8878 return;
8879
8880 LHSBase = LHSME->getBase();
8881 RHSBase = RHSME->getBase();
8882 LHSME = dyn_cast<MemberExpr>(LHSBase);
8883 RHSME = dyn_cast<MemberExpr>(RHSBase);
8884 }
8885
8886 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
8887 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
8888 if (LHSDeclRef && RHSDeclRef) {
8889 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8890 return;
8891 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8892 RHSDeclRef->getDecl()->getCanonicalDecl())
8893 return;
8894
8895 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8896 << LHSExpr->getSourceRange()
8897 << RHSExpr->getSourceRange();
8898 return;
8899 }
8900
8901 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
8902 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8903 << LHSExpr->getSourceRange()
8904 << RHSExpr->getSourceRange();
8905}
8906
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008907//===--- Layout compatibility ----------------------------------------------//
8908
8909namespace {
8910
8911bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8912
8913/// \brief Check if two enumeration types are layout-compatible.
8914bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8915 // C++11 [dcl.enum] p8:
8916 // Two enumeration types are layout-compatible if they have the same
8917 // underlying type.
8918 return ED1->isComplete() && ED2->isComplete() &&
8919 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8920}
8921
8922/// \brief Check if two fields are layout-compatible.
8923bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8924 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8925 return false;
8926
8927 if (Field1->isBitField() != Field2->isBitField())
8928 return false;
8929
8930 if (Field1->isBitField()) {
8931 // Make sure that the bit-fields are the same length.
8932 unsigned Bits1 = Field1->getBitWidthValue(C);
8933 unsigned Bits2 = Field2->getBitWidthValue(C);
8934
8935 if (Bits1 != Bits2)
8936 return false;
8937 }
8938
8939 return true;
8940}
8941
8942/// \brief Check if two standard-layout structs are layout-compatible.
8943/// (C++11 [class.mem] p17)
8944bool isLayoutCompatibleStruct(ASTContext &C,
8945 RecordDecl *RD1,
8946 RecordDecl *RD2) {
8947 // If both records are C++ classes, check that base classes match.
8948 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
8949 // If one of records is a CXXRecordDecl we are in C++ mode,
8950 // thus the other one is a CXXRecordDecl, too.
8951 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
8952 // Check number of base classes.
8953 if (D1CXX->getNumBases() != D2CXX->getNumBases())
8954 return false;
8955
8956 // Check the base classes.
8957 for (CXXRecordDecl::base_class_const_iterator
8958 Base1 = D1CXX->bases_begin(),
8959 BaseEnd1 = D1CXX->bases_end(),
8960 Base2 = D2CXX->bases_begin();
8961 Base1 != BaseEnd1;
8962 ++Base1, ++Base2) {
8963 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
8964 return false;
8965 }
8966 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
8967 // If only RD2 is a C++ class, it should have zero base classes.
8968 if (D2CXX->getNumBases() > 0)
8969 return false;
8970 }
8971
8972 // Check the fields.
8973 RecordDecl::field_iterator Field2 = RD2->field_begin(),
8974 Field2End = RD2->field_end(),
8975 Field1 = RD1->field_begin(),
8976 Field1End = RD1->field_end();
8977 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
8978 if (!isLayoutCompatible(C, *Field1, *Field2))
8979 return false;
8980 }
8981 if (Field1 != Field1End || Field2 != Field2End)
8982 return false;
8983
8984 return true;
8985}
8986
8987/// \brief Check if two standard-layout unions are layout-compatible.
8988/// (C++11 [class.mem] p18)
8989bool isLayoutCompatibleUnion(ASTContext &C,
8990 RecordDecl *RD1,
8991 RecordDecl *RD2) {
8992 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008993 for (auto *Field2 : RD2->fields())
8994 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008995
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008996 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008997 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
8998 I = UnmatchedFields.begin(),
8999 E = UnmatchedFields.end();
9000
9001 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009002 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009003 bool Result = UnmatchedFields.erase(*I);
9004 (void) Result;
9005 assert(Result);
9006 break;
9007 }
9008 }
9009 if (I == E)
9010 return false;
9011 }
9012
9013 return UnmatchedFields.empty();
9014}
9015
9016bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
9017 if (RD1->isUnion() != RD2->isUnion())
9018 return false;
9019
9020 if (RD1->isUnion())
9021 return isLayoutCompatibleUnion(C, RD1, RD2);
9022 else
9023 return isLayoutCompatibleStruct(C, RD1, RD2);
9024}
9025
9026/// \brief Check if two types are layout-compatible in C++11 sense.
9027bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
9028 if (T1.isNull() || T2.isNull())
9029 return false;
9030
9031 // C++11 [basic.types] p11:
9032 // If two types T1 and T2 are the same type, then T1 and T2 are
9033 // layout-compatible types.
9034 if (C.hasSameType(T1, T2))
9035 return true;
9036
9037 T1 = T1.getCanonicalType().getUnqualifiedType();
9038 T2 = T2.getCanonicalType().getUnqualifiedType();
9039
9040 const Type::TypeClass TC1 = T1->getTypeClass();
9041 const Type::TypeClass TC2 = T2->getTypeClass();
9042
9043 if (TC1 != TC2)
9044 return false;
9045
9046 if (TC1 == Type::Enum) {
9047 return isLayoutCompatible(C,
9048 cast<EnumType>(T1)->getDecl(),
9049 cast<EnumType>(T2)->getDecl());
9050 } else if (TC1 == Type::Record) {
9051 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
9052 return false;
9053
9054 return isLayoutCompatible(C,
9055 cast<RecordType>(T1)->getDecl(),
9056 cast<RecordType>(T2)->getDecl());
9057 }
9058
9059 return false;
9060}
9061}
9062
9063//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
9064
9065namespace {
9066/// \brief Given a type tag expression find the type tag itself.
9067///
9068/// \param TypeExpr Type tag expression, as it appears in user's code.
9069///
9070/// \param VD Declaration of an identifier that appears in a type tag.
9071///
9072/// \param MagicValue Type tag magic value.
9073bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
9074 const ValueDecl **VD, uint64_t *MagicValue) {
9075 while(true) {
9076 if (!TypeExpr)
9077 return false;
9078
9079 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
9080
9081 switch (TypeExpr->getStmtClass()) {
9082 case Stmt::UnaryOperatorClass: {
9083 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
9084 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
9085 TypeExpr = UO->getSubExpr();
9086 continue;
9087 }
9088 return false;
9089 }
9090
9091 case Stmt::DeclRefExprClass: {
9092 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
9093 *VD = DRE->getDecl();
9094 return true;
9095 }
9096
9097 case Stmt::IntegerLiteralClass: {
9098 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
9099 llvm::APInt MagicValueAPInt = IL->getValue();
9100 if (MagicValueAPInt.getActiveBits() <= 64) {
9101 *MagicValue = MagicValueAPInt.getZExtValue();
9102 return true;
9103 } else
9104 return false;
9105 }
9106
9107 case Stmt::BinaryConditionalOperatorClass:
9108 case Stmt::ConditionalOperatorClass: {
9109 const AbstractConditionalOperator *ACO =
9110 cast<AbstractConditionalOperator>(TypeExpr);
9111 bool Result;
9112 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
9113 if (Result)
9114 TypeExpr = ACO->getTrueExpr();
9115 else
9116 TypeExpr = ACO->getFalseExpr();
9117 continue;
9118 }
9119 return false;
9120 }
9121
9122 case Stmt::BinaryOperatorClass: {
9123 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
9124 if (BO->getOpcode() == BO_Comma) {
9125 TypeExpr = BO->getRHS();
9126 continue;
9127 }
9128 return false;
9129 }
9130
9131 default:
9132 return false;
9133 }
9134 }
9135}
9136
9137/// \brief Retrieve the C type corresponding to type tag TypeExpr.
9138///
9139/// \param TypeExpr Expression that specifies a type tag.
9140///
9141/// \param MagicValues Registered magic values.
9142///
9143/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
9144/// kind.
9145///
9146/// \param TypeInfo Information about the corresponding C type.
9147///
9148/// \returns true if the corresponding C type was found.
9149bool GetMatchingCType(
9150 const IdentifierInfo *ArgumentKind,
9151 const Expr *TypeExpr, const ASTContext &Ctx,
9152 const llvm::DenseMap<Sema::TypeTagMagicValue,
9153 Sema::TypeTagData> *MagicValues,
9154 bool &FoundWrongKind,
9155 Sema::TypeTagData &TypeInfo) {
9156 FoundWrongKind = false;
9157
9158 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00009159 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009160
9161 uint64_t MagicValue;
9162
9163 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
9164 return false;
9165
9166 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00009167 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009168 if (I->getArgumentKind() != ArgumentKind) {
9169 FoundWrongKind = true;
9170 return false;
9171 }
9172 TypeInfo.Type = I->getMatchingCType();
9173 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
9174 TypeInfo.MustBeNull = I->getMustBeNull();
9175 return true;
9176 }
9177 return false;
9178 }
9179
9180 if (!MagicValues)
9181 return false;
9182
9183 llvm::DenseMap<Sema::TypeTagMagicValue,
9184 Sema::TypeTagData>::const_iterator I =
9185 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
9186 if (I == MagicValues->end())
9187 return false;
9188
9189 TypeInfo = I->second;
9190 return true;
9191}
9192} // unnamed namespace
9193
9194void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9195 uint64_t MagicValue, QualType Type,
9196 bool LayoutCompatible,
9197 bool MustBeNull) {
9198 if (!TypeTagForDatatypeMagicValues)
9199 TypeTagForDatatypeMagicValues.reset(
9200 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
9201
9202 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
9203 (*TypeTagForDatatypeMagicValues)[Magic] =
9204 TypeTagData(Type, LayoutCompatible, MustBeNull);
9205}
9206
9207namespace {
9208bool IsSameCharType(QualType T1, QualType T2) {
9209 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
9210 if (!BT1)
9211 return false;
9212
9213 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
9214 if (!BT2)
9215 return false;
9216
9217 BuiltinType::Kind T1Kind = BT1->getKind();
9218 BuiltinType::Kind T2Kind = BT2->getKind();
9219
9220 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
9221 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
9222 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
9223 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
9224}
9225} // unnamed namespace
9226
9227void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9228 const Expr * const *ExprArgs) {
9229 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
9230 bool IsPointerAttr = Attr->getIsPointer();
9231
9232 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
9233 bool FoundWrongKind;
9234 TypeTagData TypeInfo;
9235 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
9236 TypeTagForDatatypeMagicValues.get(),
9237 FoundWrongKind, TypeInfo)) {
9238 if (FoundWrongKind)
9239 Diag(TypeTagExpr->getExprLoc(),
9240 diag::warn_type_tag_for_datatype_wrong_kind)
9241 << TypeTagExpr->getSourceRange();
9242 return;
9243 }
9244
9245 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
9246 if (IsPointerAttr) {
9247 // Skip implicit cast of pointer to `void *' (as a function argument).
9248 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00009249 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00009250 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009251 ArgumentExpr = ICE->getSubExpr();
9252 }
9253 QualType ArgumentType = ArgumentExpr->getType();
9254
9255 // Passing a `void*' pointer shouldn't trigger a warning.
9256 if (IsPointerAttr && ArgumentType->isVoidPointerType())
9257 return;
9258
9259 if (TypeInfo.MustBeNull) {
9260 // Type tag with matching void type requires a null pointer.
9261 if (!ArgumentExpr->isNullPointerConstant(Context,
9262 Expr::NPC_ValueDependentIsNotNull)) {
9263 Diag(ArgumentExpr->getExprLoc(),
9264 diag::warn_type_safety_null_pointer_required)
9265 << ArgumentKind->getName()
9266 << ArgumentExpr->getSourceRange()
9267 << TypeTagExpr->getSourceRange();
9268 }
9269 return;
9270 }
9271
9272 QualType RequiredType = TypeInfo.Type;
9273 if (IsPointerAttr)
9274 RequiredType = Context.getPointerType(RequiredType);
9275
9276 bool mismatch = false;
9277 if (!TypeInfo.LayoutCompatible) {
9278 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
9279
9280 // C++11 [basic.fundamental] p1:
9281 // Plain char, signed char, and unsigned char are three distinct types.
9282 //
9283 // But we treat plain `char' as equivalent to `signed char' or `unsigned
9284 // char' depending on the current char signedness mode.
9285 if (mismatch)
9286 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
9287 RequiredType->getPointeeType())) ||
9288 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
9289 mismatch = false;
9290 } else
9291 if (IsPointerAttr)
9292 mismatch = !isLayoutCompatible(Context,
9293 ArgumentType->getPointeeType(),
9294 RequiredType->getPointeeType());
9295 else
9296 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
9297
9298 if (mismatch)
9299 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00009300 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009301 << TypeInfo.LayoutCompatible << RequiredType
9302 << ArgumentExpr->getSourceRange()
9303 << TypeTagExpr->getSourceRange();
9304}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009305