blob: 5737e8338ff28a14426a46ada3336eea99b67ca8 [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 Qin78b86532015-05-14 08:18:05 +0000626 if (IsInt64Long)
627 return Context.UnsignedLongTy;
628 else
629 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000630 case NeonTypeFlags::Poly128:
631 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000632 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000633 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000634 case NeonTypeFlags::Float32:
635 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000636 case NeonTypeFlags::Float64:
637 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000638 }
David Blaikie8a40f702012-01-17 06:56:22 +0000639 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000640}
641
Tim Northover12670412014-02-19 10:37:05 +0000642bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000643 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000644 uint64_t mask = 0;
645 unsigned TV = 0;
646 int PtrArgNum = -1;
647 bool HasConstPtr = false;
648 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000649#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000650#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000651#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000652 }
653
654 // For NEON intrinsics which are overloaded on vector element type, validate
655 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000656 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000657 if (mask) {
658 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
659 return true;
660
661 TV = Result.getLimitedValue(64);
662 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
663 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000664 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000665 }
666
667 if (PtrArgNum >= 0) {
668 // Check that pointer arguments have the specified type.
669 Expr *Arg = TheCall->getArg(PtrArgNum);
670 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
671 Arg = ICE->getSubExpr();
672 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
673 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000674
Tim Northovera2ee4332014-03-29 15:09:45 +0000675 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000676 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000677 bool IsInt64Long =
678 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
679 QualType EltTy =
680 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000681 if (HasConstPtr)
682 EltTy = EltTy.withConst();
683 QualType LHSTy = Context.getPointerType(EltTy);
684 AssignConvertType ConvTy;
685 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
686 if (RHS.isInvalid())
687 return true;
688 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
689 RHS.get(), AA_Assigning))
690 return true;
691 }
692
693 // For NEON intrinsics which take an immediate value as part of the
694 // instruction, range check them here.
695 unsigned i = 0, l = 0, u = 0;
696 switch (BuiltinID) {
697 default:
698 return false;
Tim Northover12670412014-02-19 10:37:05 +0000699#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000700#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000701#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000702 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000703
Richard Sandiford28940af2014-04-16 08:47:51 +0000704 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000705}
706
Tim Northovera2ee4332014-03-29 15:09:45 +0000707bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
708 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000709 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000710 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000711 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000712 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000713 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000714 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
715 BuiltinID == AArch64::BI__builtin_arm_strex ||
716 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000717 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000718 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000719 BuiltinID == ARM::BI__builtin_arm_ldaex ||
720 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
721 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000722
723 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
724
725 // Ensure that we have the proper number of arguments.
726 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
727 return true;
728
729 // Inspect the pointer argument of the atomic builtin. This should always be
730 // a pointer type, whose element is an integral scalar or pointer type.
731 // Because it is a pointer type, we don't have to worry about any implicit
732 // casts here.
733 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
734 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
735 if (PointerArgRes.isInvalid())
736 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000737 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000738
739 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
740 if (!pointerType) {
741 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
742 << PointerArg->getType() << PointerArg->getSourceRange();
743 return true;
744 }
745
746 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
747 // task is to insert the appropriate casts into the AST. First work out just
748 // what the appropriate type is.
749 QualType ValType = pointerType->getPointeeType();
750 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
751 if (IsLdrex)
752 AddrType.addConst();
753
754 // Issue a warning if the cast is dodgy.
755 CastKind CastNeeded = CK_NoOp;
756 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
757 CastNeeded = CK_BitCast;
758 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
759 << PointerArg->getType()
760 << Context.getPointerType(AddrType)
761 << AA_Passing << PointerArg->getSourceRange();
762 }
763
764 // Finally, do the cast and replace the argument with the corrected version.
765 AddrType = Context.getPointerType(AddrType);
766 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
767 if (PointerArgRes.isInvalid())
768 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000769 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000770
771 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
772
773 // In general, we allow ints, floats and pointers to be loaded and stored.
774 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
775 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
776 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
777 << PointerArg->getType() << PointerArg->getSourceRange();
778 return true;
779 }
780
781 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000782 if (Context.getTypeSize(ValType) > MaxWidth) {
783 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000784 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
785 << PointerArg->getType() << PointerArg->getSourceRange();
786 return true;
787 }
788
789 switch (ValType.getObjCLifetime()) {
790 case Qualifiers::OCL_None:
791 case Qualifiers::OCL_ExplicitNone:
792 // okay
793 break;
794
795 case Qualifiers::OCL_Weak:
796 case Qualifiers::OCL_Strong:
797 case Qualifiers::OCL_Autoreleasing:
798 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
799 << ValType << PointerArg->getSourceRange();
800 return true;
801 }
802
803
804 if (IsLdrex) {
805 TheCall->setType(ValType);
806 return false;
807 }
808
809 // Initialize the argument to be stored.
810 ExprResult ValArg = TheCall->getArg(0);
811 InitializedEntity Entity = InitializedEntity::InitializeParameter(
812 Context, ValType, /*consume*/ false);
813 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
814 if (ValArg.isInvalid())
815 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000816 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000817
818 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
819 // but the custom checker bypasses all default analysis.
820 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000821 return false;
822}
823
Nate Begeman4904e322010-06-08 02:47:44 +0000824bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000825 llvm::APSInt Result;
826
Tim Northover6aacd492013-07-16 09:47:53 +0000827 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000828 BuiltinID == ARM::BI__builtin_arm_ldaex ||
829 BuiltinID == ARM::BI__builtin_arm_strex ||
830 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000831 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000832 }
833
Yi Kong26d104a2014-08-13 19:18:14 +0000834 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
835 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
836 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
837 }
838
Luke Cheeseman59b2d832015-06-15 17:51:01 +0000839 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
840 BuiltinID == ARM::BI__builtin_arm_wsr64)
841 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
842
843 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
844 BuiltinID == ARM::BI__builtin_arm_rsrp ||
845 BuiltinID == ARM::BI__builtin_arm_wsr ||
846 BuiltinID == ARM::BI__builtin_arm_wsrp)
847 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
848
Tim Northover12670412014-02-19 10:37:05 +0000849 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
850 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000851
Yi Kong4efadfb2014-07-03 16:01:25 +0000852 // For intrinsics which take an immediate value as part of the instruction,
853 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000854 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000855 switch (BuiltinID) {
856 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000857 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
858 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000859 case ARM::BI__builtin_arm_vcvtr_f:
860 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000861 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +0000862 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +0000863 case ARM::BI__builtin_arm_isb:
864 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000865 }
Nate Begemand773fe62010-06-13 04:47:52 +0000866
Nate Begemanf568b072010-08-03 21:32:34 +0000867 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000868 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000869}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000870
Tim Northover573cbee2014-05-24 12:52:07 +0000871bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000872 CallExpr *TheCall) {
873 llvm::APSInt Result;
874
Tim Northover573cbee2014-05-24 12:52:07 +0000875 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000876 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
877 BuiltinID == AArch64::BI__builtin_arm_strex ||
878 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000879 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
880 }
881
Yi Konga5548432014-08-13 19:18:20 +0000882 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
883 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
884 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
885 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
886 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
887 }
888
Luke Cheeseman59b2d832015-06-15 17:51:01 +0000889 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
890 BuiltinID == AArch64::BI__builtin_arm_wsr64)
891 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, false);
892
893 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
894 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
895 BuiltinID == AArch64::BI__builtin_arm_wsr ||
896 BuiltinID == AArch64::BI__builtin_arm_wsrp)
897 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
898
Tim Northovera2ee4332014-03-29 15:09:45 +0000899 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
900 return true;
901
Yi Kong19a29ac2014-07-17 10:52:06 +0000902 // For intrinsics which take an immediate value as part of the instruction,
903 // range check them here.
904 unsigned i = 0, l = 0, u = 0;
905 switch (BuiltinID) {
906 default: return false;
907 case AArch64::BI__builtin_arm_dmb:
908 case AArch64::BI__builtin_arm_dsb:
909 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
910 }
911
Yi Kong19a29ac2014-07-17 10:52:06 +0000912 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +0000913}
914
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000915bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
916 unsigned i = 0, l = 0, u = 0;
917 switch (BuiltinID) {
918 default: return false;
919 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
920 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000921 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
922 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
923 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
924 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
925 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000926 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000927
Richard Sandiford28940af2014-04-16 08:47:51 +0000928 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000929}
930
Kit Bartone50adcb2015-03-30 19:40:59 +0000931bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
932 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +0000933 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
934 BuiltinID == PPC::BI__builtin_divdeu ||
935 BuiltinID == PPC::BI__builtin_bpermd;
936 bool IsTarget64Bit = Context.getTargetInfo()
937 .getTypeWidth(Context
938 .getTargetInfo()
939 .getIntPtrType()) == 64;
940 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
941 BuiltinID == PPC::BI__builtin_divweu ||
942 BuiltinID == PPC::BI__builtin_divde ||
943 BuiltinID == PPC::BI__builtin_divdeu;
944
945 if (Is64BitBltin && !IsTarget64Bit)
946 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
947 << TheCall->getSourceRange();
948
949 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
950 (BuiltinID == PPC::BI__builtin_bpermd &&
951 !Context.getTargetInfo().hasFeature("bpermd")))
952 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
953 << TheCall->getSourceRange();
954
Kit Bartone50adcb2015-03-30 19:40:59 +0000955 switch (BuiltinID) {
956 default: return false;
957 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
958 case PPC::BI__builtin_altivec_crypto_vshasigmad:
959 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
960 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
961 case PPC::BI__builtin_tbegin:
962 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
963 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
964 case PPC::BI__builtin_tabortwc:
965 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
966 case PPC::BI__builtin_tabortwci:
967 case PPC::BI__builtin_tabortdci:
968 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
969 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
970 }
971 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
972}
973
Ulrich Weigand3a610eb2015-04-01 12:54:25 +0000974bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
975 CallExpr *TheCall) {
976 if (BuiltinID == SystemZ::BI__builtin_tabort) {
977 Expr *Arg = TheCall->getArg(0);
978 llvm::APSInt AbortCode(32);
979 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
980 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
981 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
982 << Arg->getSourceRange();
983 }
984
Ulrich Weigand5722c0f2015-05-05 19:36:42 +0000985 // For intrinsics which take an immediate value as part of the instruction,
986 // range check them here.
987 unsigned i = 0, l = 0, u = 0;
988 switch (BuiltinID) {
989 default: return false;
990 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
991 case SystemZ::BI__builtin_s390_verimb:
992 case SystemZ::BI__builtin_s390_verimh:
993 case SystemZ::BI__builtin_s390_verimf:
994 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
995 case SystemZ::BI__builtin_s390_vfaeb:
996 case SystemZ::BI__builtin_s390_vfaeh:
997 case SystemZ::BI__builtin_s390_vfaef:
998 case SystemZ::BI__builtin_s390_vfaebs:
999 case SystemZ::BI__builtin_s390_vfaehs:
1000 case SystemZ::BI__builtin_s390_vfaefs:
1001 case SystemZ::BI__builtin_s390_vfaezb:
1002 case SystemZ::BI__builtin_s390_vfaezh:
1003 case SystemZ::BI__builtin_s390_vfaezf:
1004 case SystemZ::BI__builtin_s390_vfaezbs:
1005 case SystemZ::BI__builtin_s390_vfaezhs:
1006 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1007 case SystemZ::BI__builtin_s390_vfidb:
1008 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1009 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1010 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1011 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1012 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1013 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1014 case SystemZ::BI__builtin_s390_vstrcb:
1015 case SystemZ::BI__builtin_s390_vstrch:
1016 case SystemZ::BI__builtin_s390_vstrcf:
1017 case SystemZ::BI__builtin_s390_vstrczb:
1018 case SystemZ::BI__builtin_s390_vstrczh:
1019 case SystemZ::BI__builtin_s390_vstrczf:
1020 case SystemZ::BI__builtin_s390_vstrcbs:
1021 case SystemZ::BI__builtin_s390_vstrchs:
1022 case SystemZ::BI__builtin_s390_vstrcfs:
1023 case SystemZ::BI__builtin_s390_vstrczbs:
1024 case SystemZ::BI__builtin_s390_vstrczhs:
1025 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1026 }
1027 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001028}
1029
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001030bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001031 unsigned i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001032 switch (BuiltinID) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001033 default: return false;
Eric Christopherd9832702015-06-29 21:00:05 +00001034 case X86::BI__builtin_cpu_supports:
1035 return SemaBuiltinCpuSupports(TheCall);
Craig Topperdd84ec52014-12-27 07:00:08 +00001036 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
Craig Topper16015252015-01-31 06:31:23 +00001037 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001038 case X86::BI__builtin_ia32_vpermil2pd:
1039 case X86::BI__builtin_ia32_vpermil2pd256:
1040 case X86::BI__builtin_ia32_vpermil2ps:
1041 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
Craig Topper95b0d732015-01-25 23:30:05 +00001042 case X86::BI__builtin_ia32_cmpb128_mask:
1043 case X86::BI__builtin_ia32_cmpw128_mask:
1044 case X86::BI__builtin_ia32_cmpd128_mask:
1045 case X86::BI__builtin_ia32_cmpq128_mask:
1046 case X86::BI__builtin_ia32_cmpb256_mask:
1047 case X86::BI__builtin_ia32_cmpw256_mask:
1048 case X86::BI__builtin_ia32_cmpd256_mask:
1049 case X86::BI__builtin_ia32_cmpq256_mask:
1050 case X86::BI__builtin_ia32_cmpb512_mask:
1051 case X86::BI__builtin_ia32_cmpw512_mask:
1052 case X86::BI__builtin_ia32_cmpd512_mask:
1053 case X86::BI__builtin_ia32_cmpq512_mask:
1054 case X86::BI__builtin_ia32_ucmpb128_mask:
1055 case X86::BI__builtin_ia32_ucmpw128_mask:
1056 case X86::BI__builtin_ia32_ucmpd128_mask:
1057 case X86::BI__builtin_ia32_ucmpq128_mask:
1058 case X86::BI__builtin_ia32_ucmpb256_mask:
1059 case X86::BI__builtin_ia32_ucmpw256_mask:
1060 case X86::BI__builtin_ia32_ucmpd256_mask:
1061 case X86::BI__builtin_ia32_ucmpq256_mask:
1062 case X86::BI__builtin_ia32_ucmpb512_mask:
1063 case X86::BI__builtin_ia32_ucmpw512_mask:
1064 case X86::BI__builtin_ia32_ucmpd512_mask:
1065 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
Craig Topper16015252015-01-31 06:31:23 +00001066 case X86::BI__builtin_ia32_roundps:
1067 case X86::BI__builtin_ia32_roundpd:
1068 case X86::BI__builtin_ia32_roundps256:
1069 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
1070 case X86::BI__builtin_ia32_roundss:
1071 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
1072 case X86::BI__builtin_ia32_cmpps:
1073 case X86::BI__builtin_ia32_cmpss:
1074 case X86::BI__builtin_ia32_cmppd:
1075 case X86::BI__builtin_ia32_cmpsd:
1076 case X86::BI__builtin_ia32_cmpps256:
1077 case X86::BI__builtin_ia32_cmppd256:
1078 case X86::BI__builtin_ia32_cmpps512_mask:
1079 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001080 case X86::BI__builtin_ia32_vpcomub:
1081 case X86::BI__builtin_ia32_vpcomuw:
1082 case X86::BI__builtin_ia32_vpcomud:
1083 case X86::BI__builtin_ia32_vpcomuq:
1084 case X86::BI__builtin_ia32_vpcomb:
1085 case X86::BI__builtin_ia32_vpcomw:
1086 case X86::BI__builtin_ia32_vpcomd:
1087 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001088 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001089 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001090}
1091
Richard Smith55ce3522012-06-25 20:30:08 +00001092/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1093/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1094/// Returns true when the format fits the function and the FormatStringInfo has
1095/// been populated.
1096bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1097 FormatStringInfo *FSI) {
1098 FSI->HasVAListArg = Format->getFirstArg() == 0;
1099 FSI->FormatIdx = Format->getFormatIdx() - 1;
1100 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001101
Richard Smith55ce3522012-06-25 20:30:08 +00001102 // The way the format attribute works in GCC, the implicit this argument
1103 // of member functions is counted. However, it doesn't appear in our own
1104 // lists, so decrement format_idx in that case.
1105 if (IsCXXMember) {
1106 if(FSI->FormatIdx == 0)
1107 return false;
1108 --FSI->FormatIdx;
1109 if (FSI->FirstDataArg != 0)
1110 --FSI->FirstDataArg;
1111 }
1112 return true;
1113}
Mike Stump11289f42009-09-09 15:08:12 +00001114
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001115/// Checks if a the given expression evaluates to null.
1116///
1117/// \brief Returns true if the value evaluates to null.
1118static bool CheckNonNullExpr(Sema &S,
1119 const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001120 // If the expression has non-null type, it doesn't evaluate to null.
1121 if (auto nullability
1122 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1123 if (*nullability == NullabilityKind::NonNull)
1124 return false;
1125 }
1126
Ted Kremeneka146db32014-01-17 06:24:47 +00001127 // As a special case, transparent unions initialized with zero are
1128 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001129 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001130 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1131 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001132 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001133 if (const InitListExpr *ILE =
1134 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001135 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001136 }
1137
1138 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001139 return (!Expr->isValueDependent() &&
1140 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1141 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001142}
1143
1144static void CheckNonNullArgument(Sema &S,
1145 const Expr *ArgExpr,
1146 SourceLocation CallSiteLoc) {
1147 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001148 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
1149}
1150
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001151bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1152 FormatStringInfo FSI;
1153 if ((GetFormatStringType(Format) == FST_NSString) &&
1154 getFormatStringInfo(Format, false, &FSI)) {
1155 Idx = FSI.FormatIdx;
1156 return true;
1157 }
1158 return false;
1159}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001160/// \brief Diagnose use of %s directive in an NSString which is being passed
1161/// as formatting string to formatting method.
1162static void
1163DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1164 const NamedDecl *FDecl,
1165 Expr **Args,
1166 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001167 unsigned Idx = 0;
1168 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001169 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1170 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001171 Idx = 2;
1172 Format = true;
1173 }
1174 else
1175 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1176 if (S.GetFormatNSStringIdx(I, Idx)) {
1177 Format = true;
1178 break;
1179 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001180 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001181 if (!Format || NumArgs <= Idx)
1182 return;
1183 const Expr *FormatExpr = Args[Idx];
1184 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1185 FormatExpr = CSCE->getSubExpr();
1186 const StringLiteral *FormatString;
1187 if (const ObjCStringLiteral *OSL =
1188 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1189 FormatString = OSL->getString();
1190 else
1191 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1192 if (!FormatString)
1193 return;
1194 if (S.FormatStringHasSArg(FormatString)) {
1195 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1196 << "%s" << 1 << 1;
1197 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1198 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001199 }
1200}
1201
Douglas Gregorb4866e82015-06-19 18:13:19 +00001202/// Determine whether the given type has a non-null nullability annotation.
1203static bool isNonNullType(ASTContext &ctx, QualType type) {
1204 if (auto nullability = type->getNullability(ctx))
1205 return *nullability == NullabilityKind::NonNull;
1206
1207 return false;
1208}
1209
Ted Kremenek2bc73332014-01-17 06:24:43 +00001210static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001211 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00001212 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00001213 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001214 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001215 assert((FDecl || Proto) && "Need a function declaration or prototype");
1216
Ted Kremenek9aedc152014-01-17 06:24:56 +00001217 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001218 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001219 if (FDecl) {
1220 // Handle the nonnull attribute on the function/method declaration itself.
1221 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1222 if (!NonNull->args_size()) {
1223 // Easy case: all pointer arguments are nonnull.
1224 for (const auto *Arg : Args)
1225 if (S.isValidPointerAttrType(Arg->getType()))
1226 CheckNonNullArgument(S, Arg, CallSiteLoc);
1227 return;
1228 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001229
Douglas Gregorb4866e82015-06-19 18:13:19 +00001230 for (unsigned Val : NonNull->args()) {
1231 if (Val >= Args.size())
1232 continue;
1233 if (NonNullArgs.empty())
1234 NonNullArgs.resize(Args.size());
1235 NonNullArgs.set(Val);
1236 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001237 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001238 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001239
Douglas Gregorb4866e82015-06-19 18:13:19 +00001240 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1241 // Handle the nonnull attribute on the parameters of the
1242 // function/method.
1243 ArrayRef<ParmVarDecl*> parms;
1244 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1245 parms = FD->parameters();
1246 else
1247 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1248
1249 unsigned ParamIndex = 0;
1250 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1251 I != E; ++I, ++ParamIndex) {
1252 const ParmVarDecl *PVD = *I;
1253 if (PVD->hasAttr<NonNullAttr>() ||
1254 isNonNullType(S.Context, PVD->getType())) {
1255 if (NonNullArgs.empty())
1256 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00001257
Douglas Gregorb4866e82015-06-19 18:13:19 +00001258 NonNullArgs.set(ParamIndex);
1259 }
1260 }
1261 } else {
1262 // If we have a non-function, non-method declaration but no
1263 // function prototype, try to dig out the function prototype.
1264 if (!Proto) {
1265 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1266 QualType type = VD->getType().getNonReferenceType();
1267 if (auto pointerType = type->getAs<PointerType>())
1268 type = pointerType->getPointeeType();
1269 else if (auto blockType = type->getAs<BlockPointerType>())
1270 type = blockType->getPointeeType();
1271 // FIXME: data member pointers?
1272
1273 // Dig out the function prototype, if there is one.
1274 Proto = type->getAs<FunctionProtoType>();
1275 }
1276 }
1277
1278 // Fill in non-null argument information from the nullability
1279 // information on the parameter types (if we have them).
1280 if (Proto) {
1281 unsigned Index = 0;
1282 for (auto paramType : Proto->getParamTypes()) {
1283 if (isNonNullType(S.Context, paramType)) {
1284 if (NonNullArgs.empty())
1285 NonNullArgs.resize(Args.size());
1286
1287 NonNullArgs.set(Index);
1288 }
1289
1290 ++Index;
1291 }
1292 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001293 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001294
Douglas Gregorb4866e82015-06-19 18:13:19 +00001295 // Check for non-null arguments.
1296 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1297 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001298 if (NonNullArgs[ArgIndex])
1299 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00001300 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001301}
1302
Richard Smith55ce3522012-06-25 20:30:08 +00001303/// Handles the checks for format strings, non-POD arguments to vararg
1304/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001305void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1306 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00001307 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001308 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001309 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001310 if (CurContext->isDependentContext())
1311 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001312
Ted Kremenekb8176da2010-09-09 04:33:05 +00001313 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001314 llvm::SmallBitVector CheckedVarArgs;
1315 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001316 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001317 // Only create vector if there are format attributes.
1318 CheckedVarArgs.resize(Args.size());
1319
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001320 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001321 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001322 }
Richard Smithd7293d72013-08-05 18:49:43 +00001323 }
Richard Smith55ce3522012-06-25 20:30:08 +00001324
1325 // Refuse POD arguments that weren't caught by the format string
1326 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001327 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001328 unsigned NumParams = Proto ? Proto->getNumParams()
1329 : FDecl && isa<FunctionDecl>(FDecl)
1330 ? cast<FunctionDecl>(FDecl)->getNumParams()
1331 : FDecl && isa<ObjCMethodDecl>(FDecl)
1332 ? cast<ObjCMethodDecl>(FDecl)->param_size()
1333 : 0;
1334
Alp Toker9cacbab2014-01-20 20:26:09 +00001335 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001336 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001337 if (const Expr *Arg = Args[ArgIdx]) {
1338 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1339 checkVariadicArgument(Arg, CallType);
1340 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001341 }
Richard Smithd7293d72013-08-05 18:49:43 +00001342 }
Mike Stump11289f42009-09-09 15:08:12 +00001343
Douglas Gregorb4866e82015-06-19 18:13:19 +00001344 if (FDecl || Proto) {
1345 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001346
Richard Trieu41bc0992013-06-22 00:20:41 +00001347 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001348 if (FDecl) {
1349 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1350 CheckArgumentWithTypeTag(I, Args.data());
1351 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001352 }
Richard Smith55ce3522012-06-25 20:30:08 +00001353}
1354
1355/// CheckConstructorCall - Check a constructor call for correctness and safety
1356/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001357void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1358 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001359 const FunctionProtoType *Proto,
1360 SourceLocation Loc) {
1361 VariadicCallType CallType =
1362 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001363 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1364 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00001365}
1366
1367/// CheckFunctionCall - Check a direct function call for various correctness
1368/// and safety properties not strictly enforced by the C type system.
1369bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1370 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001371 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1372 isa<CXXMethodDecl>(FDecl);
1373 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1374 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001375 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1376 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00001377 Expr** Args = TheCall->getArgs();
1378 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001379 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001380 // If this is a call to a member operator, hide the first argument
1381 // from checkCall.
1382 // FIXME: Our choice of AST representation here is less than ideal.
1383 ++Args;
1384 --NumArgs;
1385 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00001386 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00001387 IsMemberFunction, TheCall->getRParenLoc(),
1388 TheCall->getCallee()->getSourceRange(), CallType);
1389
1390 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1391 // None of the checks below are needed for functions that don't have
1392 // simple names (e.g., C++ conversion functions).
1393 if (!FnInfo)
1394 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001395
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001396 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001397 if (getLangOpts().ObjC1)
1398 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001399
Anna Zaks22122702012-01-17 00:37:07 +00001400 unsigned CMId = FDecl->getMemoryFunctionKind();
1401 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001402 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001403
Anna Zaks201d4892012-01-13 21:52:01 +00001404 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001405 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001406 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001407 else if (CMId == Builtin::BIstrncat)
1408 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001409 else
Anna Zaks22122702012-01-17 00:37:07 +00001410 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001411
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001412 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001413}
1414
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001415bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001416 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001417 VariadicCallType CallType =
1418 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001419
Douglas Gregorb4866e82015-06-19 18:13:19 +00001420 checkCall(Method, nullptr, Args,
1421 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1422 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001423
1424 return false;
1425}
1426
Richard Trieu664c4c62013-06-20 21:03:13 +00001427bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1428 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00001429 QualType Ty;
1430 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001431 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001432 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001433 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001434 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001435 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001436
Douglas Gregorb4866e82015-06-19 18:13:19 +00001437 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
1438 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001439 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001440
Richard Trieu664c4c62013-06-20 21:03:13 +00001441 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001442 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001443 CallType = VariadicDoesNotApply;
1444 } else if (Ty->isBlockPointerType()) {
1445 CallType = VariadicBlock;
1446 } else { // Ty->isFunctionPointerType()
1447 CallType = VariadicFunction;
1448 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001449
Douglas Gregorb4866e82015-06-19 18:13:19 +00001450 checkCall(NDecl, Proto,
1451 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1452 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001453 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001454
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001455 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001456}
1457
Richard Trieu41bc0992013-06-22 00:20:41 +00001458/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1459/// such as function pointers returned from functions.
1460bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001461 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001462 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00001463 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001464 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00001465 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001466 TheCall->getCallee()->getSourceRange(), CallType);
1467
1468 return false;
1469}
1470
Tim Northovere94a34c2014-03-11 10:49:14 +00001471static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1472 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1473 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1474 return false;
1475
1476 switch (Op) {
1477 case AtomicExpr::AO__c11_atomic_init:
1478 llvm_unreachable("There is no ordering argument for an init");
1479
1480 case AtomicExpr::AO__c11_atomic_load:
1481 case AtomicExpr::AO__atomic_load_n:
1482 case AtomicExpr::AO__atomic_load:
1483 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1484 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1485
1486 case AtomicExpr::AO__c11_atomic_store:
1487 case AtomicExpr::AO__atomic_store:
1488 case AtomicExpr::AO__atomic_store_n:
1489 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1490 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1491 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1492
1493 default:
1494 return true;
1495 }
1496}
1497
Richard Smithfeea8832012-04-12 05:08:17 +00001498ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1499 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001500 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1501 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001502
Richard Smithfeea8832012-04-12 05:08:17 +00001503 // All these operations take one of the following forms:
1504 enum {
1505 // C __c11_atomic_init(A *, C)
1506 Init,
1507 // C __c11_atomic_load(A *, int)
1508 Load,
1509 // void __atomic_load(A *, CP, int)
1510 Copy,
1511 // C __c11_atomic_add(A *, M, int)
1512 Arithmetic,
1513 // C __atomic_exchange_n(A *, CP, int)
1514 Xchg,
1515 // void __atomic_exchange(A *, C *, CP, int)
1516 GNUXchg,
1517 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1518 C11CmpXchg,
1519 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1520 GNUCmpXchg
1521 } Form = Init;
1522 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1523 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1524 // where:
1525 // C is an appropriate type,
1526 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1527 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1528 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1529 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001530
Gabor Horvath98bd0982015-03-16 09:59:54 +00001531 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1532 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1533 AtomicExpr::AO__atomic_load,
1534 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00001535 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1536 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1537 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1538 Op == AtomicExpr::AO__atomic_store_n ||
1539 Op == AtomicExpr::AO__atomic_exchange_n ||
1540 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1541 bool IsAddSub = false;
1542
1543 switch (Op) {
1544 case AtomicExpr::AO__c11_atomic_init:
1545 Form = Init;
1546 break;
1547
1548 case AtomicExpr::AO__c11_atomic_load:
1549 case AtomicExpr::AO__atomic_load_n:
1550 Form = Load;
1551 break;
1552
1553 case AtomicExpr::AO__c11_atomic_store:
1554 case AtomicExpr::AO__atomic_load:
1555 case AtomicExpr::AO__atomic_store:
1556 case AtomicExpr::AO__atomic_store_n:
1557 Form = Copy;
1558 break;
1559
1560 case AtomicExpr::AO__c11_atomic_fetch_add:
1561 case AtomicExpr::AO__c11_atomic_fetch_sub:
1562 case AtomicExpr::AO__atomic_fetch_add:
1563 case AtomicExpr::AO__atomic_fetch_sub:
1564 case AtomicExpr::AO__atomic_add_fetch:
1565 case AtomicExpr::AO__atomic_sub_fetch:
1566 IsAddSub = true;
1567 // Fall through.
1568 case AtomicExpr::AO__c11_atomic_fetch_and:
1569 case AtomicExpr::AO__c11_atomic_fetch_or:
1570 case AtomicExpr::AO__c11_atomic_fetch_xor:
1571 case AtomicExpr::AO__atomic_fetch_and:
1572 case AtomicExpr::AO__atomic_fetch_or:
1573 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001574 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001575 case AtomicExpr::AO__atomic_and_fetch:
1576 case AtomicExpr::AO__atomic_or_fetch:
1577 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001578 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001579 Form = Arithmetic;
1580 break;
1581
1582 case AtomicExpr::AO__c11_atomic_exchange:
1583 case AtomicExpr::AO__atomic_exchange_n:
1584 Form = Xchg;
1585 break;
1586
1587 case AtomicExpr::AO__atomic_exchange:
1588 Form = GNUXchg;
1589 break;
1590
1591 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1592 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1593 Form = C11CmpXchg;
1594 break;
1595
1596 case AtomicExpr::AO__atomic_compare_exchange:
1597 case AtomicExpr::AO__atomic_compare_exchange_n:
1598 Form = GNUCmpXchg;
1599 break;
1600 }
1601
1602 // Check we have the right number of arguments.
1603 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001604 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001605 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001606 << TheCall->getCallee()->getSourceRange();
1607 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001608 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1609 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001610 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001611 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001612 << TheCall->getCallee()->getSourceRange();
1613 return ExprError();
1614 }
1615
Richard Smithfeea8832012-04-12 05:08:17 +00001616 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001617 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001618 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1619 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1620 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001621 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001622 << Ptr->getType() << Ptr->getSourceRange();
1623 return ExprError();
1624 }
1625
Richard Smithfeea8832012-04-12 05:08:17 +00001626 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1627 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1628 QualType ValType = AtomTy; // 'C'
1629 if (IsC11) {
1630 if (!AtomTy->isAtomicType()) {
1631 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1632 << Ptr->getType() << Ptr->getSourceRange();
1633 return ExprError();
1634 }
Richard Smithe00921a2012-09-15 06:09:58 +00001635 if (AtomTy.isConstQualified()) {
1636 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1637 << Ptr->getType() << Ptr->getSourceRange();
1638 return ExprError();
1639 }
Richard Smithfeea8832012-04-12 05:08:17 +00001640 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001641 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001642
Richard Smithfeea8832012-04-12 05:08:17 +00001643 // For an arithmetic operation, the implied arithmetic must be well-formed.
1644 if (Form == Arithmetic) {
1645 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1646 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1647 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1648 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1649 return ExprError();
1650 }
1651 if (!IsAddSub && !ValType->isIntegerType()) {
1652 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1653 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1654 return ExprError();
1655 }
David Majnemere85cff82015-01-28 05:48:06 +00001656 if (IsC11 && ValType->isPointerType() &&
1657 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1658 diag::err_incomplete_type)) {
1659 return ExprError();
1660 }
Richard Smithfeea8832012-04-12 05:08:17 +00001661 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1662 // For __atomic_*_n operations, the value type must be a scalar integral or
1663 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001664 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001665 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1666 return ExprError();
1667 }
1668
Eli Friedmanaa769812013-09-11 03:49:34 +00001669 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1670 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001671 // For GNU atomics, require a trivially-copyable type. This is not part of
1672 // the GNU atomics specification, but we enforce it for sanity.
1673 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001674 << Ptr->getType() << Ptr->getSourceRange();
1675 return ExprError();
1676 }
1677
Richard Smithfeea8832012-04-12 05:08:17 +00001678 // FIXME: For any builtin other than a load, the ValType must not be
1679 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001680
1681 switch (ValType.getObjCLifetime()) {
1682 case Qualifiers::OCL_None:
1683 case Qualifiers::OCL_ExplicitNone:
1684 // okay
1685 break;
1686
1687 case Qualifiers::OCL_Weak:
1688 case Qualifiers::OCL_Strong:
1689 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001690 // FIXME: Can this happen? By this point, ValType should be known
1691 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001692 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1693 << ValType << Ptr->getSourceRange();
1694 return ExprError();
1695 }
1696
David Majnemerc6eb6502015-06-03 00:26:35 +00001697 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
1698 // volatile-ness of the pointee-type inject itself into the result or the
1699 // other operands.
1700 ValType.removeLocalVolatile();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001701 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001702 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001703 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001704 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001705 ResultType = Context.BoolTy;
1706
Richard Smithfeea8832012-04-12 05:08:17 +00001707 // The type of a parameter passed 'by value'. In the GNU atomics, such
1708 // arguments are actually passed as pointers.
1709 QualType ByValType = ValType; // 'CP'
1710 if (!IsC11 && !IsN)
1711 ByValType = Ptr->getType();
1712
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001713 // The first argument --- the pointer --- has a fixed type; we
1714 // deduce the types of the rest of the arguments accordingly. Walk
1715 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001716 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001717 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001718 if (i < NumVals[Form] + 1) {
1719 switch (i) {
1720 case 1:
1721 // The second argument is the non-atomic operand. For arithmetic, this
1722 // is always passed by value, and for a compare_exchange it is always
1723 // passed by address. For the rest, GNU uses by-address and C11 uses
1724 // by-value.
1725 assert(Form != Load);
1726 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1727 Ty = ValType;
1728 else if (Form == Copy || Form == Xchg)
1729 Ty = ByValType;
1730 else if (Form == Arithmetic)
1731 Ty = Context.getPointerDiffType();
1732 else
1733 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1734 break;
1735 case 2:
1736 // The third argument to compare_exchange / GNU exchange is a
1737 // (pointer to a) desired value.
1738 Ty = ByValType;
1739 break;
1740 case 3:
1741 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1742 Ty = Context.BoolTy;
1743 break;
1744 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001745 } else {
1746 // The order(s) are always converted to int.
1747 Ty = Context.IntTy;
1748 }
Richard Smithfeea8832012-04-12 05:08:17 +00001749
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001750 InitializedEntity Entity =
1751 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001752 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001753 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1754 if (Arg.isInvalid())
1755 return true;
1756 TheCall->setArg(i, Arg.get());
1757 }
1758
Richard Smithfeea8832012-04-12 05:08:17 +00001759 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001760 SmallVector<Expr*, 5> SubExprs;
1761 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001762 switch (Form) {
1763 case Init:
1764 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001765 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001766 break;
1767 case Load:
1768 SubExprs.push_back(TheCall->getArg(1)); // Order
1769 break;
1770 case Copy:
1771 case Arithmetic:
1772 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001773 SubExprs.push_back(TheCall->getArg(2)); // Order
1774 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001775 break;
1776 case GNUXchg:
1777 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1778 SubExprs.push_back(TheCall->getArg(3)); // Order
1779 SubExprs.push_back(TheCall->getArg(1)); // Val1
1780 SubExprs.push_back(TheCall->getArg(2)); // Val2
1781 break;
1782 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001783 SubExprs.push_back(TheCall->getArg(3)); // Order
1784 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001785 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001786 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001787 break;
1788 case GNUCmpXchg:
1789 SubExprs.push_back(TheCall->getArg(4)); // Order
1790 SubExprs.push_back(TheCall->getArg(1)); // Val1
1791 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1792 SubExprs.push_back(TheCall->getArg(2)); // Val2
1793 SubExprs.push_back(TheCall->getArg(3)); // Weak
1794 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001795 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001796
1797 if (SubExprs.size() >= 2 && Form != Init) {
1798 llvm::APSInt Result(32);
1799 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1800 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001801 Diag(SubExprs[1]->getLocStart(),
1802 diag::warn_atomic_op_has_invalid_memory_order)
1803 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001804 }
1805
Fariborz Jahanian615de762013-05-28 17:37:39 +00001806 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1807 SubExprs, ResultType, Op,
1808 TheCall->getRParenLoc());
1809
1810 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1811 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1812 Context.AtomicUsesUnsupportedLibcall(AE))
1813 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1814 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001815
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001816 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001817}
1818
1819
John McCall29ad95b2011-08-27 01:09:30 +00001820/// checkBuiltinArgument - Given a call to a builtin function, perform
1821/// normal type-checking on the given argument, updating the call in
1822/// place. This is useful when a builtin function requires custom
1823/// type-checking for some of its arguments but not necessarily all of
1824/// them.
1825///
1826/// Returns true on error.
1827static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1828 FunctionDecl *Fn = E->getDirectCallee();
1829 assert(Fn && "builtin call without direct callee!");
1830
1831 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1832 InitializedEntity Entity =
1833 InitializedEntity::InitializeParameter(S.Context, Param);
1834
1835 ExprResult Arg = E->getArg(0);
1836 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1837 if (Arg.isInvalid())
1838 return true;
1839
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001840 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001841 return false;
1842}
1843
Chris Lattnerdc046542009-05-08 06:58:22 +00001844/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1845/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1846/// type of its first argument. The main ActOnCallExpr routines have already
1847/// promoted the types of arguments because all of these calls are prototyped as
1848/// void(...).
1849///
1850/// This function goes through and does final semantic checking for these
1851/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001852ExprResult
1853Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001854 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001855 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1856 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1857
1858 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001859 if (TheCall->getNumArgs() < 1) {
1860 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1861 << 0 << 1 << TheCall->getNumArgs()
1862 << TheCall->getCallee()->getSourceRange();
1863 return ExprError();
1864 }
Mike Stump11289f42009-09-09 15:08:12 +00001865
Chris Lattnerdc046542009-05-08 06:58:22 +00001866 // Inspect the first argument of the atomic builtin. This should always be
1867 // a pointer type, whose element is an integral scalar or pointer type.
1868 // Because it is a pointer type, we don't have to worry about any implicit
1869 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001870 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001871 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001872 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1873 if (FirstArgResult.isInvalid())
1874 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001875 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001876 TheCall->setArg(0, FirstArg);
1877
John McCall31168b02011-06-15 23:02:42 +00001878 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1879 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001880 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1881 << FirstArg->getType() << FirstArg->getSourceRange();
1882 return ExprError();
1883 }
Mike Stump11289f42009-09-09 15:08:12 +00001884
John McCall31168b02011-06-15 23:02:42 +00001885 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001886 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001887 !ValType->isBlockPointerType()) {
1888 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1889 << FirstArg->getType() << FirstArg->getSourceRange();
1890 return ExprError();
1891 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001892
John McCall31168b02011-06-15 23:02:42 +00001893 switch (ValType.getObjCLifetime()) {
1894 case Qualifiers::OCL_None:
1895 case Qualifiers::OCL_ExplicitNone:
1896 // okay
1897 break;
1898
1899 case Qualifiers::OCL_Weak:
1900 case Qualifiers::OCL_Strong:
1901 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001902 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001903 << ValType << FirstArg->getSourceRange();
1904 return ExprError();
1905 }
1906
John McCallb50451a2011-10-05 07:41:44 +00001907 // Strip any qualifiers off ValType.
1908 ValType = ValType.getUnqualifiedType();
1909
Chandler Carruth3973af72010-07-18 20:54:12 +00001910 // The majority of builtins return a value, but a few have special return
1911 // types, so allow them to override appropriately below.
1912 QualType ResultType = ValType;
1913
Chris Lattnerdc046542009-05-08 06:58:22 +00001914 // We need to figure out which concrete builtin this maps onto. For example,
1915 // __sync_fetch_and_add with a 2 byte object turns into
1916 // __sync_fetch_and_add_2.
1917#define BUILTIN_ROW(x) \
1918 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1919 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001920
Chris Lattnerdc046542009-05-08 06:58:22 +00001921 static const unsigned BuiltinIndices[][5] = {
1922 BUILTIN_ROW(__sync_fetch_and_add),
1923 BUILTIN_ROW(__sync_fetch_and_sub),
1924 BUILTIN_ROW(__sync_fetch_and_or),
1925 BUILTIN_ROW(__sync_fetch_and_and),
1926 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00001927 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00001928
Chris Lattnerdc046542009-05-08 06:58:22 +00001929 BUILTIN_ROW(__sync_add_and_fetch),
1930 BUILTIN_ROW(__sync_sub_and_fetch),
1931 BUILTIN_ROW(__sync_and_and_fetch),
1932 BUILTIN_ROW(__sync_or_and_fetch),
1933 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00001934 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001935
Chris Lattnerdc046542009-05-08 06:58:22 +00001936 BUILTIN_ROW(__sync_val_compare_and_swap),
1937 BUILTIN_ROW(__sync_bool_compare_and_swap),
1938 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001939 BUILTIN_ROW(__sync_lock_release),
1940 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001941 };
Mike Stump11289f42009-09-09 15:08:12 +00001942#undef BUILTIN_ROW
1943
Chris Lattnerdc046542009-05-08 06:58:22 +00001944 // Determine the index of the size.
1945 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001946 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001947 case 1: SizeIndex = 0; break;
1948 case 2: SizeIndex = 1; break;
1949 case 4: SizeIndex = 2; break;
1950 case 8: SizeIndex = 3; break;
1951 case 16: SizeIndex = 4; break;
1952 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001953 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1954 << FirstArg->getType() << FirstArg->getSourceRange();
1955 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001956 }
Mike Stump11289f42009-09-09 15:08:12 +00001957
Chris Lattnerdc046542009-05-08 06:58:22 +00001958 // Each of these builtins has one pointer argument, followed by some number of
1959 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1960 // that we ignore. Find out which row of BuiltinIndices to read from as well
1961 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001962 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001963 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00001964 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00001965 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001966 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001967 case Builtin::BI__sync_fetch_and_add:
1968 case Builtin::BI__sync_fetch_and_add_1:
1969 case Builtin::BI__sync_fetch_and_add_2:
1970 case Builtin::BI__sync_fetch_and_add_4:
1971 case Builtin::BI__sync_fetch_and_add_8:
1972 case Builtin::BI__sync_fetch_and_add_16:
1973 BuiltinIndex = 0;
1974 break;
1975
1976 case Builtin::BI__sync_fetch_and_sub:
1977 case Builtin::BI__sync_fetch_and_sub_1:
1978 case Builtin::BI__sync_fetch_and_sub_2:
1979 case Builtin::BI__sync_fetch_and_sub_4:
1980 case Builtin::BI__sync_fetch_and_sub_8:
1981 case Builtin::BI__sync_fetch_and_sub_16:
1982 BuiltinIndex = 1;
1983 break;
1984
1985 case Builtin::BI__sync_fetch_and_or:
1986 case Builtin::BI__sync_fetch_and_or_1:
1987 case Builtin::BI__sync_fetch_and_or_2:
1988 case Builtin::BI__sync_fetch_and_or_4:
1989 case Builtin::BI__sync_fetch_and_or_8:
1990 case Builtin::BI__sync_fetch_and_or_16:
1991 BuiltinIndex = 2;
1992 break;
1993
1994 case Builtin::BI__sync_fetch_and_and:
1995 case Builtin::BI__sync_fetch_and_and_1:
1996 case Builtin::BI__sync_fetch_and_and_2:
1997 case Builtin::BI__sync_fetch_and_and_4:
1998 case Builtin::BI__sync_fetch_and_and_8:
1999 case Builtin::BI__sync_fetch_and_and_16:
2000 BuiltinIndex = 3;
2001 break;
Mike Stump11289f42009-09-09 15:08:12 +00002002
Douglas Gregor73722482011-11-28 16:30:08 +00002003 case Builtin::BI__sync_fetch_and_xor:
2004 case Builtin::BI__sync_fetch_and_xor_1:
2005 case Builtin::BI__sync_fetch_and_xor_2:
2006 case Builtin::BI__sync_fetch_and_xor_4:
2007 case Builtin::BI__sync_fetch_and_xor_8:
2008 case Builtin::BI__sync_fetch_and_xor_16:
2009 BuiltinIndex = 4;
2010 break;
2011
Hal Finkeld2208b52014-10-02 20:53:50 +00002012 case Builtin::BI__sync_fetch_and_nand:
2013 case Builtin::BI__sync_fetch_and_nand_1:
2014 case Builtin::BI__sync_fetch_and_nand_2:
2015 case Builtin::BI__sync_fetch_and_nand_4:
2016 case Builtin::BI__sync_fetch_and_nand_8:
2017 case Builtin::BI__sync_fetch_and_nand_16:
2018 BuiltinIndex = 5;
2019 WarnAboutSemanticsChange = true;
2020 break;
2021
Douglas Gregor73722482011-11-28 16:30:08 +00002022 case Builtin::BI__sync_add_and_fetch:
2023 case Builtin::BI__sync_add_and_fetch_1:
2024 case Builtin::BI__sync_add_and_fetch_2:
2025 case Builtin::BI__sync_add_and_fetch_4:
2026 case Builtin::BI__sync_add_and_fetch_8:
2027 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002028 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002029 break;
2030
2031 case Builtin::BI__sync_sub_and_fetch:
2032 case Builtin::BI__sync_sub_and_fetch_1:
2033 case Builtin::BI__sync_sub_and_fetch_2:
2034 case Builtin::BI__sync_sub_and_fetch_4:
2035 case Builtin::BI__sync_sub_and_fetch_8:
2036 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002037 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002038 break;
2039
2040 case Builtin::BI__sync_and_and_fetch:
2041 case Builtin::BI__sync_and_and_fetch_1:
2042 case Builtin::BI__sync_and_and_fetch_2:
2043 case Builtin::BI__sync_and_and_fetch_4:
2044 case Builtin::BI__sync_and_and_fetch_8:
2045 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002046 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002047 break;
2048
2049 case Builtin::BI__sync_or_and_fetch:
2050 case Builtin::BI__sync_or_and_fetch_1:
2051 case Builtin::BI__sync_or_and_fetch_2:
2052 case Builtin::BI__sync_or_and_fetch_4:
2053 case Builtin::BI__sync_or_and_fetch_8:
2054 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002055 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002056 break;
2057
2058 case Builtin::BI__sync_xor_and_fetch:
2059 case Builtin::BI__sync_xor_and_fetch_1:
2060 case Builtin::BI__sync_xor_and_fetch_2:
2061 case Builtin::BI__sync_xor_and_fetch_4:
2062 case Builtin::BI__sync_xor_and_fetch_8:
2063 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002064 BuiltinIndex = 10;
2065 break;
2066
2067 case Builtin::BI__sync_nand_and_fetch:
2068 case Builtin::BI__sync_nand_and_fetch_1:
2069 case Builtin::BI__sync_nand_and_fetch_2:
2070 case Builtin::BI__sync_nand_and_fetch_4:
2071 case Builtin::BI__sync_nand_and_fetch_8:
2072 case Builtin::BI__sync_nand_and_fetch_16:
2073 BuiltinIndex = 11;
2074 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002075 break;
Mike Stump11289f42009-09-09 15:08:12 +00002076
Chris Lattnerdc046542009-05-08 06:58:22 +00002077 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002078 case Builtin::BI__sync_val_compare_and_swap_1:
2079 case Builtin::BI__sync_val_compare_and_swap_2:
2080 case Builtin::BI__sync_val_compare_and_swap_4:
2081 case Builtin::BI__sync_val_compare_and_swap_8:
2082 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002083 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002084 NumFixed = 2;
2085 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002086
Chris Lattnerdc046542009-05-08 06:58:22 +00002087 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002088 case Builtin::BI__sync_bool_compare_and_swap_1:
2089 case Builtin::BI__sync_bool_compare_and_swap_2:
2090 case Builtin::BI__sync_bool_compare_and_swap_4:
2091 case Builtin::BI__sync_bool_compare_and_swap_8:
2092 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002093 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002094 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002095 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002096 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002097
2098 case Builtin::BI__sync_lock_test_and_set:
2099 case Builtin::BI__sync_lock_test_and_set_1:
2100 case Builtin::BI__sync_lock_test_and_set_2:
2101 case Builtin::BI__sync_lock_test_and_set_4:
2102 case Builtin::BI__sync_lock_test_and_set_8:
2103 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002104 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002105 break;
2106
Chris Lattnerdc046542009-05-08 06:58:22 +00002107 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002108 case Builtin::BI__sync_lock_release_1:
2109 case Builtin::BI__sync_lock_release_2:
2110 case Builtin::BI__sync_lock_release_4:
2111 case Builtin::BI__sync_lock_release_8:
2112 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002113 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002114 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002115 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002116 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002117
2118 case Builtin::BI__sync_swap:
2119 case Builtin::BI__sync_swap_1:
2120 case Builtin::BI__sync_swap_2:
2121 case Builtin::BI__sync_swap_4:
2122 case Builtin::BI__sync_swap_8:
2123 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002124 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002125 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002126 }
Mike Stump11289f42009-09-09 15:08:12 +00002127
Chris Lattnerdc046542009-05-08 06:58:22 +00002128 // Now that we know how many fixed arguments we expect, first check that we
2129 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002130 if (TheCall->getNumArgs() < 1+NumFixed) {
2131 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2132 << 0 << 1+NumFixed << TheCall->getNumArgs()
2133 << TheCall->getCallee()->getSourceRange();
2134 return ExprError();
2135 }
Mike Stump11289f42009-09-09 15:08:12 +00002136
Hal Finkeld2208b52014-10-02 20:53:50 +00002137 if (WarnAboutSemanticsChange) {
2138 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2139 << TheCall->getCallee()->getSourceRange();
2140 }
2141
Chris Lattner5b9241b2009-05-08 15:36:58 +00002142 // Get the decl for the concrete builtin from this, we can tell what the
2143 // concrete integer type we should convert to is.
2144 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
2145 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002146 FunctionDecl *NewBuiltinDecl;
2147 if (NewBuiltinID == BuiltinID)
2148 NewBuiltinDecl = FDecl;
2149 else {
2150 // Perform builtin lookup to avoid redeclaring it.
2151 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2152 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2153 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2154 assert(Res.getFoundDecl());
2155 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00002156 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002157 return ExprError();
2158 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002159
John McCallcf142162010-08-07 06:22:56 +00002160 // The first argument --- the pointer --- has a fixed type; we
2161 // deduce the types of the rest of the arguments accordingly. Walk
2162 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00002163 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002164 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002165
Chris Lattnerdc046542009-05-08 06:58:22 +00002166 // GCC does an implicit conversion to the pointer or integer ValType. This
2167 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002168 // Initialize the argument.
2169 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2170 ValType, /*consume*/ false);
2171 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002172 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002173 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002174
Chris Lattnerdc046542009-05-08 06:58:22 +00002175 // Okay, we have something that *can* be converted to the right type. Check
2176 // to see if there is a potentially weird extension going on here. This can
2177 // happen when you do an atomic operation on something like an char* and
2178 // pass in 42. The 42 gets converted to char. This is even more strange
2179 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002180 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002181 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002182 }
Mike Stump11289f42009-09-09 15:08:12 +00002183
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002184 ASTContext& Context = this->getASTContext();
2185
2186 // Create a new DeclRefExpr to refer to the new decl.
2187 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2188 Context,
2189 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002190 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002191 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002192 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002193 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002194 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002195 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002196
Chris Lattnerdc046542009-05-08 06:58:22 +00002197 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002198 // FIXME: This loses syntactic information.
2199 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2200 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2201 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002202 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002203
Chandler Carruthbc8cab12010-07-18 07:23:17 +00002204 // Change the result type of the call to match the original value type. This
2205 // is arbitrary, but the codegen for these builtins ins design to handle it
2206 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00002207 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002208
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002209 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002210}
2211
Chris Lattner6436fb62009-02-18 06:01:06 +00002212/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002213/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002214/// Note: It might also make sense to do the UTF-16 conversion here (would
2215/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002216bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002217 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002218 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2219
Douglas Gregorfb65e592011-07-27 05:40:30 +00002220 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002221 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2222 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002223 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002224 }
Mike Stump11289f42009-09-09 15:08:12 +00002225
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002226 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002227 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002228 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002229 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002230 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002231 UTF16 *ToPtr = &ToBuf[0];
2232
2233 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2234 &ToPtr, ToPtr + NumBytes,
2235 strictConversion);
2236 // Check for conversion failure.
2237 if (Result != conversionOK)
2238 Diag(Arg->getLocStart(),
2239 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2240 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002241 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002242}
2243
Chris Lattnere202e6a2007-12-20 00:05:45 +00002244/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
2245/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00002246bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2247 Expr *Fn = TheCall->getCallee();
2248 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002249 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002250 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002251 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2252 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002253 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002254 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002255 return true;
2256 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002257
2258 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002259 return Diag(TheCall->getLocEnd(),
2260 diag::err_typecheck_call_too_few_args_at_least)
2261 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002262 }
2263
John McCall29ad95b2011-08-27 01:09:30 +00002264 // Type-check the first argument normally.
2265 if (checkBuiltinArgument(*this, TheCall, 0))
2266 return true;
2267
Chris Lattnere202e6a2007-12-20 00:05:45 +00002268 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002269 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002270 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002271 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002272 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002273 else if (FunctionDecl *FD = getCurFunctionDecl())
2274 isVariadic = FD->isVariadic();
2275 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002276 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002277
Chris Lattnere202e6a2007-12-20 00:05:45 +00002278 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002279 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2280 return true;
2281 }
Mike Stump11289f42009-09-09 15:08:12 +00002282
Chris Lattner43be2e62007-12-19 23:59:04 +00002283 // Verify that the second argument to the builtin is the last argument of the
2284 // current function or method.
2285 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002286 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002287
Nico Weber9eea7642013-05-24 23:31:57 +00002288 // These are valid if SecondArgIsLastNamedArgument is false after the next
2289 // block.
2290 QualType Type;
2291 SourceLocation ParamLoc;
2292
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002293 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2294 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002295 // FIXME: This isn't correct for methods (results in bogus warning).
2296 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002297 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002298 if (CurBlock)
2299 LastArg = *(CurBlock->TheDecl->param_end()-1);
2300 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002301 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002302 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002303 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002304 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002305
2306 Type = PV->getType();
2307 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002308 }
2309 }
Mike Stump11289f42009-09-09 15:08:12 +00002310
Chris Lattner43be2e62007-12-19 23:59:04 +00002311 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002312 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002313 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002314 else if (Type->isReferenceType()) {
2315 Diag(Arg->getLocStart(),
2316 diag::warn_va_start_of_reference_type_is_undefined);
2317 Diag(ParamLoc, diag::note_parameter_type) << Type;
2318 }
2319
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002320 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002321 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002322}
Chris Lattner43be2e62007-12-19 23:59:04 +00002323
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002324bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2325 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2326 // const char *named_addr);
2327
2328 Expr *Func = Call->getCallee();
2329
2330 if (Call->getNumArgs() < 3)
2331 return Diag(Call->getLocEnd(),
2332 diag::err_typecheck_call_too_few_args_at_least)
2333 << 0 /*function call*/ << 3 << Call->getNumArgs();
2334
2335 // Determine whether the current function is variadic or not.
2336 bool IsVariadic;
2337 if (BlockScopeInfo *CurBlock = getCurBlock())
2338 IsVariadic = CurBlock->TheDecl->isVariadic();
2339 else if (FunctionDecl *FD = getCurFunctionDecl())
2340 IsVariadic = FD->isVariadic();
2341 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2342 IsVariadic = MD->isVariadic();
2343 else
2344 llvm_unreachable("unexpected statement type");
2345
2346 if (!IsVariadic) {
2347 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2348 return true;
2349 }
2350
2351 // Type-check the first argument normally.
2352 if (checkBuiltinArgument(*this, Call, 0))
2353 return true;
2354
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002355 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002356 unsigned ArgNo;
2357 QualType Type;
2358 } ArgumentTypes[] = {
2359 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2360 { 2, Context.getSizeType() },
2361 };
2362
2363 for (const auto &AT : ArgumentTypes) {
2364 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2365 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2366 continue;
2367 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2368 << Arg->getType() << AT.Type << 1 /* different class */
2369 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2370 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2371 }
2372
2373 return false;
2374}
2375
Chris Lattner2da14fb2007-12-20 00:26:33 +00002376/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2377/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002378bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2379 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002380 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002381 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002382 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002383 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002384 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002385 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002386 << SourceRange(TheCall->getArg(2)->getLocStart(),
2387 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002388
John Wiegley01296292011-04-08 18:41:53 +00002389 ExprResult OrigArg0 = TheCall->getArg(0);
2390 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002391
Chris Lattner2da14fb2007-12-20 00:26:33 +00002392 // Do standard promotions between the two arguments, returning their common
2393 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002394 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002395 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2396 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002397
2398 // Make sure any conversions are pushed back into the call; this is
2399 // type safe since unordered compare builtins are declared as "_Bool
2400 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002401 TheCall->setArg(0, OrigArg0.get());
2402 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002403
John Wiegley01296292011-04-08 18:41:53 +00002404 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002405 return false;
2406
Chris Lattner2da14fb2007-12-20 00:26:33 +00002407 // If the common type isn't a real floating type, then the arguments were
2408 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002409 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002410 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002411 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002412 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2413 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002414
Chris Lattner2da14fb2007-12-20 00:26:33 +00002415 return false;
2416}
2417
Benjamin Kramer634fc102010-02-15 22:42:31 +00002418/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2419/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002420/// to check everything. We expect the last argument to be a floating point
2421/// value.
2422bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2423 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002424 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002425 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002426 if (TheCall->getNumArgs() > NumArgs)
2427 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002428 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002429 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002430 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002431 (*(TheCall->arg_end()-1))->getLocEnd());
2432
Benjamin Kramer64aae502010-02-16 10:07:31 +00002433 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002434
Eli Friedman7e4faac2009-08-31 20:06:00 +00002435 if (OrigArg->isTypeDependent())
2436 return false;
2437
Chris Lattner68784ef2010-05-06 05:50:07 +00002438 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002439 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002440 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002441 diag::err_typecheck_call_invalid_unary_fp)
2442 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002443
Chris Lattner68784ef2010-05-06 05:50:07 +00002444 // If this is an implicit conversion from float -> double, remove it.
2445 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2446 Expr *CastArg = Cast->getSubExpr();
2447 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2448 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2449 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002450 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002451 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002452 }
2453 }
2454
Eli Friedman7e4faac2009-08-31 20:06:00 +00002455 return false;
2456}
2457
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002458/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2459// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002460ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002461 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002462 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002463 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002464 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2465 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002466
Nate Begemana0110022010-06-08 00:16:34 +00002467 // Determine which of the following types of shufflevector we're checking:
2468 // 1) unary, vector mask: (lhs, mask)
2469 // 2) binary, vector mask: (lhs, rhs, mask)
2470 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2471 QualType resType = TheCall->getArg(0)->getType();
2472 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002473
Douglas Gregorc25f7662009-05-19 22:10:17 +00002474 if (!TheCall->getArg(0)->isTypeDependent() &&
2475 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002476 QualType LHSType = TheCall->getArg(0)->getType();
2477 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002478
Craig Topperbaca3892013-07-29 06:47:04 +00002479 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2480 return ExprError(Diag(TheCall->getLocStart(),
2481 diag::err_shufflevector_non_vector)
2482 << SourceRange(TheCall->getArg(0)->getLocStart(),
2483 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002484
Nate Begemana0110022010-06-08 00:16:34 +00002485 numElements = LHSType->getAs<VectorType>()->getNumElements();
2486 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002487
Nate Begemana0110022010-06-08 00:16:34 +00002488 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2489 // with mask. If so, verify that RHS is an integer vector type with the
2490 // same number of elts as lhs.
2491 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002492 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002493 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002494 return ExprError(Diag(TheCall->getLocStart(),
2495 diag::err_shufflevector_incompatible_vector)
2496 << SourceRange(TheCall->getArg(1)->getLocStart(),
2497 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002498 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002499 return ExprError(Diag(TheCall->getLocStart(),
2500 diag::err_shufflevector_incompatible_vector)
2501 << SourceRange(TheCall->getArg(0)->getLocStart(),
2502 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002503 } else if (numElements != numResElements) {
2504 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002505 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002506 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002507 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002508 }
2509
2510 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002511 if (TheCall->getArg(i)->isTypeDependent() ||
2512 TheCall->getArg(i)->isValueDependent())
2513 continue;
2514
Nate Begemana0110022010-06-08 00:16:34 +00002515 llvm::APSInt Result(32);
2516 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2517 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002518 diag::err_shufflevector_nonconstant_argument)
2519 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002520
Craig Topper50ad5b72013-08-03 17:40:38 +00002521 // Allow -1 which will be translated to undef in the IR.
2522 if (Result.isSigned() && Result.isAllOnesValue())
2523 continue;
2524
Chris Lattner7ab824e2008-08-10 02:05:13 +00002525 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002526 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002527 diag::err_shufflevector_argument_too_large)
2528 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002529 }
2530
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002531 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002532
Chris Lattner7ab824e2008-08-10 02:05:13 +00002533 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002534 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002535 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002536 }
2537
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002538 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2539 TheCall->getCallee()->getLocStart(),
2540 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002541}
Chris Lattner43be2e62007-12-19 23:59:04 +00002542
Hal Finkelc4d7c822013-09-18 03:29:45 +00002543/// SemaConvertVectorExpr - Handle __builtin_convertvector
2544ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2545 SourceLocation BuiltinLoc,
2546 SourceLocation RParenLoc) {
2547 ExprValueKind VK = VK_RValue;
2548 ExprObjectKind OK = OK_Ordinary;
2549 QualType DstTy = TInfo->getType();
2550 QualType SrcTy = E->getType();
2551
2552 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2553 return ExprError(Diag(BuiltinLoc,
2554 diag::err_convertvector_non_vector)
2555 << E->getSourceRange());
2556 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2557 return ExprError(Diag(BuiltinLoc,
2558 diag::err_convertvector_non_vector_type));
2559
2560 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2561 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2562 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2563 if (SrcElts != DstElts)
2564 return ExprError(Diag(BuiltinLoc,
2565 diag::err_convertvector_incompatible_vector)
2566 << E->getSourceRange());
2567 }
2568
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002569 return new (Context)
2570 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002571}
2572
Daniel Dunbarb7257262008-07-21 22:59:13 +00002573/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2574// This is declared to take (const void*, ...) and can take two
2575// optional constant int args.
2576bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002577 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002578
Chris Lattner3b054132008-11-19 05:08:23 +00002579 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002580 return Diag(TheCall->getLocEnd(),
2581 diag::err_typecheck_call_too_many_args_at_most)
2582 << 0 /*function call*/ << 3 << NumArgs
2583 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002584
2585 // Argument 0 is checked for us and the remaining arguments must be
2586 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002587 for (unsigned i = 1; i != NumArgs; ++i)
2588 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002589 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002590
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002591 return false;
2592}
2593
Hal Finkelf0417332014-07-17 14:25:55 +00002594/// SemaBuiltinAssume - Handle __assume (MS Extension).
2595// __assume does not evaluate its arguments, and should warn if its argument
2596// has side effects.
2597bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2598 Expr *Arg = TheCall->getArg(0);
2599 if (Arg->isInstantiationDependent()) return false;
2600
2601 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00002602 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002603 << Arg->getSourceRange()
2604 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2605
2606 return false;
2607}
2608
2609/// Handle __builtin_assume_aligned. This is declared
2610/// as (const void*, size_t, ...) and can take one optional constant int arg.
2611bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2612 unsigned NumArgs = TheCall->getNumArgs();
2613
2614 if (NumArgs > 3)
2615 return Diag(TheCall->getLocEnd(),
2616 diag::err_typecheck_call_too_many_args_at_most)
2617 << 0 /*function call*/ << 3 << NumArgs
2618 << TheCall->getSourceRange();
2619
2620 // The alignment must be a constant integer.
2621 Expr *Arg = TheCall->getArg(1);
2622
2623 // We can't check the value of a dependent argument.
2624 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2625 llvm::APSInt Result;
2626 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2627 return true;
2628
2629 if (!Result.isPowerOf2())
2630 return Diag(TheCall->getLocStart(),
2631 diag::err_alignment_not_power_of_two)
2632 << Arg->getSourceRange();
2633 }
2634
2635 if (NumArgs > 2) {
2636 ExprResult Arg(TheCall->getArg(2));
2637 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2638 Context.getSizeType(), false);
2639 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2640 if (Arg.isInvalid()) return true;
2641 TheCall->setArg(2, Arg.get());
2642 }
Hal Finkelf0417332014-07-17 14:25:55 +00002643
2644 return false;
2645}
2646
Eric Christopher8d0c6212010-04-17 02:26:23 +00002647/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2648/// TheCall is a constant expression.
2649bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2650 llvm::APSInt &Result) {
2651 Expr *Arg = TheCall->getArg(ArgNum);
2652 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2653 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2654
2655 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2656
2657 if (!Arg->isIntegerConstantExpr(Result, Context))
2658 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002659 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002660
Chris Lattnerd545ad12009-09-23 06:06:36 +00002661 return false;
2662}
2663
Richard Sandiford28940af2014-04-16 08:47:51 +00002664/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2665/// TheCall is a constant expression in the range [Low, High].
2666bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2667 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002668 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002669
2670 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002671 Expr *Arg = TheCall->getArg(ArgNum);
2672 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002673 return false;
2674
Eric Christopher8d0c6212010-04-17 02:26:23 +00002675 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002676 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002677 return true;
2678
Richard Sandiford28940af2014-04-16 08:47:51 +00002679 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002680 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002681 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002682
2683 return false;
2684}
2685
Luke Cheeseman59b2d832015-06-15 17:51:01 +00002686/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
2687/// TheCall is an ARM/AArch64 special register string literal.
2688bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
2689 int ArgNum, unsigned ExpectedFieldNum,
2690 bool AllowName) {
2691 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2692 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
2693 BuiltinID == ARM::BI__builtin_arm_rsr ||
2694 BuiltinID == ARM::BI__builtin_arm_rsrp ||
2695 BuiltinID == ARM::BI__builtin_arm_wsr ||
2696 BuiltinID == ARM::BI__builtin_arm_wsrp;
2697 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2698 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
2699 BuiltinID == AArch64::BI__builtin_arm_rsr ||
2700 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2701 BuiltinID == AArch64::BI__builtin_arm_wsr ||
2702 BuiltinID == AArch64::BI__builtin_arm_wsrp;
2703 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
2704
2705 // We can't check the value of a dependent argument.
2706 Expr *Arg = TheCall->getArg(ArgNum);
2707 if (Arg->isTypeDependent() || Arg->isValueDependent())
2708 return false;
2709
2710 // Check if the argument is a string literal.
2711 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2712 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2713 << Arg->getSourceRange();
2714
2715 // Check the type of special register given.
2716 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2717 SmallVector<StringRef, 6> Fields;
2718 Reg.split(Fields, ":");
2719
2720 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
2721 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
2722 << Arg->getSourceRange();
2723
2724 // If the string is the name of a register then we cannot check that it is
2725 // valid here but if the string is of one the forms described in ACLE then we
2726 // can check that the supplied fields are integers and within the valid
2727 // ranges.
2728 if (Fields.size() > 1) {
2729 bool FiveFields = Fields.size() == 5;
2730
2731 bool ValidString = true;
2732 if (IsARMBuiltin) {
2733 ValidString &= Fields[0].startswith_lower("cp") ||
2734 Fields[0].startswith_lower("p");
2735 if (ValidString)
2736 Fields[0] =
2737 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
2738
2739 ValidString &= Fields[2].startswith_lower("c");
2740 if (ValidString)
2741 Fields[2] = Fields[2].drop_front(1);
2742
2743 if (FiveFields) {
2744 ValidString &= Fields[3].startswith_lower("c");
2745 if (ValidString)
2746 Fields[3] = Fields[3].drop_front(1);
2747 }
2748 }
2749
2750 SmallVector<int, 5> Ranges;
2751 if (FiveFields)
2752 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
2753 else
2754 Ranges.append({15, 7, 15});
2755
2756 for (unsigned i=0; i<Fields.size(); ++i) {
2757 int IntField;
2758 ValidString &= !Fields[i].getAsInteger(10, IntField);
2759 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
2760 }
2761
2762 if (!ValidString)
2763 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
2764 << Arg->getSourceRange();
2765
2766 } else if (IsAArch64Builtin && Fields.size() == 1) {
2767 // If the register name is one of those that appear in the condition below
2768 // and the special register builtin being used is one of the write builtins,
2769 // then we require that the argument provided for writing to the register
2770 // is an integer constant expression. This is because it will be lowered to
2771 // an MSR (immediate) instruction, so we need to know the immediate at
2772 // compile time.
2773 if (TheCall->getNumArgs() != 2)
2774 return false;
2775
2776 std::string RegLower = Reg.lower();
2777 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
2778 RegLower != "pan" && RegLower != "uao")
2779 return false;
2780
2781 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2782 }
2783
2784 return false;
2785}
2786
Eric Christopherd9832702015-06-29 21:00:05 +00002787/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
2788/// This checks that the target supports __builtin_cpu_supports and
2789/// that the string argument is constant and valid.
2790bool Sema::SemaBuiltinCpuSupports(CallExpr *TheCall) {
2791 Expr *Arg = TheCall->getArg(0);
2792
2793 // Check if the argument is a string literal.
2794 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2795 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2796 << Arg->getSourceRange();
2797
2798 // Check the contents of the string.
2799 StringRef Feature =
2800 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2801 if (!Context.getTargetInfo().validateCpuSupports(Feature))
2802 return Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
2803 << Arg->getSourceRange();
2804 return false;
2805}
2806
Eli Friedmanc97d0142009-05-03 06:04:26 +00002807/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002808/// This checks that the target supports __builtin_longjmp and
2809/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002810bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002811 if (!Context.getTargetInfo().hasSjLjLowering())
2812 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
2813 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2814
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002815 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002816 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002817
Eric Christopher8d0c6212010-04-17 02:26:23 +00002818 // TODO: This is less than ideal. Overload this to take a value.
2819 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2820 return true;
2821
2822 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002823 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2824 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2825
2826 return false;
2827}
2828
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002829
2830/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
2831/// This checks that the target supports __builtin_setjmp.
2832bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
2833 if (!Context.getTargetInfo().hasSjLjLowering())
2834 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
2835 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2836 return false;
2837}
2838
Richard Smithd7293d72013-08-05 18:49:43 +00002839namespace {
2840enum StringLiteralCheckType {
2841 SLCT_NotALiteral,
2842 SLCT_UncheckedLiteral,
2843 SLCT_CheckedLiteral
2844};
2845}
2846
Richard Smith55ce3522012-06-25 20:30:08 +00002847// Determine if an expression is a string literal or constant string.
2848// If this function returns false on the arguments to a function expecting a
2849// format string, we will usually need to emit a warning.
2850// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002851static StringLiteralCheckType
2852checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2853 bool HasVAListArg, unsigned format_idx,
2854 unsigned firstDataArg, Sema::FormatStringType Type,
2855 Sema::VariadicCallType CallType, bool InFunctionCall,
2856 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002857 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002858 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002859 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002860
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002861 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002862
Richard Smithd7293d72013-08-05 18:49:43 +00002863 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002864 // Technically -Wformat-nonliteral does not warn about this case.
2865 // The behavior of printf and friends in this case is implementation
2866 // dependent. Ideally if the format string cannot be null then
2867 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002868 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002869
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002870 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002871 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002872 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002873 // The expression is a literal if both sub-expressions were, and it was
2874 // completely checked only if both sub-expressions were checked.
2875 const AbstractConditionalOperator *C =
2876 cast<AbstractConditionalOperator>(E);
2877 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002878 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002879 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002880 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002881 if (Left == SLCT_NotALiteral)
2882 return SLCT_NotALiteral;
2883 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002884 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002885 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002886 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002887 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002888 }
2889
2890 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002891 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2892 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002893 }
2894
John McCallc07a0c72011-02-17 10:25:35 +00002895 case Stmt::OpaqueValueExprClass:
2896 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2897 E = src;
2898 goto tryAgain;
2899 }
Richard Smith55ce3522012-06-25 20:30:08 +00002900 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002901
Ted Kremeneka8890832011-02-24 23:03:04 +00002902 case Stmt::PredefinedExprClass:
2903 // While __func__, etc., are technically not string literals, they
2904 // cannot contain format specifiers and thus are not a security
2905 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002906 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002907
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002908 case Stmt::DeclRefExprClass: {
2909 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002910
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002911 // As an exception, do not flag errors for variables binding to
2912 // const string literals.
2913 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2914 bool isConstant = false;
2915 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002916
Richard Smithd7293d72013-08-05 18:49:43 +00002917 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2918 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002919 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002920 isConstant = T.isConstant(S.Context) &&
2921 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002922 } else if (T->isObjCObjectPointerType()) {
2923 // In ObjC, there is usually no "const ObjectPointer" type,
2924 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002925 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002926 }
Mike Stump11289f42009-09-09 15:08:12 +00002927
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002928 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002929 if (const Expr *Init = VD->getAnyInitializer()) {
2930 // Look through initializers like const char c[] = { "foo" }
2931 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2932 if (InitList->isStringLiteralInit())
2933 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2934 }
Richard Smithd7293d72013-08-05 18:49:43 +00002935 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002936 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002937 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002938 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002939 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002940 }
Mike Stump11289f42009-09-09 15:08:12 +00002941
Anders Carlssonb012ca92009-06-28 19:55:58 +00002942 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2943 // special check to see if the format string is a function parameter
2944 // of the function calling the printf function. If the function
2945 // has an attribute indicating it is a printf-like function, then we
2946 // should suppress warnings concerning non-literals being used in a call
2947 // to a vprintf function. For example:
2948 //
2949 // void
2950 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2951 // va_list ap;
2952 // va_start(ap, fmt);
2953 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2954 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002955 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002956 if (HasVAListArg) {
2957 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2958 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2959 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002960 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002961 // adjust for implicit parameter
2962 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2963 if (MD->isInstance())
2964 ++PVIndex;
2965 // We also check if the formats are compatible.
2966 // We can't pass a 'scanf' string to a 'printf' function.
2967 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002968 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002969 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002970 }
2971 }
2972 }
2973 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002974 }
Mike Stump11289f42009-09-09 15:08:12 +00002975
Richard Smith55ce3522012-06-25 20:30:08 +00002976 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002977 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002978
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002979 case Stmt::CallExprClass:
2980 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002981 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002982 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2983 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2984 unsigned ArgIndex = FA->getFormatIdx();
2985 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2986 if (MD->isInstance())
2987 --ArgIndex;
2988 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002989
Richard Smithd7293d72013-08-05 18:49:43 +00002990 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002991 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002992 Type, CallType, InFunctionCall,
2993 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002994 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2995 unsigned BuiltinID = FD->getBuiltinID();
2996 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2997 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2998 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002999 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003000 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003001 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003002 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003003 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003004 }
3005 }
Mike Stump11289f42009-09-09 15:08:12 +00003006
Richard Smith55ce3522012-06-25 20:30:08 +00003007 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003008 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003009 case Stmt::ObjCStringLiteralClass:
3010 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00003011 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003012
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003013 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003014 StrE = ObjCFExpr->getString();
3015 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003016 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003017
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003018 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00003019 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
3020 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003021 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003022 }
Mike Stump11289f42009-09-09 15:08:12 +00003023
Richard Smith55ce3522012-06-25 20:30:08 +00003024 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003025 }
Mike Stump11289f42009-09-09 15:08:12 +00003026
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003027 default:
Richard Smith55ce3522012-06-25 20:30:08 +00003028 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003029 }
3030}
3031
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003032Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003033 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003034 .Case("scanf", FST_Scanf)
3035 .Cases("printf", "printf0", FST_Printf)
3036 .Cases("NSString", "CFString", FST_NSString)
3037 .Case("strftime", FST_Strftime)
3038 .Case("strfmon", FST_Strfmon)
3039 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003040 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00003041 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003042 .Default(FST_Unknown);
3043}
3044
Jordan Rose3e0ec582012-07-19 18:10:23 +00003045/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00003046/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003047/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003048bool Sema::CheckFormatArguments(const FormatAttr *Format,
3049 ArrayRef<const Expr *> Args,
3050 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003051 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003052 SourceLocation Loc, SourceRange Range,
3053 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00003054 FormatStringInfo FSI;
3055 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003056 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00003057 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00003058 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003059 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003060}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003061
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003062bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003063 bool HasVAListArg, unsigned format_idx,
3064 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003065 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003066 SourceLocation Loc, SourceRange Range,
3067 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003068 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003069 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003070 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00003071 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003072 }
Mike Stump11289f42009-09-09 15:08:12 +00003073
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003074 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003075
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003076 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00003077 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003078 // Dynamically generated format strings are difficult to
3079 // automatically vet at compile time. Requiring that format strings
3080 // are string literals: (1) permits the checking of format strings by
3081 // the compiler and thereby (2) can practically remove the source of
3082 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00003083
Mike Stump11289f42009-09-09 15:08:12 +00003084 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00003085 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00003086 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00003087 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003088 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00003089 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3090 format_idx, firstDataArg, Type, CallType,
3091 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003092 if (CT != SLCT_NotALiteral)
3093 // Literal format string found, check done!
3094 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00003095
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003096 // Strftime is particular as it always uses a single 'time' argument,
3097 // so it is safe to pass a non-literal string.
3098 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00003099 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003100
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003101 // Do not emit diag when the string param is a macro expansion and the
3102 // format is either NSString or CFString. This is a hack to prevent
3103 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3104 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00003105 if (Type == FST_NSString &&
3106 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00003107 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003108
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003109 // If there are no arguments specified, warn with -Wformat-security, otherwise
3110 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00003111 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003112 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003113 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003114 << OrigFormatExpr->getSourceRange();
3115 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003116 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003117 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003118 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00003119 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003120}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003121
Ted Kremenekab278de2010-01-28 23:39:18 +00003122namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00003123class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3124protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00003125 Sema &S;
3126 const StringLiteral *FExpr;
3127 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003128 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00003129 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00003130 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00003131 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003132 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00003133 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00003134 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00003135 bool usesPositionalArgs;
3136 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003137 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00003138 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00003139 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003140public:
Ted Kremenek02087932010-07-16 02:11:22 +00003141 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003142 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003143 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003144 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003145 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003146 Sema::VariadicCallType callType,
3147 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00003148 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003149 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3150 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003151 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00003152 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00003153 inFunctionCall(inFunctionCall), CallType(callType),
3154 CheckedVarArgs(CheckedVarArgs) {
3155 CoveredArgs.resize(numDataArgs);
3156 CoveredArgs.reset();
3157 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003158
Ted Kremenek019d2242010-01-29 01:50:07 +00003159 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003160
Ted Kremenek02087932010-07-16 02:11:22 +00003161 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003162 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003163
Jordan Rose92303592012-09-08 04:00:03 +00003164 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003165 const analyze_format_string::FormatSpecifier &FS,
3166 const analyze_format_string::ConversionSpecifier &CS,
3167 const char *startSpecifier, unsigned specifierLen,
3168 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00003169
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003170 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003171 const analyze_format_string::FormatSpecifier &FS,
3172 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003173
3174 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003175 const analyze_format_string::ConversionSpecifier &CS,
3176 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003177
Craig Toppere14c0f82014-03-12 04:55:44 +00003178 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003179
Craig Toppere14c0f82014-03-12 04:55:44 +00003180 void HandleInvalidPosition(const char *startSpecifier,
3181 unsigned specifierLen,
3182 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003183
Craig Toppere14c0f82014-03-12 04:55:44 +00003184 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003185
Craig Toppere14c0f82014-03-12 04:55:44 +00003186 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003187
Richard Trieu03cf7b72011-10-28 00:41:25 +00003188 template <typename Range>
3189 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3190 const Expr *ArgumentExpr,
3191 PartialDiagnostic PDiag,
3192 SourceLocation StringLoc,
3193 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003194 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003195
Ted Kremenek02087932010-07-16 02:11:22 +00003196protected:
Ted Kremenekce815422010-07-19 21:25:57 +00003197 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3198 const char *startSpec,
3199 unsigned specifierLen,
3200 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003201
3202 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
3203 const char *startSpec,
3204 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003205
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003206 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00003207 CharSourceRange getSpecifierRange(const char *startSpecifier,
3208 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00003209 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003210
Ted Kremenek5739de72010-01-29 01:06:55 +00003211 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003212
3213 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
3214 const analyze_format_string::ConversionSpecifier &CS,
3215 const char *startSpecifier, unsigned specifierLen,
3216 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003217
3218 template <typename Range>
3219 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3220 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003221 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00003222};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003223}
Ted Kremenekab278de2010-01-28 23:39:18 +00003224
Ted Kremenek02087932010-07-16 02:11:22 +00003225SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00003226 return OrigFormatExpr->getSourceRange();
3227}
3228
Ted Kremenek02087932010-07-16 02:11:22 +00003229CharSourceRange CheckFormatHandler::
3230getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00003231 SourceLocation Start = getLocationOfByte(startSpecifier);
3232 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3233
3234 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003235 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00003236
3237 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003238}
3239
Ted Kremenek02087932010-07-16 02:11:22 +00003240SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003241 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00003242}
3243
Ted Kremenek02087932010-07-16 02:11:22 +00003244void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
3245 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00003246 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
3247 getLocationOfByte(startSpecifier),
3248 /*IsStringLocation*/true,
3249 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00003250}
3251
Jordan Rose92303592012-09-08 04:00:03 +00003252void CheckFormatHandler::HandleInvalidLengthModifier(
3253 const analyze_format_string::FormatSpecifier &FS,
3254 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00003255 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00003256 using namespace analyze_format_string;
3257
3258 const LengthModifier &LM = FS.getLengthModifier();
3259 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3260
3261 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003262 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00003263 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003264 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003265 getLocationOfByte(LM.getStart()),
3266 /*IsStringLocation*/true,
3267 getSpecifierRange(startSpecifier, specifierLen));
3268
3269 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3270 << FixedLM->toString()
3271 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3272
3273 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003274 FixItHint Hint;
3275 if (DiagID == diag::warn_format_nonsensical_length)
3276 Hint = FixItHint::CreateRemoval(LMRange);
3277
3278 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003279 getLocationOfByte(LM.getStart()),
3280 /*IsStringLocation*/true,
3281 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00003282 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00003283 }
3284}
3285
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003286void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00003287 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003288 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003289 using namespace analyze_format_string;
3290
3291 const LengthModifier &LM = FS.getLengthModifier();
3292 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3293
3294 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003295 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00003296 if (FixedLM) {
3297 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3298 << LM.toString() << 0,
3299 getLocationOfByte(LM.getStart()),
3300 /*IsStringLocation*/true,
3301 getSpecifierRange(startSpecifier, specifierLen));
3302
3303 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3304 << FixedLM->toString()
3305 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3306
3307 } else {
3308 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3309 << LM.toString() << 0,
3310 getLocationOfByte(LM.getStart()),
3311 /*IsStringLocation*/true,
3312 getSpecifierRange(startSpecifier, specifierLen));
3313 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003314}
3315
3316void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3317 const analyze_format_string::ConversionSpecifier &CS,
3318 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00003319 using namespace analyze_format_string;
3320
3321 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00003322 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00003323 if (FixedCS) {
3324 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3325 << CS.toString() << /*conversion specifier*/1,
3326 getLocationOfByte(CS.getStart()),
3327 /*IsStringLocation*/true,
3328 getSpecifierRange(startSpecifier, specifierLen));
3329
3330 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3331 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3332 << FixedCS->toString()
3333 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3334 } else {
3335 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3336 << CS.toString() << /*conversion specifier*/1,
3337 getLocationOfByte(CS.getStart()),
3338 /*IsStringLocation*/true,
3339 getSpecifierRange(startSpecifier, specifierLen));
3340 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003341}
3342
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003343void CheckFormatHandler::HandlePosition(const char *startPos,
3344 unsigned posLen) {
3345 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3346 getLocationOfByte(startPos),
3347 /*IsStringLocation*/true,
3348 getSpecifierRange(startPos, posLen));
3349}
3350
Ted Kremenekd1668192010-02-27 01:41:03 +00003351void
Ted Kremenek02087932010-07-16 02:11:22 +00003352CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3353 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003354 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3355 << (unsigned) p,
3356 getLocationOfByte(startPos), /*IsStringLocation*/true,
3357 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003358}
3359
Ted Kremenek02087932010-07-16 02:11:22 +00003360void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003361 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003362 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3363 getLocationOfByte(startPos),
3364 /*IsStringLocation*/true,
3365 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003366}
3367
Ted Kremenek02087932010-07-16 02:11:22 +00003368void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003369 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003370 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003371 EmitFormatDiagnostic(
3372 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3373 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3374 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003375 }
Ted Kremenek02087932010-07-16 02:11:22 +00003376}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003377
Jordan Rose58bbe422012-07-19 18:10:08 +00003378// Note that this may return NULL if there was an error parsing or building
3379// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003380const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003381 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003382}
3383
3384void CheckFormatHandler::DoneProcessing() {
3385 // Does the number of data arguments exceed the number of
3386 // format conversions in the format string?
3387 if (!HasVAListArg) {
3388 // Find any arguments that weren't covered.
3389 CoveredArgs.flip();
3390 signed notCoveredArg = CoveredArgs.find_first();
3391 if (notCoveredArg >= 0) {
3392 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00003393 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3394 SourceLocation Loc = E->getLocStart();
3395 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3396 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3397 Loc, /*IsStringLocation*/false,
3398 getFormatStringRange());
3399 }
Bob Wilson23cd4342012-05-03 19:47:19 +00003400 }
Ted Kremenek02087932010-07-16 02:11:22 +00003401 }
3402 }
3403}
3404
Ted Kremenekce815422010-07-19 21:25:57 +00003405bool
3406CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3407 SourceLocation Loc,
3408 const char *startSpec,
3409 unsigned specifierLen,
3410 const char *csStart,
3411 unsigned csLen) {
3412
3413 bool keepGoing = true;
3414 if (argIndex < NumDataArgs) {
3415 // Consider the argument coverered, even though the specifier doesn't
3416 // make sense.
3417 CoveredArgs.set(argIndex);
3418 }
3419 else {
3420 // If argIndex exceeds the number of data arguments we
3421 // don't issue a warning because that is just a cascade of warnings (and
3422 // they may have intended '%%' anyway). We don't want to continue processing
3423 // the format string after this point, however, as we will like just get
3424 // gibberish when trying to match arguments.
3425 keepGoing = false;
3426 }
3427
Richard Trieu03cf7b72011-10-28 00:41:25 +00003428 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3429 << StringRef(csStart, csLen),
3430 Loc, /*IsStringLocation*/true,
3431 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003432
3433 return keepGoing;
3434}
3435
Richard Trieu03cf7b72011-10-28 00:41:25 +00003436void
3437CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3438 const char *startSpec,
3439 unsigned specifierLen) {
3440 EmitFormatDiagnostic(
3441 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3442 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3443}
3444
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003445bool
3446CheckFormatHandler::CheckNumArgs(
3447 const analyze_format_string::FormatSpecifier &FS,
3448 const analyze_format_string::ConversionSpecifier &CS,
3449 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3450
3451 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003452 PartialDiagnostic PDiag = FS.usesPositionalArg()
3453 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3454 << (argIndex+1) << NumDataArgs)
3455 : S.PDiag(diag::warn_printf_insufficient_data_args);
3456 EmitFormatDiagnostic(
3457 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3458 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003459 return false;
3460 }
3461 return true;
3462}
3463
Richard Trieu03cf7b72011-10-28 00:41:25 +00003464template<typename Range>
3465void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3466 SourceLocation Loc,
3467 bool IsStringLocation,
3468 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003469 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003470 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003471 Loc, IsStringLocation, StringRange, FixIt);
3472}
3473
3474/// \brief If the format string is not within the funcion call, emit a note
3475/// so that the function call and string are in diagnostic messages.
3476///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003477/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003478/// call and only one diagnostic message will be produced. Otherwise, an
3479/// extra note will be emitted pointing to location of the format string.
3480///
3481/// \param ArgumentExpr the expression that is passed as the format string
3482/// argument in the function call. Used for getting locations when two
3483/// diagnostics are emitted.
3484///
3485/// \param PDiag the callee should already have provided any strings for the
3486/// diagnostic message. This function only adds locations and fixits
3487/// to diagnostics.
3488///
3489/// \param Loc primary location for diagnostic. If two diagnostics are
3490/// required, one will be at Loc and a new SourceLocation will be created for
3491/// the other one.
3492///
3493/// \param IsStringLocation if true, Loc points to the format string should be
3494/// used for the note. Otherwise, Loc points to the argument list and will
3495/// be used with PDiag.
3496///
3497/// \param StringRange some or all of the string to highlight. This is
3498/// templated so it can accept either a CharSourceRange or a SourceRange.
3499///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003500/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003501template<typename Range>
3502void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3503 const Expr *ArgumentExpr,
3504 PartialDiagnostic PDiag,
3505 SourceLocation Loc,
3506 bool IsStringLocation,
3507 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003508 ArrayRef<FixItHint> FixIt) {
3509 if (InFunctionCall) {
3510 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3511 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003512 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00003513 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003514 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3515 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003516
3517 const Sema::SemaDiagnosticBuilder &Note =
3518 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3519 diag::note_format_string_defined);
3520
3521 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003522 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003523 }
3524}
3525
Ted Kremenek02087932010-07-16 02:11:22 +00003526//===--- CHECK: Printf format string checking ------------------------------===//
3527
3528namespace {
3529class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003530 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00003531public:
3532 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3533 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003534 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003535 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003536 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003537 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003538 Sema::VariadicCallType CallType,
3539 llvm::SmallBitVector &CheckedVarArgs)
3540 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3541 numDataArgs, beg, hasVAListArg, Args,
3542 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3543 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003544 {}
3545
Craig Toppere14c0f82014-03-12 04:55:44 +00003546
Ted Kremenek02087932010-07-16 02:11:22 +00003547 bool HandleInvalidPrintfConversionSpecifier(
3548 const analyze_printf::PrintfSpecifier &FS,
3549 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003550 unsigned specifierLen) override;
3551
Ted Kremenek02087932010-07-16 02:11:22 +00003552 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3553 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003554 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003555 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3556 const char *StartSpecifier,
3557 unsigned SpecifierLen,
3558 const Expr *E);
3559
Ted Kremenek02087932010-07-16 02:11:22 +00003560 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3561 const char *startSpecifier, unsigned specifierLen);
3562 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3563 const analyze_printf::OptionalAmount &Amt,
3564 unsigned type,
3565 const char *startSpecifier, unsigned specifierLen);
3566 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3567 const analyze_printf::OptionalFlag &flag,
3568 const char *startSpecifier, unsigned specifierLen);
3569 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3570 const analyze_printf::OptionalFlag &ignoredFlag,
3571 const analyze_printf::OptionalFlag &flag,
3572 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003573 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003574 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00003575
3576 void HandleEmptyObjCModifierFlag(const char *startFlag,
3577 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003578
Ted Kremenek2b417712015-07-02 05:39:16 +00003579 void HandleInvalidObjCModifierFlag(const char *startFlag,
3580 unsigned flagLen) override;
3581
3582 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
3583 const char *flagsEnd,
3584 const char *conversionPosition)
3585 override;
3586};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003587}
Ted Kremenek02087932010-07-16 02:11:22 +00003588
3589bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3590 const analyze_printf::PrintfSpecifier &FS,
3591 const char *startSpecifier,
3592 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003593 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003594 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003595
Ted Kremenekce815422010-07-19 21:25:57 +00003596 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3597 getLocationOfByte(CS.getStart()),
3598 startSpecifier, specifierLen,
3599 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003600}
3601
Ted Kremenek02087932010-07-16 02:11:22 +00003602bool CheckPrintfHandler::HandleAmount(
3603 const analyze_format_string::OptionalAmount &Amt,
3604 unsigned k, const char *startSpecifier,
3605 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003606
3607 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003608 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003609 unsigned argIndex = Amt.getArgIndex();
3610 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003611 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3612 << k,
3613 getLocationOfByte(Amt.getStart()),
3614 /*IsStringLocation*/true,
3615 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003616 // Don't do any more checking. We will just emit
3617 // spurious errors.
3618 return false;
3619 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003620
Ted Kremenek5739de72010-01-29 01:06:55 +00003621 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00003622 // Although not in conformance with C99, we also allow the argument to be
3623 // an 'unsigned int' as that is a reasonably safe case. GCC also
3624 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003625 CoveredArgs.set(argIndex);
3626 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003627 if (!Arg)
3628 return false;
3629
Ted Kremenek5739de72010-01-29 01:06:55 +00003630 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003631
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003632 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3633 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003634
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003635 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003636 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003637 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003638 << T << Arg->getSourceRange(),
3639 getLocationOfByte(Amt.getStart()),
3640 /*IsStringLocation*/true,
3641 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003642 // Don't do any more checking. We will just emit
3643 // spurious errors.
3644 return false;
3645 }
3646 }
3647 }
3648 return true;
3649}
Ted Kremenek5739de72010-01-29 01:06:55 +00003650
Tom Careb49ec692010-06-17 19:00:27 +00003651void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003652 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003653 const analyze_printf::OptionalAmount &Amt,
3654 unsigned type,
3655 const char *startSpecifier,
3656 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003657 const analyze_printf::PrintfConversionSpecifier &CS =
3658 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003659
Richard Trieu03cf7b72011-10-28 00:41:25 +00003660 FixItHint fixit =
3661 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3662 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3663 Amt.getConstantLength()))
3664 : FixItHint();
3665
3666 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3667 << type << CS.toString(),
3668 getLocationOfByte(Amt.getStart()),
3669 /*IsStringLocation*/true,
3670 getSpecifierRange(startSpecifier, specifierLen),
3671 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003672}
3673
Ted Kremenek02087932010-07-16 02:11:22 +00003674void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003675 const analyze_printf::OptionalFlag &flag,
3676 const char *startSpecifier,
3677 unsigned specifierLen) {
3678 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003679 const analyze_printf::PrintfConversionSpecifier &CS =
3680 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003681 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3682 << flag.toString() << CS.toString(),
3683 getLocationOfByte(flag.getPosition()),
3684 /*IsStringLocation*/true,
3685 getSpecifierRange(startSpecifier, specifierLen),
3686 FixItHint::CreateRemoval(
3687 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003688}
3689
3690void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003691 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003692 const analyze_printf::OptionalFlag &ignoredFlag,
3693 const analyze_printf::OptionalFlag &flag,
3694 const char *startSpecifier,
3695 unsigned specifierLen) {
3696 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003697 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3698 << ignoredFlag.toString() << flag.toString(),
3699 getLocationOfByte(ignoredFlag.getPosition()),
3700 /*IsStringLocation*/true,
3701 getSpecifierRange(startSpecifier, specifierLen),
3702 FixItHint::CreateRemoval(
3703 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003704}
3705
Ted Kremenek2b417712015-07-02 05:39:16 +00003706// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3707// bool IsStringLocation, Range StringRange,
3708// ArrayRef<FixItHint> Fixit = None);
3709
3710void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
3711 unsigned flagLen) {
3712 // Warn about an empty flag.
3713 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
3714 getLocationOfByte(startFlag),
3715 /*IsStringLocation*/true,
3716 getSpecifierRange(startFlag, flagLen));
3717}
3718
3719void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
3720 unsigned flagLen) {
3721 // Warn about an invalid flag.
3722 auto Range = getSpecifierRange(startFlag, flagLen);
3723 StringRef flag(startFlag, flagLen);
3724 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
3725 getLocationOfByte(startFlag),
3726 /*IsStringLocation*/true,
3727 Range, FixItHint::CreateRemoval(Range));
3728}
3729
3730void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
3731 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
3732 // Warn about using '[...]' without a '@' conversion.
3733 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
3734 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
3735 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
3736 getLocationOfByte(conversionPosition),
3737 /*IsStringLocation*/true,
3738 Range, FixItHint::CreateRemoval(Range));
3739}
3740
Richard Smith55ce3522012-06-25 20:30:08 +00003741// Determines if the specified is a C++ class or struct containing
3742// a member with the specified name and kind (e.g. a CXXMethodDecl named
3743// "c_str()").
3744template<typename MemberKind>
3745static llvm::SmallPtrSet<MemberKind*, 1>
3746CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3747 const RecordType *RT = Ty->getAs<RecordType>();
3748 llvm::SmallPtrSet<MemberKind*, 1> Results;
3749
3750 if (!RT)
3751 return Results;
3752 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003753 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003754 return Results;
3755
Alp Tokerb6cc5922014-05-03 03:45:55 +00003756 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003757 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003758 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003759
3760 // We just need to include all members of the right kind turned up by the
3761 // filter, at this point.
3762 if (S.LookupQualifiedName(R, RT->getDecl()))
3763 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3764 NamedDecl *decl = (*I)->getUnderlyingDecl();
3765 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3766 Results.insert(FK);
3767 }
3768 return Results;
3769}
3770
Richard Smith2868a732014-02-28 01:36:39 +00003771/// Check if we could call '.c_str()' on an object.
3772///
3773/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3774/// allow the call, or if it would be ambiguous).
3775bool Sema::hasCStrMethod(const Expr *E) {
3776 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3777 MethodSet Results =
3778 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3779 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3780 MI != ME; ++MI)
3781 if ((*MI)->getMinRequiredArguments() == 0)
3782 return true;
3783 return false;
3784}
3785
Richard Smith55ce3522012-06-25 20:30:08 +00003786// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003787// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003788// Returns true when a c_str() conversion method is found.
3789bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003790 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003791 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3792
3793 MethodSet Results =
3794 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3795
3796 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3797 MI != ME; ++MI) {
3798 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003799 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003800 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003801 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003802 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003803 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3804 << "c_str()"
3805 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3806 return true;
3807 }
3808 }
3809
3810 return false;
3811}
3812
Ted Kremenekab278de2010-01-28 23:39:18 +00003813bool
Ted Kremenek02087932010-07-16 02:11:22 +00003814CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003815 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003816 const char *startSpecifier,
3817 unsigned specifierLen) {
3818
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003819 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003820 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003821 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003822
Ted Kremenek6cd69422010-07-19 22:01:06 +00003823 if (FS.consumesDataArgument()) {
3824 if (atFirstArg) {
3825 atFirstArg = false;
3826 usesPositionalArgs = FS.usesPositionalArg();
3827 }
3828 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003829 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3830 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003831 return false;
3832 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003833 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003834
Ted Kremenekd1668192010-02-27 01:41:03 +00003835 // First check if the field width, precision, and conversion specifier
3836 // have matching data arguments.
3837 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3838 startSpecifier, specifierLen)) {
3839 return false;
3840 }
3841
3842 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3843 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003844 return false;
3845 }
3846
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003847 if (!CS.consumesDataArgument()) {
3848 // FIXME: Technically specifying a precision or field width here
3849 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003850 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003851 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003852
Ted Kremenek4a49d982010-02-26 19:18:41 +00003853 // Consume the argument.
3854 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003855 if (argIndex < NumDataArgs) {
3856 // The check to see if the argIndex is valid will come later.
3857 // We set the bit here because we may exit early from this
3858 // function if we encounter some other error.
3859 CoveredArgs.set(argIndex);
3860 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003861
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003862 // FreeBSD kernel extensions.
3863 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
3864 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
3865 // We need at least two arguments.
3866 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
3867 return false;
3868
3869 // Claim the second argument.
3870 CoveredArgs.set(argIndex + 1);
3871
3872 // Type check the first argument (int for %b, pointer for %D)
3873 const Expr *Ex = getDataArg(argIndex);
3874 const analyze_printf::ArgType &AT =
3875 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
3876 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
3877 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
3878 EmitFormatDiagnostic(
3879 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3880 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3881 << false << Ex->getSourceRange(),
3882 Ex->getLocStart(), /*IsStringLocation*/false,
3883 getSpecifierRange(startSpecifier, specifierLen));
3884
3885 // Type check the second argument (char * for both %b and %D)
3886 Ex = getDataArg(argIndex + 1);
3887 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
3888 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
3889 EmitFormatDiagnostic(
3890 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3891 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
3892 << false << Ex->getSourceRange(),
3893 Ex->getLocStart(), /*IsStringLocation*/false,
3894 getSpecifierRange(startSpecifier, specifierLen));
3895
3896 return true;
3897 }
3898
Ted Kremenek4a49d982010-02-26 19:18:41 +00003899 // Check for using an Objective-C specific conversion specifier
3900 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003901 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003902 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3903 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003904 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003905
Tom Careb49ec692010-06-17 19:00:27 +00003906 // Check for invalid use of field width
3907 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003908 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003909 startSpecifier, specifierLen);
3910 }
3911
3912 // Check for invalid use of precision
3913 if (!FS.hasValidPrecision()) {
3914 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3915 startSpecifier, specifierLen);
3916 }
3917
3918 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003919 if (!FS.hasValidThousandsGroupingPrefix())
3920 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003921 if (!FS.hasValidLeadingZeros())
3922 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3923 if (!FS.hasValidPlusPrefix())
3924 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003925 if (!FS.hasValidSpacePrefix())
3926 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003927 if (!FS.hasValidAlternativeForm())
3928 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3929 if (!FS.hasValidLeftJustified())
3930 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3931
3932 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003933 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3934 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3935 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003936 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3937 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3938 startSpecifier, specifierLen);
3939
3940 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003941 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003942 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3943 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003944 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003945 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003946 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003947 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3948 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003949
Jordan Rose92303592012-09-08 04:00:03 +00003950 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3951 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3952
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003953 // The remaining checks depend on the data arguments.
3954 if (HasVAListArg)
3955 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003956
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003957 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003958 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003959
Jordan Rose58bbe422012-07-19 18:10:08 +00003960 const Expr *Arg = getDataArg(argIndex);
3961 if (!Arg)
3962 return true;
3963
3964 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003965}
3966
Jordan Roseaee34382012-09-05 22:56:26 +00003967static bool requiresParensToAddCast(const Expr *E) {
3968 // FIXME: We should have a general way to reason about operator
3969 // precedence and whether parens are actually needed here.
3970 // Take care of a few common cases where they aren't.
3971 const Expr *Inside = E->IgnoreImpCasts();
3972 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3973 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3974
3975 switch (Inside->getStmtClass()) {
3976 case Stmt::ArraySubscriptExprClass:
3977 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003978 case Stmt::CharacterLiteralClass:
3979 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003980 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003981 case Stmt::FloatingLiteralClass:
3982 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003983 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003984 case Stmt::ObjCArrayLiteralClass:
3985 case Stmt::ObjCBoolLiteralExprClass:
3986 case Stmt::ObjCBoxedExprClass:
3987 case Stmt::ObjCDictionaryLiteralClass:
3988 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003989 case Stmt::ObjCIvarRefExprClass:
3990 case Stmt::ObjCMessageExprClass:
3991 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003992 case Stmt::ObjCStringLiteralClass:
3993 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003994 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003995 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003996 case Stmt::UnaryOperatorClass:
3997 return false;
3998 default:
3999 return true;
4000 }
4001}
4002
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004003static std::pair<QualType, StringRef>
4004shouldNotPrintDirectly(const ASTContext &Context,
4005 QualType IntendedTy,
4006 const Expr *E) {
4007 // Use a 'while' to peel off layers of typedefs.
4008 QualType TyTy = IntendedTy;
4009 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
4010 StringRef Name = UserTy->getDecl()->getName();
4011 QualType CastTy = llvm::StringSwitch<QualType>(Name)
4012 .Case("NSInteger", Context.LongTy)
4013 .Case("NSUInteger", Context.UnsignedLongTy)
4014 .Case("SInt32", Context.IntTy)
4015 .Case("UInt32", Context.UnsignedIntTy)
4016 .Default(QualType());
4017
4018 if (!CastTy.isNull())
4019 return std::make_pair(CastTy, Name);
4020
4021 TyTy = UserTy->desugar();
4022 }
4023
4024 // Strip parens if necessary.
4025 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4026 return shouldNotPrintDirectly(Context,
4027 PE->getSubExpr()->getType(),
4028 PE->getSubExpr());
4029
4030 // If this is a conditional expression, then its result type is constructed
4031 // via usual arithmetic conversions and thus there might be no necessary
4032 // typedef sugar there. Recurse to operands to check for NSInteger &
4033 // Co. usage condition.
4034 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4035 QualType TrueTy, FalseTy;
4036 StringRef TrueName, FalseName;
4037
4038 std::tie(TrueTy, TrueName) =
4039 shouldNotPrintDirectly(Context,
4040 CO->getTrueExpr()->getType(),
4041 CO->getTrueExpr());
4042 std::tie(FalseTy, FalseName) =
4043 shouldNotPrintDirectly(Context,
4044 CO->getFalseExpr()->getType(),
4045 CO->getFalseExpr());
4046
4047 if (TrueTy == FalseTy)
4048 return std::make_pair(TrueTy, TrueName);
4049 else if (TrueTy.isNull())
4050 return std::make_pair(FalseTy, FalseName);
4051 else if (FalseTy.isNull())
4052 return std::make_pair(TrueTy, TrueName);
4053 }
4054
4055 return std::make_pair(QualType(), StringRef());
4056}
4057
Richard Smith55ce3522012-06-25 20:30:08 +00004058bool
4059CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4060 const char *StartSpecifier,
4061 unsigned SpecifierLen,
4062 const Expr *E) {
4063 using namespace analyze_format_string;
4064 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004065 // Now type check the data expression that matches the
4066 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004067 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4068 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00004069 if (!AT.isValid())
4070 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00004071
Jordan Rose598ec092012-12-05 18:44:40 +00004072 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00004073 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4074 ExprTy = TET->getUnderlyingExpr()->getType();
4075 }
4076
Seth Cantrellb4802962015-03-04 03:12:10 +00004077 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4078
4079 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00004080 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004081 }
Jordan Rose98709982012-06-04 22:48:57 +00004082
Jordan Rose22b74712012-09-05 22:56:19 +00004083 // Look through argument promotions for our error message's reported type.
4084 // This includes the integral and floating promotions, but excludes array
4085 // and function pointer decay; seeing that an argument intended to be a
4086 // string has type 'char [6]' is probably more confusing than 'char *'.
4087 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4088 if (ICE->getCastKind() == CK_IntegralCast ||
4089 ICE->getCastKind() == CK_FloatingCast) {
4090 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00004091 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00004092
4093 // Check if we didn't match because of an implicit cast from a 'char'
4094 // or 'short' to an 'int'. This is done because printf is a varargs
4095 // function.
4096 if (ICE->getType() == S.Context.IntTy ||
4097 ICE->getType() == S.Context.UnsignedIntTy) {
4098 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00004099 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00004100 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00004101 }
Jordan Rose98709982012-06-04 22:48:57 +00004102 }
Jordan Rose598ec092012-12-05 18:44:40 +00004103 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4104 // Special case for 'a', which has type 'int' in C.
4105 // Note, however, that we do /not/ want to treat multibyte constants like
4106 // 'MooV' as characters! This form is deprecated but still exists.
4107 if (ExprTy == S.Context.IntTy)
4108 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4109 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00004110 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004111
Jordan Rosebc53ed12014-05-31 04:12:14 +00004112 // Look through enums to their underlying type.
4113 bool IsEnum = false;
4114 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4115 ExprTy = EnumTy->getDecl()->getIntegerType();
4116 IsEnum = true;
4117 }
4118
Jordan Rose0e5badd2012-12-05 18:44:49 +00004119 // %C in an Objective-C context prints a unichar, not a wchar_t.
4120 // If the argument is an integer of some kind, believe the %C and suggest
4121 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00004122 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004123 if (ObjCContext &&
4124 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4125 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4126 !ExprTy->isCharType()) {
4127 // 'unichar' is defined as a typedef of unsigned short, but we should
4128 // prefer using the typedef if it is visible.
4129 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00004130
4131 // While we are here, check if the value is an IntegerLiteral that happens
4132 // to be within the valid range.
4133 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4134 const llvm::APInt &V = IL->getValue();
4135 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4136 return true;
4137 }
4138
Jordan Rose0e5badd2012-12-05 18:44:49 +00004139 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4140 Sema::LookupOrdinaryName);
4141 if (S.LookupName(Result, S.getCurScope())) {
4142 NamedDecl *ND = Result.getFoundDecl();
4143 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4144 if (TD->getUnderlyingType() == IntendedTy)
4145 IntendedTy = S.Context.getTypedefType(TD);
4146 }
4147 }
4148 }
4149
4150 // Special-case some of Darwin's platform-independence types by suggesting
4151 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004152 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00004153 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004154 QualType CastTy;
4155 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
4156 if (!CastTy.isNull()) {
4157 IntendedTy = CastTy;
4158 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00004159 }
4160 }
4161
Jordan Rose22b74712012-09-05 22:56:19 +00004162 // We may be able to offer a FixItHint if it is a supported type.
4163 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00004164 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00004165 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004166
Jordan Rose22b74712012-09-05 22:56:19 +00004167 if (success) {
4168 // Get the fix string from the fixed format specifier
4169 SmallString<16> buf;
4170 llvm::raw_svector_ostream os(buf);
4171 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004172
Jordan Roseaee34382012-09-05 22:56:26 +00004173 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4174
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004175 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00004176 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4177 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4178 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4179 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00004180 // In this case, the specifier is wrong and should be changed to match
4181 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00004182 EmitFormatDiagnostic(S.PDiag(diag)
4183 << AT.getRepresentativeTypeName(S.Context)
4184 << IntendedTy << IsEnum << E->getSourceRange(),
4185 E->getLocStart(),
4186 /*IsStringLocation*/ false, SpecRange,
4187 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00004188
4189 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00004190 // The canonical type for formatting this value is different from the
4191 // actual type of the expression. (This occurs, for example, with Darwin's
4192 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
4193 // should be printed as 'long' for 64-bit compatibility.)
4194 // Rather than emitting a normal format/argument mismatch, we want to
4195 // add a cast to the recommended type (and correct the format string
4196 // if necessary).
4197 SmallString<16> CastBuf;
4198 llvm::raw_svector_ostream CastFix(CastBuf);
4199 CastFix << "(";
4200 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
4201 CastFix << ")";
4202
4203 SmallVector<FixItHint,4> Hints;
4204 if (!AT.matchesType(S.Context, IntendedTy))
4205 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
4206
4207 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
4208 // If there's already a cast present, just replace it.
4209 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
4210 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
4211
4212 } else if (!requiresParensToAddCast(E)) {
4213 // If the expression has high enough precedence,
4214 // just write the C-style cast.
4215 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4216 CastFix.str()));
4217 } else {
4218 // Otherwise, add parens around the expression as well as the cast.
4219 CastFix << "(";
4220 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4221 CastFix.str()));
4222
Alp Tokerb6cc5922014-05-03 03:45:55 +00004223 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00004224 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
4225 }
4226
Jordan Rose0e5badd2012-12-05 18:44:49 +00004227 if (ShouldNotPrintDirectly) {
4228 // The expression has a type that should not be printed directly.
4229 // We extract the name from the typedef because we don't want to show
4230 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004231 StringRef Name;
4232 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
4233 Name = TypedefTy->getDecl()->getName();
4234 else
4235 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004236 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00004237 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004238 << E->getSourceRange(),
4239 E->getLocStart(), /*IsStringLocation=*/false,
4240 SpecRange, Hints);
4241 } else {
4242 // In this case, the expression could be printed using a different
4243 // specifier, but we've decided that the specifier is probably correct
4244 // and we should cast instead. Just use the normal warning message.
4245 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00004246 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4247 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004248 << E->getSourceRange(),
4249 E->getLocStart(), /*IsStringLocation*/false,
4250 SpecRange, Hints);
4251 }
Jordan Roseaee34382012-09-05 22:56:26 +00004252 }
Jordan Rose22b74712012-09-05 22:56:19 +00004253 } else {
4254 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
4255 SpecifierLen);
4256 // Since the warning for passing non-POD types to variadic functions
4257 // was deferred until now, we emit a warning for non-POD
4258 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00004259 switch (S.isValidVarArgType(ExprTy)) {
4260 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00004261 case Sema::VAK_ValidInCXX11: {
4262 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4263 if (match == analyze_printf::ArgType::NoMatchPedantic) {
4264 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4265 }
Richard Smithd7293d72013-08-05 18:49:43 +00004266
Seth Cantrellb4802962015-03-04 03:12:10 +00004267 EmitFormatDiagnostic(
4268 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4269 << IsEnum << CSR << E->getSourceRange(),
4270 E->getLocStart(), /*IsStringLocation*/ false, CSR);
4271 break;
4272 }
Richard Smithd7293d72013-08-05 18:49:43 +00004273 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00004274 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00004275 EmitFormatDiagnostic(
4276 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004277 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00004278 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00004279 << CallType
4280 << AT.getRepresentativeTypeName(S.Context)
4281 << CSR
4282 << E->getSourceRange(),
4283 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00004284 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00004285 break;
4286
4287 case Sema::VAK_Invalid:
4288 if (ExprTy->isObjCObjectType())
4289 EmitFormatDiagnostic(
4290 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4291 << S.getLangOpts().CPlusPlus11
4292 << ExprTy
4293 << CallType
4294 << AT.getRepresentativeTypeName(S.Context)
4295 << CSR
4296 << E->getSourceRange(),
4297 E->getLocStart(), /*IsStringLocation*/false, CSR);
4298 else
4299 // FIXME: If this is an initializer list, suggest removing the braces
4300 // or inserting a cast to the target type.
4301 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4302 << isa<InitListExpr>(E) << ExprTy << CallType
4303 << AT.getRepresentativeTypeName(S.Context)
4304 << E->getSourceRange();
4305 break;
4306 }
4307
4308 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4309 "format string specifier index out of range");
4310 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004311 }
4312
Ted Kremenekab278de2010-01-28 23:39:18 +00004313 return true;
4314}
4315
Ted Kremenek02087932010-07-16 02:11:22 +00004316//===--- CHECK: Scanf format string checking ------------------------------===//
4317
4318namespace {
4319class CheckScanfHandler : public CheckFormatHandler {
4320public:
4321 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4322 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004323 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004324 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004325 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004326 Sema::VariadicCallType CallType,
4327 llvm::SmallBitVector &CheckedVarArgs)
4328 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4329 numDataArgs, beg, hasVAListArg,
4330 Args, formatIdx, inFunctionCall, CallType,
4331 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004332 {}
Ted Kremenek02087932010-07-16 02:11:22 +00004333
4334 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4335 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004336 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00004337
4338 bool HandleInvalidScanfConversionSpecifier(
4339 const analyze_scanf::ScanfSpecifier &FS,
4340 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004341 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004342
Craig Toppere14c0f82014-03-12 04:55:44 +00004343 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00004344};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004345}
Ted Kremenekab278de2010-01-28 23:39:18 +00004346
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004347void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4348 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004349 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4350 getLocationOfByte(end), /*IsStringLocation*/true,
4351 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004352}
4353
Ted Kremenekce815422010-07-19 21:25:57 +00004354bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4355 const analyze_scanf::ScanfSpecifier &FS,
4356 const char *startSpecifier,
4357 unsigned specifierLen) {
4358
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004359 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004360 FS.getConversionSpecifier();
4361
4362 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4363 getLocationOfByte(CS.getStart()),
4364 startSpecifier, specifierLen,
4365 CS.getStart(), CS.getLength());
4366}
4367
Ted Kremenek02087932010-07-16 02:11:22 +00004368bool CheckScanfHandler::HandleScanfSpecifier(
4369 const analyze_scanf::ScanfSpecifier &FS,
4370 const char *startSpecifier,
4371 unsigned specifierLen) {
4372
4373 using namespace analyze_scanf;
4374 using namespace analyze_format_string;
4375
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004376 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004377
Ted Kremenek6cd69422010-07-19 22:01:06 +00004378 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4379 // be used to decide if we are using positional arguments consistently.
4380 if (FS.consumesDataArgument()) {
4381 if (atFirstArg) {
4382 atFirstArg = false;
4383 usesPositionalArgs = FS.usesPositionalArg();
4384 }
4385 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004386 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4387 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004388 return false;
4389 }
Ted Kremenek02087932010-07-16 02:11:22 +00004390 }
4391
4392 // Check if the field with is non-zero.
4393 const OptionalAmount &Amt = FS.getFieldWidth();
4394 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4395 if (Amt.getConstantAmount() == 0) {
4396 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4397 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00004398 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4399 getLocationOfByte(Amt.getStart()),
4400 /*IsStringLocation*/true, R,
4401 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00004402 }
4403 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004404
Ted Kremenek02087932010-07-16 02:11:22 +00004405 if (!FS.consumesDataArgument()) {
4406 // FIXME: Technically specifying a precision or field width here
4407 // makes no sense. Worth issuing a warning at some point.
4408 return true;
4409 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004410
Ted Kremenek02087932010-07-16 02:11:22 +00004411 // Consume the argument.
4412 unsigned argIndex = FS.getArgIndex();
4413 if (argIndex < NumDataArgs) {
4414 // The check to see if the argIndex is valid will come later.
4415 // We set the bit here because we may exit early from this
4416 // function if we encounter some other error.
4417 CoveredArgs.set(argIndex);
4418 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004419
Ted Kremenek4407ea42010-07-20 20:04:47 +00004420 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004421 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004422 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4423 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004424 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004425 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004426 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004427 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4428 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004429
Jordan Rose92303592012-09-08 04:00:03 +00004430 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4431 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4432
Ted Kremenek02087932010-07-16 02:11:22 +00004433 // The remaining checks depend on the data arguments.
4434 if (HasVAListArg)
4435 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004436
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004437 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004438 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00004439
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004440 // Check that the argument type matches the format specifier.
4441 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004442 if (!Ex)
4443 return true;
4444
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004445 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00004446
4447 if (!AT.isValid()) {
4448 return true;
4449 }
4450
Seth Cantrellb4802962015-03-04 03:12:10 +00004451 analyze_format_string::ArgType::MatchKind match =
4452 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00004453 if (match == analyze_format_string::ArgType::Match) {
4454 return true;
4455 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004456
Seth Cantrell79340072015-03-04 05:58:08 +00004457 ScanfSpecifier fixedFS = FS;
4458 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4459 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004460
Seth Cantrell79340072015-03-04 05:58:08 +00004461 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4462 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4463 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4464 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004465
Seth Cantrell79340072015-03-04 05:58:08 +00004466 if (success) {
4467 // Get the fix string from the fixed format specifier.
4468 SmallString<128> buf;
4469 llvm::raw_svector_ostream os(buf);
4470 fixedFS.toString(os);
4471
4472 EmitFormatDiagnostic(
4473 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4474 << Ex->getType() << false << Ex->getSourceRange(),
4475 Ex->getLocStart(),
4476 /*IsStringLocation*/ false,
4477 getSpecifierRange(startSpecifier, specifierLen),
4478 FixItHint::CreateReplacement(
4479 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4480 } else {
4481 EmitFormatDiagnostic(S.PDiag(diag)
4482 << AT.getRepresentativeTypeName(S.Context)
4483 << Ex->getType() << false << Ex->getSourceRange(),
4484 Ex->getLocStart(),
4485 /*IsStringLocation*/ false,
4486 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004487 }
4488
Ted Kremenek02087932010-07-16 02:11:22 +00004489 return true;
4490}
4491
4492void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00004493 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004494 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004495 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004496 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00004497 bool inFunctionCall, VariadicCallType CallType,
4498 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004499
Ted Kremenekab278de2010-01-28 23:39:18 +00004500 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004501 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004502 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004503 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004504 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4505 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004506 return;
4507 }
Ted Kremenek02087932010-07-16 02:11:22 +00004508
Ted Kremenekab278de2010-01-28 23:39:18 +00004509 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004510 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004511 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004512 // Account for cases where the string literal is truncated in a declaration.
4513 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4514 assert(T && "String literal not of constant array type!");
4515 size_t TypeSize = T->getSize().getZExtValue();
4516 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004517 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004518
4519 // Emit a warning if the string literal is truncated and does not contain an
4520 // embedded null character.
4521 if (TypeSize <= StrRef.size() &&
4522 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4523 CheckFormatHandler::EmitFormatDiagnostic(
4524 *this, inFunctionCall, Args[format_idx],
4525 PDiag(diag::warn_printf_format_string_not_null_terminated),
4526 FExpr->getLocStart(),
4527 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4528 return;
4529 }
4530
Ted Kremenekab278de2010-01-28 23:39:18 +00004531 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004532 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004533 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004534 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004535 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4536 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004537 return;
4538 }
Ted Kremenek02087932010-07-16 02:11:22 +00004539
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004540 if (Type == FST_Printf || Type == FST_NSString ||
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004541 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek02087932010-07-16 02:11:22 +00004542 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004543 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004544 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004545 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004546
Hans Wennborg23926bd2011-12-15 10:25:47 +00004547 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004548 getLangOpts(),
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004549 Context.getTargetInfo(),
4550 Type == FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00004551 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004552 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004553 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004554 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004555 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004556
Hans Wennborg23926bd2011-12-15 10:25:47 +00004557 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004558 getLangOpts(),
4559 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004560 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004561 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004562}
4563
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004564bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4565 // Str - The format string. NOTE: this is NOT null-terminated!
4566 StringRef StrRef = FExpr->getString();
4567 const char *Str = StrRef.data();
4568 // Account for cases where the string literal is truncated in a declaration.
4569 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4570 assert(T && "String literal not of constant array type!");
4571 size_t TypeSize = T->getSize().getZExtValue();
4572 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4573 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4574 getLangOpts(),
4575 Context.getTargetInfo());
4576}
4577
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004578//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4579
4580// Returns the related absolute value function that is larger, of 0 if one
4581// does not exist.
4582static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4583 switch (AbsFunction) {
4584 default:
4585 return 0;
4586
4587 case Builtin::BI__builtin_abs:
4588 return Builtin::BI__builtin_labs;
4589 case Builtin::BI__builtin_labs:
4590 return Builtin::BI__builtin_llabs;
4591 case Builtin::BI__builtin_llabs:
4592 return 0;
4593
4594 case Builtin::BI__builtin_fabsf:
4595 return Builtin::BI__builtin_fabs;
4596 case Builtin::BI__builtin_fabs:
4597 return Builtin::BI__builtin_fabsl;
4598 case Builtin::BI__builtin_fabsl:
4599 return 0;
4600
4601 case Builtin::BI__builtin_cabsf:
4602 return Builtin::BI__builtin_cabs;
4603 case Builtin::BI__builtin_cabs:
4604 return Builtin::BI__builtin_cabsl;
4605 case Builtin::BI__builtin_cabsl:
4606 return 0;
4607
4608 case Builtin::BIabs:
4609 return Builtin::BIlabs;
4610 case Builtin::BIlabs:
4611 return Builtin::BIllabs;
4612 case Builtin::BIllabs:
4613 return 0;
4614
4615 case Builtin::BIfabsf:
4616 return Builtin::BIfabs;
4617 case Builtin::BIfabs:
4618 return Builtin::BIfabsl;
4619 case Builtin::BIfabsl:
4620 return 0;
4621
4622 case Builtin::BIcabsf:
4623 return Builtin::BIcabs;
4624 case Builtin::BIcabs:
4625 return Builtin::BIcabsl;
4626 case Builtin::BIcabsl:
4627 return 0;
4628 }
4629}
4630
4631// Returns the argument type of the absolute value function.
4632static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4633 unsigned AbsType) {
4634 if (AbsType == 0)
4635 return QualType();
4636
4637 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4638 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4639 if (Error != ASTContext::GE_None)
4640 return QualType();
4641
4642 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4643 if (!FT)
4644 return QualType();
4645
4646 if (FT->getNumParams() != 1)
4647 return QualType();
4648
4649 return FT->getParamType(0);
4650}
4651
4652// Returns the best absolute value function, or zero, based on type and
4653// current absolute value function.
4654static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4655 unsigned AbsFunctionKind) {
4656 unsigned BestKind = 0;
4657 uint64_t ArgSize = Context.getTypeSize(ArgType);
4658 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4659 Kind = getLargerAbsoluteValueFunction(Kind)) {
4660 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4661 if (Context.getTypeSize(ParamType) >= ArgSize) {
4662 if (BestKind == 0)
4663 BestKind = Kind;
4664 else if (Context.hasSameType(ParamType, ArgType)) {
4665 BestKind = Kind;
4666 break;
4667 }
4668 }
4669 }
4670 return BestKind;
4671}
4672
4673enum AbsoluteValueKind {
4674 AVK_Integer,
4675 AVK_Floating,
4676 AVK_Complex
4677};
4678
4679static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4680 if (T->isIntegralOrEnumerationType())
4681 return AVK_Integer;
4682 if (T->isRealFloatingType())
4683 return AVK_Floating;
4684 if (T->isAnyComplexType())
4685 return AVK_Complex;
4686
4687 llvm_unreachable("Type not integer, floating, or complex");
4688}
4689
4690// Changes the absolute value function to a different type. Preserves whether
4691// the function is a builtin.
4692static unsigned changeAbsFunction(unsigned AbsKind,
4693 AbsoluteValueKind ValueKind) {
4694 switch (ValueKind) {
4695 case AVK_Integer:
4696 switch (AbsKind) {
4697 default:
4698 return 0;
4699 case Builtin::BI__builtin_fabsf:
4700 case Builtin::BI__builtin_fabs:
4701 case Builtin::BI__builtin_fabsl:
4702 case Builtin::BI__builtin_cabsf:
4703 case Builtin::BI__builtin_cabs:
4704 case Builtin::BI__builtin_cabsl:
4705 return Builtin::BI__builtin_abs;
4706 case Builtin::BIfabsf:
4707 case Builtin::BIfabs:
4708 case Builtin::BIfabsl:
4709 case Builtin::BIcabsf:
4710 case Builtin::BIcabs:
4711 case Builtin::BIcabsl:
4712 return Builtin::BIabs;
4713 }
4714 case AVK_Floating:
4715 switch (AbsKind) {
4716 default:
4717 return 0;
4718 case Builtin::BI__builtin_abs:
4719 case Builtin::BI__builtin_labs:
4720 case Builtin::BI__builtin_llabs:
4721 case Builtin::BI__builtin_cabsf:
4722 case Builtin::BI__builtin_cabs:
4723 case Builtin::BI__builtin_cabsl:
4724 return Builtin::BI__builtin_fabsf;
4725 case Builtin::BIabs:
4726 case Builtin::BIlabs:
4727 case Builtin::BIllabs:
4728 case Builtin::BIcabsf:
4729 case Builtin::BIcabs:
4730 case Builtin::BIcabsl:
4731 return Builtin::BIfabsf;
4732 }
4733 case AVK_Complex:
4734 switch (AbsKind) {
4735 default:
4736 return 0;
4737 case Builtin::BI__builtin_abs:
4738 case Builtin::BI__builtin_labs:
4739 case Builtin::BI__builtin_llabs:
4740 case Builtin::BI__builtin_fabsf:
4741 case Builtin::BI__builtin_fabs:
4742 case Builtin::BI__builtin_fabsl:
4743 return Builtin::BI__builtin_cabsf;
4744 case Builtin::BIabs:
4745 case Builtin::BIlabs:
4746 case Builtin::BIllabs:
4747 case Builtin::BIfabsf:
4748 case Builtin::BIfabs:
4749 case Builtin::BIfabsl:
4750 return Builtin::BIcabsf;
4751 }
4752 }
4753 llvm_unreachable("Unable to convert function");
4754}
4755
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004756static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004757 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4758 if (!FnInfo)
4759 return 0;
4760
4761 switch (FDecl->getBuiltinID()) {
4762 default:
4763 return 0;
4764 case Builtin::BI__builtin_abs:
4765 case Builtin::BI__builtin_fabs:
4766 case Builtin::BI__builtin_fabsf:
4767 case Builtin::BI__builtin_fabsl:
4768 case Builtin::BI__builtin_labs:
4769 case Builtin::BI__builtin_llabs:
4770 case Builtin::BI__builtin_cabs:
4771 case Builtin::BI__builtin_cabsf:
4772 case Builtin::BI__builtin_cabsl:
4773 case Builtin::BIabs:
4774 case Builtin::BIlabs:
4775 case Builtin::BIllabs:
4776 case Builtin::BIfabs:
4777 case Builtin::BIfabsf:
4778 case Builtin::BIfabsl:
4779 case Builtin::BIcabs:
4780 case Builtin::BIcabsf:
4781 case Builtin::BIcabsl:
4782 return FDecl->getBuiltinID();
4783 }
4784 llvm_unreachable("Unknown Builtin type");
4785}
4786
4787// If the replacement is valid, emit a note with replacement function.
4788// Additionally, suggest including the proper header if not already included.
4789static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004790 unsigned AbsKind, QualType ArgType) {
4791 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004792 const char *HeaderName = nullptr;
4793 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004794 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4795 FunctionName = "std::abs";
4796 if (ArgType->isIntegralOrEnumerationType()) {
4797 HeaderName = "cstdlib";
4798 } else if (ArgType->isRealFloatingType()) {
4799 HeaderName = "cmath";
4800 } else {
4801 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004802 }
Richard Trieubeffb832014-04-15 23:47:53 +00004803
4804 // Lookup all std::abs
4805 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004806 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004807 R.suppressDiagnostics();
4808 S.LookupQualifiedName(R, Std);
4809
4810 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004811 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004812 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4813 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4814 } else {
4815 FDecl = dyn_cast<FunctionDecl>(I);
4816 }
4817 if (!FDecl)
4818 continue;
4819
4820 // Found std::abs(), check that they are the right ones.
4821 if (FDecl->getNumParams() != 1)
4822 continue;
4823
4824 // Check that the parameter type can handle the argument.
4825 QualType ParamType = FDecl->getParamDecl(0)->getType();
4826 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4827 S.Context.getTypeSize(ArgType) <=
4828 S.Context.getTypeSize(ParamType)) {
4829 // Found a function, don't need the header hint.
4830 EmitHeaderHint = false;
4831 break;
4832 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004833 }
Richard Trieubeffb832014-04-15 23:47:53 +00004834 }
4835 } else {
4836 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4837 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4838
4839 if (HeaderName) {
4840 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4841 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4842 R.suppressDiagnostics();
4843 S.LookupName(R, S.getCurScope());
4844
4845 if (R.isSingleResult()) {
4846 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4847 if (FD && FD->getBuiltinID() == AbsKind) {
4848 EmitHeaderHint = false;
4849 } else {
4850 return;
4851 }
4852 } else if (!R.empty()) {
4853 return;
4854 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004855 }
4856 }
4857
4858 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00004859 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004860
Richard Trieubeffb832014-04-15 23:47:53 +00004861 if (!HeaderName)
4862 return;
4863
4864 if (!EmitHeaderHint)
4865 return;
4866
Alp Toker5d96e0a2014-07-11 20:53:51 +00004867 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4868 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00004869}
4870
4871static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4872 if (!FDecl)
4873 return false;
4874
4875 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4876 return false;
4877
4878 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4879
4880 while (ND && ND->isInlineNamespace()) {
4881 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004882 }
Richard Trieubeffb832014-04-15 23:47:53 +00004883
4884 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4885 return false;
4886
4887 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4888 return false;
4889
4890 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004891}
4892
4893// Warn when using the wrong abs() function.
4894void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4895 const FunctionDecl *FDecl,
4896 IdentifierInfo *FnInfo) {
4897 if (Call->getNumArgs() != 1)
4898 return;
4899
4900 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00004901 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4902 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004903 return;
4904
4905 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4906 QualType ParamType = Call->getArg(0)->getType();
4907
Alp Toker5d96e0a2014-07-11 20:53:51 +00004908 // Unsigned types cannot be negative. Suggest removing the absolute value
4909 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004910 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00004911 const char *FunctionName =
4912 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004913 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4914 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00004915 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004916 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4917 return;
4918 }
4919
Richard Trieubeffb832014-04-15 23:47:53 +00004920 // std::abs has overloads which prevent most of the absolute value problems
4921 // from occurring.
4922 if (IsStdAbs)
4923 return;
4924
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004925 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4926 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4927
4928 // The argument and parameter are the same kind. Check if they are the right
4929 // size.
4930 if (ArgValueKind == ParamValueKind) {
4931 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4932 return;
4933
4934 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4935 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4936 << FDecl << ArgType << ParamType;
4937
4938 if (NewAbsKind == 0)
4939 return;
4940
4941 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004942 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004943 return;
4944 }
4945
4946 // ArgValueKind != ParamValueKind
4947 // The wrong type of absolute value function was used. Attempt to find the
4948 // proper one.
4949 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4950 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4951 if (NewAbsKind == 0)
4952 return;
4953
4954 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4955 << FDecl << ParamValueKind << ArgValueKind;
4956
4957 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004958 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004959 return;
4960}
4961
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004962//===--- CHECK: Standard memory functions ---------------------------------===//
4963
Nico Weber0e6daef2013-12-26 23:38:39 +00004964/// \brief Takes the expression passed to the size_t parameter of functions
4965/// such as memcmp, strncat, etc and warns if it's a comparison.
4966///
4967/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4968static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4969 IdentifierInfo *FnName,
4970 SourceLocation FnLoc,
4971 SourceLocation RParenLoc) {
4972 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4973 if (!Size)
4974 return false;
4975
4976 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4977 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4978 return false;
4979
Nico Weber0e6daef2013-12-26 23:38:39 +00004980 SourceRange SizeRange = Size->getSourceRange();
4981 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4982 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00004983 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004984 << FnName << FixItHint::CreateInsertion(
4985 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00004986 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00004987 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00004988 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00004989 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4990 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00004991
4992 return true;
4993}
4994
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004995/// \brief Determine whether the given type is or contains a dynamic class type
4996/// (e.g., whether it has a vtable).
4997static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4998 bool &IsContained) {
4999 // Look through array types while ignoring qualifiers.
5000 const Type *Ty = T->getBaseElementTypeUnsafe();
5001 IsContained = false;
5002
5003 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5004 RD = RD ? RD->getDefinition() : nullptr;
5005 if (!RD)
5006 return nullptr;
5007
5008 if (RD->isDynamicClass())
5009 return RD;
5010
5011 // Check all the fields. If any bases were dynamic, the class is dynamic.
5012 // It's impossible for a class to transitively contain itself by value, so
5013 // infinite recursion is impossible.
5014 for (auto *FD : RD->fields()) {
5015 bool SubContained;
5016 if (const CXXRecordDecl *ContainedRD =
5017 getContainedDynamicClass(FD->getType(), SubContained)) {
5018 IsContained = true;
5019 return ContainedRD;
5020 }
5021 }
5022
5023 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00005024}
5025
Chandler Carruth889ed862011-06-21 23:04:20 +00005026/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005027/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00005028static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00005029 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005030 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5031 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5032 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005033
Craig Topperc3ec1492014-05-26 06:22:03 +00005034 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005035}
5036
Chandler Carruth889ed862011-06-21 23:04:20 +00005037/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00005038static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005039 if (const UnaryExprOrTypeTraitExpr *SizeOf =
5040 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5041 if (SizeOf->getKind() == clang::UETT_SizeOf)
5042 return SizeOf->getTypeOfArgument();
5043
5044 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00005045}
5046
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005047/// \brief Check for dangerous or invalid arguments to memset().
5048///
Chandler Carruthac687262011-06-03 06:23:57 +00005049/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005050/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5051/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005052///
5053/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005054void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00005055 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005056 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00005057 assert(BId != 0);
5058
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005059 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00005060 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00005061 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00005062 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005063 return;
5064
Anna Zaks22122702012-01-17 00:37:07 +00005065 unsigned LastArg = (BId == Builtin::BImemset ||
5066 BId == Builtin::BIstrndup ? 1 : 2);
5067 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00005068 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005069
Nico Weber0e6daef2013-12-26 23:38:39 +00005070 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5071 Call->getLocStart(), Call->getRParenLoc()))
5072 return;
5073
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005074 // We have special checking when the length is a sizeof expression.
5075 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5076 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5077 llvm::FoldingSetNodeID SizeOfArgID;
5078
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005079 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5080 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005081 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005082
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005083 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00005084 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005085 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00005086 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00005087
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005088 // Never warn about void type pointers. This can be used to suppress
5089 // false positives.
5090 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005091 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005092
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005093 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5094 // actually comparing the expressions for equality. Because computing the
5095 // expression IDs can be expensive, we only do this if the diagnostic is
5096 // enabled.
5097 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005098 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5099 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005100 // We only compute IDs for expressions if the warning is enabled, and
5101 // cache the sizeof arg's ID.
5102 if (SizeOfArgID == llvm::FoldingSetNodeID())
5103 SizeOfArg->Profile(SizeOfArgID, Context, true);
5104 llvm::FoldingSetNodeID DestID;
5105 Dest->Profile(DestID, Context, true);
5106 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00005107 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5108 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005109 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00005110 StringRef ReadableName = FnName->getName();
5111
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005112 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00005113 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005114 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00005115 if (!PointeeTy->isIncompleteType() &&
5116 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005117 ActionIdx = 2; // If the pointee's size is sizeof(char),
5118 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00005119
5120 // If the function is defined as a builtin macro, do not show macro
5121 // expansion.
5122 SourceLocation SL = SizeOfArg->getExprLoc();
5123 SourceRange DSR = Dest->getSourceRange();
5124 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005125 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00005126
5127 if (SM.isMacroArgExpansion(SL)) {
5128 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5129 SL = SM.getSpellingLoc(SL);
5130 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5131 SM.getSpellingLoc(DSR.getEnd()));
5132 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5133 SM.getSpellingLoc(SSR.getEnd()));
5134 }
5135
Anna Zaksd08d9152012-05-30 23:14:52 +00005136 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005137 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00005138 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00005139 << PointeeTy
5140 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00005141 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00005142 << SSR);
5143 DiagRuntimeBehavior(SL, SizeOfArg,
5144 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5145 << ActionIdx
5146 << SSR);
5147
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005148 break;
5149 }
5150 }
5151
5152 // Also check for cases where the sizeof argument is the exact same
5153 // type as the memory argument, and where it points to a user-defined
5154 // record type.
5155 if (SizeOfArgTy != QualType()) {
5156 if (PointeeTy->isRecordType() &&
5157 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
5158 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
5159 PDiag(diag::warn_sizeof_pointer_type_memaccess)
5160 << FnName << SizeOfArgTy << ArgIdx
5161 << PointeeTy << Dest->getSourceRange()
5162 << LenExpr->getSourceRange());
5163 break;
5164 }
Nico Weberc5e73862011-06-14 16:14:58 +00005165 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00005166 } else if (DestTy->isArrayType()) {
5167 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00005168 }
Nico Weberc5e73862011-06-14 16:14:58 +00005169
Nico Weberc44b35e2015-03-21 17:37:46 +00005170 if (PointeeTy == QualType())
5171 continue;
Anna Zaks22122702012-01-17 00:37:07 +00005172
Nico Weberc44b35e2015-03-21 17:37:46 +00005173 // Always complain about dynamic classes.
5174 bool IsContained;
5175 if (const CXXRecordDecl *ContainedRD =
5176 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00005177
Nico Weberc44b35e2015-03-21 17:37:46 +00005178 unsigned OperationType = 0;
5179 // "overwritten" if we're warning about the destination for any call
5180 // but memcmp; otherwise a verb appropriate to the call.
5181 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
5182 if (BId == Builtin::BImemcpy)
5183 OperationType = 1;
5184 else if(BId == Builtin::BImemmove)
5185 OperationType = 2;
5186 else if (BId == Builtin::BImemcmp)
5187 OperationType = 3;
5188 }
5189
John McCall31168b02011-06-15 23:02:42 +00005190 DiagRuntimeBehavior(
5191 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00005192 PDiag(diag::warn_dyn_class_memaccess)
5193 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
5194 << FnName << IsContained << ContainedRD << OperationType
5195 << Call->getCallee()->getSourceRange());
5196 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
5197 BId != Builtin::BImemset)
5198 DiagRuntimeBehavior(
5199 Dest->getExprLoc(), Dest,
5200 PDiag(diag::warn_arc_object_memaccess)
5201 << ArgIdx << FnName << PointeeTy
5202 << Call->getCallee()->getSourceRange());
5203 else
5204 continue;
5205
5206 DiagRuntimeBehavior(
5207 Dest->getExprLoc(), Dest,
5208 PDiag(diag::note_bad_memaccess_silence)
5209 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
5210 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005211 }
Nico Weberc44b35e2015-03-21 17:37:46 +00005212
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005213}
5214
Ted Kremenek6865f772011-08-18 20:55:45 +00005215// A little helper routine: ignore addition and subtraction of integer literals.
5216// This intentionally does not ignore all integer constant expressions because
5217// we don't want to remove sizeof().
5218static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
5219 Ex = Ex->IgnoreParenCasts();
5220
5221 for (;;) {
5222 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
5223 if (!BO || !BO->isAdditiveOp())
5224 break;
5225
5226 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
5227 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
5228
5229 if (isa<IntegerLiteral>(RHS))
5230 Ex = LHS;
5231 else if (isa<IntegerLiteral>(LHS))
5232 Ex = RHS;
5233 else
5234 break;
5235 }
5236
5237 return Ex;
5238}
5239
Anna Zaks13b08572012-08-08 21:42:23 +00005240static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
5241 ASTContext &Context) {
5242 // Only handle constant-sized or VLAs, but not flexible members.
5243 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
5244 // Only issue the FIXIT for arrays of size > 1.
5245 if (CAT->getSize().getSExtValue() <= 1)
5246 return false;
5247 } else if (!Ty->isVariableArrayType()) {
5248 return false;
5249 }
5250 return true;
5251}
5252
Ted Kremenek6865f772011-08-18 20:55:45 +00005253// Warn if the user has made the 'size' argument to strlcpy or strlcat
5254// be the size of the source, instead of the destination.
5255void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
5256 IdentifierInfo *FnName) {
5257
5258 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00005259 unsigned NumArgs = Call->getNumArgs();
5260 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00005261 return;
5262
5263 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5264 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00005265 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00005266
5267 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5268 Call->getLocStart(), Call->getRParenLoc()))
5269 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00005270
5271 // Look for 'strlcpy(dst, x, sizeof(x))'
5272 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5273 CompareWithSrc = Ex;
5274 else {
5275 // Look for 'strlcpy(dst, x, strlen(x))'
5276 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00005277 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5278 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00005279 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5280 }
5281 }
5282
5283 if (!CompareWithSrc)
5284 return;
5285
5286 // Determine if the argument to sizeof/strlen is equal to the source
5287 // argument. In principle there's all kinds of things you could do
5288 // here, for instance creating an == expression and evaluating it with
5289 // EvaluateAsBooleanCondition, but this uses a more direct technique:
5290 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5291 if (!SrcArgDRE)
5292 return;
5293
5294 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5295 if (!CompareWithSrcDRE ||
5296 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5297 return;
5298
5299 const Expr *OriginalSizeArg = Call->getArg(2);
5300 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5301 << OriginalSizeArg->getSourceRange() << FnName;
5302
5303 // Output a FIXIT hint if the destination is an array (rather than a
5304 // pointer to an array). This could be enhanced to handle some
5305 // pointers if we know the actual size, like if DstArg is 'array+2'
5306 // we could say 'sizeof(array)-2'.
5307 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00005308 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00005309 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005310
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005311 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005312 llvm::raw_svector_ostream OS(sizeString);
5313 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005314 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00005315 OS << ")";
5316
5317 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5318 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5319 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00005320}
5321
Anna Zaks314cd092012-02-01 19:08:57 +00005322/// Check if two expressions refer to the same declaration.
5323static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5324 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5325 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5326 return D1->getDecl() == D2->getDecl();
5327 return false;
5328}
5329
5330static const Expr *getStrlenExprArg(const Expr *E) {
5331 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5332 const FunctionDecl *FD = CE->getDirectCallee();
5333 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00005334 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005335 return CE->getArg(0)->IgnoreParenCasts();
5336 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005337 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005338}
5339
5340// Warn on anti-patterns as the 'size' argument to strncat.
5341// The correct size argument should look like following:
5342// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5343void Sema::CheckStrncatArguments(const CallExpr *CE,
5344 IdentifierInfo *FnName) {
5345 // Don't crash if the user has the wrong number of arguments.
5346 if (CE->getNumArgs() < 3)
5347 return;
5348 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5349 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5350 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5351
Nico Weber0e6daef2013-12-26 23:38:39 +00005352 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5353 CE->getRParenLoc()))
5354 return;
5355
Anna Zaks314cd092012-02-01 19:08:57 +00005356 // Identify common expressions, which are wrongly used as the size argument
5357 // to strncat and may lead to buffer overflows.
5358 unsigned PatternType = 0;
5359 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5360 // - sizeof(dst)
5361 if (referToTheSameDecl(SizeOfArg, DstArg))
5362 PatternType = 1;
5363 // - sizeof(src)
5364 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5365 PatternType = 2;
5366 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5367 if (BE->getOpcode() == BO_Sub) {
5368 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5369 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5370 // - sizeof(dst) - strlen(dst)
5371 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5372 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5373 PatternType = 1;
5374 // - sizeof(src) - (anything)
5375 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5376 PatternType = 2;
5377 }
5378 }
5379
5380 if (PatternType == 0)
5381 return;
5382
Anna Zaks5069aa32012-02-03 01:27:37 +00005383 // Generate the diagnostic.
5384 SourceLocation SL = LenArg->getLocStart();
5385 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005386 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00005387
5388 // If the function is defined as a builtin macro, do not show macro expansion.
5389 if (SM.isMacroArgExpansion(SL)) {
5390 SL = SM.getSpellingLoc(SL);
5391 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5392 SM.getSpellingLoc(SR.getEnd()));
5393 }
5394
Anna Zaks13b08572012-08-08 21:42:23 +00005395 // Check if the destination is an array (rather than a pointer to an array).
5396 QualType DstTy = DstArg->getType();
5397 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5398 Context);
5399 if (!isKnownSizeArray) {
5400 if (PatternType == 1)
5401 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5402 else
5403 Diag(SL, diag::warn_strncat_src_size) << SR;
5404 return;
5405 }
5406
Anna Zaks314cd092012-02-01 19:08:57 +00005407 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00005408 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005409 else
Anna Zaks5069aa32012-02-03 01:27:37 +00005410 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005411
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005412 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00005413 llvm::raw_svector_ostream OS(sizeString);
5414 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005415 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005416 OS << ") - ";
5417 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005418 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005419 OS << ") - 1";
5420
Anna Zaks5069aa32012-02-03 01:27:37 +00005421 Diag(SL, diag::note_strncat_wrong_size)
5422 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005423}
5424
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005425//===--- CHECK: Return Address of Stack Variable --------------------------===//
5426
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005427static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5428 Decl *ParentDecl);
5429static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5430 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005431
5432/// CheckReturnStackAddr - Check if a return statement returns the address
5433/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005434static void
5435CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5436 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005437
Craig Topperc3ec1492014-05-26 06:22:03 +00005438 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005439 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005440
5441 // Perform checking for returned stack addresses, local blocks,
5442 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005443 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005444 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005445 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005446 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005447 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005448 }
5449
Craig Topperc3ec1492014-05-26 06:22:03 +00005450 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005451 return; // Nothing suspicious was found.
5452
5453 SourceLocation diagLoc;
5454 SourceRange diagRange;
5455 if (refVars.empty()) {
5456 diagLoc = stackE->getLocStart();
5457 diagRange = stackE->getSourceRange();
5458 } else {
5459 // We followed through a reference variable. 'stackE' contains the
5460 // problematic expression but we will warn at the return statement pointing
5461 // at the reference variable. We will later display the "trail" of
5462 // reference variables using notes.
5463 diagLoc = refVars[0]->getLocStart();
5464 diagRange = refVars[0]->getSourceRange();
5465 }
5466
5467 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005468 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005469 : diag::warn_ret_stack_addr)
5470 << DR->getDecl()->getDeclName() << diagRange;
5471 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005472 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005473 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005474 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005475 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005476 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
5477 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005478 << diagRange;
5479 }
5480
5481 // Display the "trail" of reference variables that we followed until we
5482 // found the problematic expression using notes.
5483 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5484 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5485 // If this var binds to another reference var, show the range of the next
5486 // var, otherwise the var binds to the problematic expression, in which case
5487 // show the range of the expression.
5488 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5489 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005490 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5491 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005492 }
5493}
5494
5495/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5496/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005497/// to a location on the stack, a local block, an address of a label, or a
5498/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005499/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005500/// encounter a subexpression that (1) clearly does not lead to one of the
5501/// above problematic expressions (2) is something we cannot determine leads to
5502/// a problematic expression based on such local checking.
5503///
5504/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5505/// the expression that they point to. Such variables are added to the
5506/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005507///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005508/// EvalAddr processes expressions that are pointers that are used as
5509/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005510/// At the base case of the recursion is a check for the above problematic
5511/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005512///
5513/// This implementation handles:
5514///
5515/// * pointer-to-pointer casts
5516/// * implicit conversions from array references to pointers
5517/// * taking the address of fields
5518/// * arbitrary interplay between "&" and "*" operators
5519/// * pointer arithmetic from an address of a stack variable
5520/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005521static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5522 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005523 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005524 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005525
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005526 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005527 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005528 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005529 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005530 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005531
Peter Collingbourne91147592011-04-15 00:35:48 +00005532 E = E->IgnoreParens();
5533
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005534 // Our "symbolic interpreter" is just a dispatch off the currently
5535 // viewed AST node. We then recursively traverse the AST by calling
5536 // EvalAddr and EvalVal appropriately.
5537 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005538 case Stmt::DeclRefExprClass: {
5539 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5540
Richard Smith40f08eb2014-01-30 22:05:38 +00005541 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005542 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005543 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005544
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005545 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5546 // If this is a reference variable, follow through to the expression that
5547 // it points to.
5548 if (V->hasLocalStorage() &&
5549 V->getType()->isReferenceType() && V->hasInit()) {
5550 // Add the reference variable to the "trail".
5551 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005552 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005553 }
5554
Craig Topperc3ec1492014-05-26 06:22:03 +00005555 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005556 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005557
Chris Lattner934edb22007-12-28 05:31:15 +00005558 case Stmt::UnaryOperatorClass: {
5559 // The only unary operator that make sense to handle here
5560 // is AddrOf. All others don't make sense as pointers.
5561 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005562
John McCalle3027922010-08-25 11:45:40 +00005563 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005564 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005565 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005566 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005567 }
Mike Stump11289f42009-09-09 15:08:12 +00005568
Chris Lattner934edb22007-12-28 05:31:15 +00005569 case Stmt::BinaryOperatorClass: {
5570 // Handle pointer arithmetic. All other binary operators are not valid
5571 // in this context.
5572 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005573 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005574
John McCalle3027922010-08-25 11:45:40 +00005575 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005576 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005577
Chris Lattner934edb22007-12-28 05:31:15 +00005578 Expr *Base = B->getLHS();
5579
5580 // Determine which argument is the real pointer base. It could be
5581 // the RHS argument instead of the LHS.
5582 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005583
Chris Lattner934edb22007-12-28 05:31:15 +00005584 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005585 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005586 }
Steve Naroff2752a172008-09-10 19:17:48 +00005587
Chris Lattner934edb22007-12-28 05:31:15 +00005588 // For conditional operators we need to see if either the LHS or RHS are
5589 // valid DeclRefExpr*s. If one of them is valid, we return it.
5590 case Stmt::ConditionalOperatorClass: {
5591 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005592
Chris Lattner934edb22007-12-28 05:31:15 +00005593 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005594 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5595 if (Expr *LHSExpr = C->getLHS()) {
5596 // In C++, we can have a throw-expression, which has 'void' type.
5597 if (!LHSExpr->getType()->isVoidType())
5598 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005599 return LHS;
5600 }
Chris Lattner934edb22007-12-28 05:31:15 +00005601
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005602 // In C++, we can have a throw-expression, which has 'void' type.
5603 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005604 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005605
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005606 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005607 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005608
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005609 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00005610 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005611 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00005612 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005613
5614 case Stmt::AddrLabelExprClass:
5615 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00005616
John McCall28fc7092011-11-10 05:35:25 +00005617 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005618 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5619 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005620
Ted Kremenekc3b4c522008-08-07 00:49:01 +00005621 // For casts, we need to handle conversions from arrays to
5622 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00005623 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00005624 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005625 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00005626 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00005627 case Stmt::CXXStaticCastExprClass:
5628 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00005629 case Stmt::CXXConstCastExprClass:
5630 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00005631 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5632 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00005633 case CK_LValueToRValue:
5634 case CK_NoOp:
5635 case CK_BaseToDerived:
5636 case CK_DerivedToBase:
5637 case CK_UncheckedDerivedToBase:
5638 case CK_Dynamic:
5639 case CK_CPointerToObjCPointerCast:
5640 case CK_BlockPointerToObjCPointerCast:
5641 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005642 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005643
5644 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005645 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005646
Richard Trieudadefde2014-07-02 04:39:38 +00005647 case CK_BitCast:
5648 if (SubExpr->getType()->isAnyPointerType() ||
5649 SubExpr->getType()->isBlockPointerType() ||
5650 SubExpr->getType()->isObjCQualifiedIdType())
5651 return EvalAddr(SubExpr, refVars, ParentDecl);
5652 else
5653 return nullptr;
5654
Eli Friedman8195ad72012-02-23 23:04:32 +00005655 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005656 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00005657 }
Chris Lattner934edb22007-12-28 05:31:15 +00005658 }
Mike Stump11289f42009-09-09 15:08:12 +00005659
Douglas Gregorfe314812011-06-21 17:03:29 +00005660 case Stmt::MaterializeTemporaryExprClass:
5661 if (Expr *Result = EvalAddr(
5662 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005663 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005664 return Result;
5665
5666 return E;
5667
Chris Lattner934edb22007-12-28 05:31:15 +00005668 // Everything else: we simply don't reason about them.
5669 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005670 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00005671 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005672}
Mike Stump11289f42009-09-09 15:08:12 +00005673
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005674
5675/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5676/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005677static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5678 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005679do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005680 // We should only be called for evaluating non-pointer expressions, or
5681 // expressions with a pointer type that are not used as references but instead
5682 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00005683
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005684 // Our "symbolic interpreter" is just a dispatch off the currently
5685 // viewed AST node. We then recursively traverse the AST by calling
5686 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00005687
5688 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005689 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005690 case Stmt::ImplicitCastExprClass: {
5691 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00005692 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005693 E = IE->getSubExpr();
5694 continue;
5695 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005696 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00005697 }
5698
John McCall28fc7092011-11-10 05:35:25 +00005699 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005700 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005701
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005702 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005703 // When we hit a DeclRefExpr we are looking at code that refers to a
5704 // variable's name. If it's not a reference variable we check if it has
5705 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005706 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005707
Richard Smith40f08eb2014-01-30 22:05:38 +00005708 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005709 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005710 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005711
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005712 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5713 // Check if it refers to itself, e.g. "int& i = i;".
5714 if (V == ParentDecl)
5715 return DR;
5716
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005717 if (V->hasLocalStorage()) {
5718 if (!V->getType()->isReferenceType())
5719 return DR;
5720
5721 // Reference variable, follow through to the expression that
5722 // it points to.
5723 if (V->hasInit()) {
5724 // Add the reference variable to the "trail".
5725 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005726 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005727 }
5728 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005729 }
Mike Stump11289f42009-09-09 15:08:12 +00005730
Craig Topperc3ec1492014-05-26 06:22:03 +00005731 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005732 }
Mike Stump11289f42009-09-09 15:08:12 +00005733
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005734 case Stmt::UnaryOperatorClass: {
5735 // The only unary operator that make sense to handle here
5736 // is Deref. All others don't resolve to a "name." This includes
5737 // handling all sorts of rvalues passed to a unary operator.
5738 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005739
John McCalle3027922010-08-25 11:45:40 +00005740 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005741 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005742
Craig Topperc3ec1492014-05-26 06:22:03 +00005743 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005744 }
Mike Stump11289f42009-09-09 15:08:12 +00005745
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005746 case Stmt::ArraySubscriptExprClass: {
5747 // Array subscripts are potential references to data on the stack. We
5748 // retrieve the DeclRefExpr* for the array variable if it indeed
5749 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005750 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005751 }
Mike Stump11289f42009-09-09 15:08:12 +00005752
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005753 case Stmt::ConditionalOperatorClass: {
5754 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005755 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005756 ConditionalOperator *C = cast<ConditionalOperator>(E);
5757
Anders Carlsson801c5c72007-11-30 19:04:31 +00005758 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005759 if (Expr *LHSExpr = C->getLHS()) {
5760 // In C++, we can have a throw-expression, which has 'void' type.
5761 if (!LHSExpr->getType()->isVoidType())
5762 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5763 return LHS;
5764 }
5765
5766 // In C++, we can have a throw-expression, which has 'void' type.
5767 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005768 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005769
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005770 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005771 }
Mike Stump11289f42009-09-09 15:08:12 +00005772
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005773 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005774 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005775 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005776
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005777 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005778 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005779 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005780
5781 // Check whether the member type is itself a reference, in which case
5782 // we're not going to refer to the member, but to what the member refers to.
5783 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005784 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005785
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005786 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005787 }
Mike Stump11289f42009-09-09 15:08:12 +00005788
Douglas Gregorfe314812011-06-21 17:03:29 +00005789 case Stmt::MaterializeTemporaryExprClass:
5790 if (Expr *Result = EvalVal(
5791 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005792 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005793 return Result;
5794
5795 return E;
5796
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005797 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005798 // Check that we don't return or take the address of a reference to a
5799 // temporary. This is only useful in C++.
5800 if (!E->isTypeDependent() && E->isRValue())
5801 return E;
5802
5803 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005804 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005805 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005806} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005807}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005808
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005809void
5810Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5811 SourceLocation ReturnLoc,
5812 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005813 const AttrVec *Attrs,
5814 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005815 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5816
5817 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00005818 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
5819 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00005820 CheckNonNullExpr(*this, RetValExp))
5821 Diag(ReturnLoc, diag::warn_null_ret)
5822 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00005823
5824 // C++11 [basic.stc.dynamic.allocation]p4:
5825 // If an allocation function declared with a non-throwing
5826 // exception-specification fails to allocate storage, it shall return
5827 // a null pointer. Any other allocation function that fails to allocate
5828 // storage shall indicate failure only by throwing an exception [...]
5829 if (FD) {
5830 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5831 if (Op == OO_New || Op == OO_Array_New) {
5832 const FunctionProtoType *Proto
5833 = FD->getType()->castAs<FunctionProtoType>();
5834 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5835 CheckNonNullExpr(*this, RetValExp))
5836 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5837 << FD << getLangOpts().CPlusPlus11;
5838 }
5839 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005840}
5841
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005842//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5843
5844/// Check for comparisons of floating point operands using != and ==.
5845/// Issue a warning if these are no self-comparisons, as they are not likely
5846/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00005847void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00005848 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5849 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005850
5851 // Special case: check for x == x (which is OK).
5852 // Do not emit warnings for such cases.
5853 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5854 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5855 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00005856 return;
Mike Stump11289f42009-09-09 15:08:12 +00005857
5858
Ted Kremenekeda40e22007-11-29 00:59:04 +00005859 // Special case: check for comparisons against literals that can be exactly
5860 // represented by APFloat. In such cases, do not emit a warning. This
5861 // is a heuristic: often comparison against such literals are used to
5862 // detect if a value in a variable has not changed. This clearly can
5863 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00005864 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5865 if (FLL->isExact())
5866 return;
5867 } else
5868 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5869 if (FLR->isExact())
5870 return;
Mike Stump11289f42009-09-09 15:08:12 +00005871
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005872 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00005873 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005874 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005875 return;
Mike Stump11289f42009-09-09 15:08:12 +00005876
David Blaikie1f4ff152012-07-16 20:47:22 +00005877 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005878 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005879 return;
Mike Stump11289f42009-09-09 15:08:12 +00005880
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005881 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00005882 Diag(Loc, diag::warn_floatingpoint_eq)
5883 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005884}
John McCallca01b222010-01-04 23:21:16 +00005885
John McCall70aa5392010-01-06 05:24:50 +00005886//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5887//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00005888
John McCall70aa5392010-01-06 05:24:50 +00005889namespace {
John McCallca01b222010-01-04 23:21:16 +00005890
John McCall70aa5392010-01-06 05:24:50 +00005891/// Structure recording the 'active' range of an integer-valued
5892/// expression.
5893struct IntRange {
5894 /// The number of bits active in the int.
5895 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00005896
John McCall70aa5392010-01-06 05:24:50 +00005897 /// True if the int is known not to have negative values.
5898 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00005899
John McCall70aa5392010-01-06 05:24:50 +00005900 IntRange(unsigned Width, bool NonNegative)
5901 : Width(Width), NonNegative(NonNegative)
5902 {}
John McCallca01b222010-01-04 23:21:16 +00005903
John McCall817d4af2010-11-10 23:38:19 +00005904 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00005905 static IntRange forBoolType() {
5906 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00005907 }
5908
John McCall817d4af2010-11-10 23:38:19 +00005909 /// Returns the range of an opaque value of the given integral type.
5910 static IntRange forValueOfType(ASTContext &C, QualType T) {
5911 return forValueOfCanonicalType(C,
5912 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00005913 }
5914
John McCall817d4af2010-11-10 23:38:19 +00005915 /// Returns the range of an opaque value of a canonical integral type.
5916 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00005917 assert(T->isCanonicalUnqualified());
5918
5919 if (const VectorType *VT = dyn_cast<VectorType>(T))
5920 T = VT->getElementType().getTypePtr();
5921 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5922 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005923 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5924 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00005925
David Majnemer6a426652013-06-07 22:07:20 +00005926 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00005927 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00005928 EnumDecl *Enum = ET->getDecl();
5929 if (!Enum->isCompleteDefinition())
5930 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00005931
David Majnemer6a426652013-06-07 22:07:20 +00005932 unsigned NumPositive = Enum->getNumPositiveBits();
5933 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00005934
David Majnemer6a426652013-06-07 22:07:20 +00005935 if (NumNegative == 0)
5936 return IntRange(NumPositive, true/*NonNegative*/);
5937 else
5938 return IntRange(std::max(NumPositive + 1, NumNegative),
5939 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00005940 }
John McCall70aa5392010-01-06 05:24:50 +00005941
5942 const BuiltinType *BT = cast<BuiltinType>(T);
5943 assert(BT->isInteger());
5944
5945 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5946 }
5947
John McCall817d4af2010-11-10 23:38:19 +00005948 /// Returns the "target" range of a canonical integral type, i.e.
5949 /// the range of values expressible in the type.
5950 ///
5951 /// This matches forValueOfCanonicalType except that enums have the
5952 /// full range of their type, not the range of their enumerators.
5953 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5954 assert(T->isCanonicalUnqualified());
5955
5956 if (const VectorType *VT = dyn_cast<VectorType>(T))
5957 T = VT->getElementType().getTypePtr();
5958 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5959 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005960 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5961 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005962 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00005963 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005964
5965 const BuiltinType *BT = cast<BuiltinType>(T);
5966 assert(BT->isInteger());
5967
5968 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5969 }
5970
5971 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00005972 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00005973 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00005974 L.NonNegative && R.NonNegative);
5975 }
5976
John McCall817d4af2010-11-10 23:38:19 +00005977 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00005978 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00005979 return IntRange(std::min(L.Width, R.Width),
5980 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00005981 }
5982};
5983
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005984static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5985 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005986 if (value.isSigned() && value.isNegative())
5987 return IntRange(value.getMinSignedBits(), false);
5988
5989 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005990 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005991
5992 // isNonNegative() just checks the sign bit without considering
5993 // signedness.
5994 return IntRange(value.getActiveBits(), true);
5995}
5996
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005997static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5998 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005999 if (result.isInt())
6000 return GetValueRange(C, result.getInt(), MaxWidth);
6001
6002 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00006003 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6004 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6005 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6006 R = IntRange::join(R, El);
6007 }
John McCall70aa5392010-01-06 05:24:50 +00006008 return R;
6009 }
6010
6011 if (result.isComplexInt()) {
6012 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6013 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6014 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00006015 }
6016
6017 // This can happen with lossless casts to intptr_t of "based" lvalues.
6018 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00006019 // FIXME: The only reason we need to pass the type in here is to get
6020 // the sign right on this one case. It would be nice if APValue
6021 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006022 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00006023 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00006024}
John McCall70aa5392010-01-06 05:24:50 +00006025
Eli Friedmane6d33952013-07-08 20:20:06 +00006026static QualType GetExprType(Expr *E) {
6027 QualType Ty = E->getType();
6028 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6029 Ty = AtomicRHS->getValueType();
6030 return Ty;
6031}
6032
John McCall70aa5392010-01-06 05:24:50 +00006033/// Pseudo-evaluate the given integer expression, estimating the
6034/// range of values it might take.
6035///
6036/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006037static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006038 E = E->IgnoreParens();
6039
6040 // Try a full evaluation first.
6041 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006042 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00006043 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006044
6045 // I think we only want to look through implicit casts here; if the
6046 // user has an explicit widening cast, we should treat the value as
6047 // being of the new, wider type.
6048 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00006049 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00006050 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6051
Eli Friedmane6d33952013-07-08 20:20:06 +00006052 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00006053
John McCalle3027922010-08-25 11:45:40 +00006054 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00006055
John McCall70aa5392010-01-06 05:24:50 +00006056 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00006057 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00006058 return OutputTypeRange;
6059
6060 IntRange SubRange
6061 = GetExprRange(C, CE->getSubExpr(),
6062 std::min(MaxWidth, OutputTypeRange.Width));
6063
6064 // Bail out if the subexpr's range is as wide as the cast type.
6065 if (SubRange.Width >= OutputTypeRange.Width)
6066 return OutputTypeRange;
6067
6068 // Otherwise, we take the smaller width, and we're non-negative if
6069 // either the output type or the subexpr is.
6070 return IntRange(SubRange.Width,
6071 SubRange.NonNegative || OutputTypeRange.NonNegative);
6072 }
6073
6074 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6075 // If we can fold the condition, just take that operand.
6076 bool CondResult;
6077 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6078 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6079 : CO->getFalseExpr(),
6080 MaxWidth);
6081
6082 // Otherwise, conservatively merge.
6083 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6084 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6085 return IntRange::join(L, R);
6086 }
6087
6088 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6089 switch (BO->getOpcode()) {
6090
6091 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00006092 case BO_LAnd:
6093 case BO_LOr:
6094 case BO_LT:
6095 case BO_GT:
6096 case BO_LE:
6097 case BO_GE:
6098 case BO_EQ:
6099 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00006100 return IntRange::forBoolType();
6101
John McCallc3688382011-07-13 06:35:24 +00006102 // The type of the assignments is the type of the LHS, so the RHS
6103 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00006104 case BO_MulAssign:
6105 case BO_DivAssign:
6106 case BO_RemAssign:
6107 case BO_AddAssign:
6108 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00006109 case BO_XorAssign:
6110 case BO_OrAssign:
6111 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00006112 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00006113
John McCallc3688382011-07-13 06:35:24 +00006114 // Simple assignments just pass through the RHS, which will have
6115 // been coerced to the LHS type.
6116 case BO_Assign:
6117 // TODO: bitfields?
6118 return GetExprRange(C, BO->getRHS(), MaxWidth);
6119
John McCall70aa5392010-01-06 05:24:50 +00006120 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006121 case BO_PtrMemD:
6122 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00006123 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006124
John McCall2ce81ad2010-01-06 22:07:33 +00006125 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00006126 case BO_And:
6127 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00006128 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6129 GetExprRange(C, BO->getRHS(), MaxWidth));
6130
John McCall70aa5392010-01-06 05:24:50 +00006131 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00006132 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00006133 // ...except that we want to treat '1 << (blah)' as logically
6134 // positive. It's an important idiom.
6135 if (IntegerLiteral *I
6136 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6137 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006138 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00006139 return IntRange(R.Width, /*NonNegative*/ true);
6140 }
6141 }
6142 // fallthrough
6143
John McCalle3027922010-08-25 11:45:40 +00006144 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00006145 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006146
John McCall2ce81ad2010-01-06 22:07:33 +00006147 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00006148 case BO_Shr:
6149 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00006150 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6151
6152 // If the shift amount is a positive constant, drop the width by
6153 // that much.
6154 llvm::APSInt shift;
6155 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6156 shift.isNonNegative()) {
6157 unsigned zext = shift.getZExtValue();
6158 if (zext >= L.Width)
6159 L.Width = (L.NonNegative ? 0 : 1);
6160 else
6161 L.Width -= zext;
6162 }
6163
6164 return L;
6165 }
6166
6167 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00006168 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00006169 return GetExprRange(C, BO->getRHS(), MaxWidth);
6170
John McCall2ce81ad2010-01-06 22:07:33 +00006171 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00006172 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00006173 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00006174 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006175 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006176
John McCall51431812011-07-14 22:39:48 +00006177 // The width of a division result is mostly determined by the size
6178 // of the LHS.
6179 case BO_Div: {
6180 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006181 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006182 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6183
6184 // If the divisor is constant, use that.
6185 llvm::APSInt divisor;
6186 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
6187 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
6188 if (log2 >= L.Width)
6189 L.Width = (L.NonNegative ? 0 : 1);
6190 else
6191 L.Width = std::min(L.Width - log2, MaxWidth);
6192 return L;
6193 }
6194
6195 // Otherwise, just use the LHS's width.
6196 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6197 return IntRange(L.Width, L.NonNegative && R.NonNegative);
6198 }
6199
6200 // The result of a remainder can't be larger than the result of
6201 // either side.
6202 case BO_Rem: {
6203 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006204 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006205 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6206 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6207
6208 IntRange meet = IntRange::meet(L, R);
6209 meet.Width = std::min(meet.Width, MaxWidth);
6210 return meet;
6211 }
6212
6213 // The default behavior is okay for these.
6214 case BO_Mul:
6215 case BO_Add:
6216 case BO_Xor:
6217 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00006218 break;
6219 }
6220
John McCall51431812011-07-14 22:39:48 +00006221 // The default case is to treat the operation as if it were closed
6222 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00006223 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6224 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
6225 return IntRange::join(L, R);
6226 }
6227
6228 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6229 switch (UO->getOpcode()) {
6230 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00006231 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00006232 return IntRange::forBoolType();
6233
6234 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006235 case UO_Deref:
6236 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00006237 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006238
6239 default:
6240 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
6241 }
6242 }
6243
Ted Kremeneka553fbf2013-10-14 18:55:27 +00006244 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6245 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
6246
John McCalld25db7e2013-05-06 21:39:12 +00006247 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00006248 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00006249 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00006250
Eli Friedmane6d33952013-07-08 20:20:06 +00006251 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006252}
John McCall263a48b2010-01-04 23:31:57 +00006253
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006254static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006255 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00006256}
6257
John McCall263a48b2010-01-04 23:31:57 +00006258/// Checks whether the given value, which currently has the given
6259/// source semantics, has the same value when coerced through the
6260/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006261static bool IsSameFloatAfterCast(const llvm::APFloat &value,
6262 const llvm::fltSemantics &Src,
6263 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006264 llvm::APFloat truncated = value;
6265
6266 bool ignored;
6267 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6268 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6269
6270 return truncated.bitwiseIsEqual(value);
6271}
6272
6273/// Checks whether the given value, which currently has the given
6274/// source semantics, has the same value when coerced through the
6275/// target semantics.
6276///
6277/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006278static bool IsSameFloatAfterCast(const APValue &value,
6279 const llvm::fltSemantics &Src,
6280 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006281 if (value.isFloat())
6282 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6283
6284 if (value.isVector()) {
6285 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6286 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6287 return false;
6288 return true;
6289 }
6290
6291 assert(value.isComplexFloat());
6292 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6293 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6294}
6295
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006296static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006297
Ted Kremenek6274be42010-09-23 21:43:44 +00006298static bool IsZero(Sema &S, Expr *E) {
6299 // Suppress cases where we are comparing against an enum constant.
6300 if (const DeclRefExpr *DR =
6301 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6302 if (isa<EnumConstantDecl>(DR->getDecl()))
6303 return false;
6304
6305 // Suppress cases where the '0' value is expanded from a macro.
6306 if (E->getLocStart().isMacroID())
6307 return false;
6308
John McCallcc7e5bf2010-05-06 08:58:33 +00006309 llvm::APSInt Value;
6310 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6311}
6312
John McCall2551c1b2010-10-06 00:25:24 +00006313static bool HasEnumType(Expr *E) {
6314 // Strip off implicit integral promotions.
6315 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006316 if (ICE->getCastKind() != CK_IntegralCast &&
6317 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00006318 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006319 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00006320 }
6321
6322 return E->getType()->isEnumeralType();
6323}
6324
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006325static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00006326 // Disable warning in template instantiations.
6327 if (!S.ActiveTemplateInstantiations.empty())
6328 return;
6329
John McCalle3027922010-08-25 11:45:40 +00006330 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00006331 if (E->isValueDependent())
6332 return;
6333
John McCalle3027922010-08-25 11:45:40 +00006334 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006335 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006336 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006337 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006338 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006339 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006340 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006341 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006342 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006343 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006344 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006345 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006346 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006347 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006348 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006349 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6350 }
6351}
6352
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006353static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006354 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006355 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006356 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00006357 // Disable warning in template instantiations.
6358 if (!S.ActiveTemplateInstantiations.empty())
6359 return;
6360
Richard Trieu0f097742014-04-04 04:13:47 +00006361 // TODO: Investigate using GetExprRange() to get tighter bounds
6362 // on the bit ranges.
6363 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00006364 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00006365 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00006366 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6367 unsigned OtherWidth = OtherRange.Width;
6368
6369 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6370
Richard Trieu560910c2012-11-14 22:50:24 +00006371 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00006372 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00006373 return;
6374
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006375 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00006376 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006377
Richard Trieu0f097742014-04-04 04:13:47 +00006378 // Used for diagnostic printout.
6379 enum {
6380 LiteralConstant = 0,
6381 CXXBoolLiteralTrue,
6382 CXXBoolLiteralFalse
6383 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006384
Richard Trieu0f097742014-04-04 04:13:47 +00006385 if (!OtherIsBooleanType) {
6386 QualType ConstantT = Constant->getType();
6387 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00006388
Richard Trieu0f097742014-04-04 04:13:47 +00006389 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6390 return;
6391 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6392 "comparison with non-integer type");
6393
6394 bool ConstantSigned = ConstantT->isSignedIntegerType();
6395 bool CommonSigned = CommonT->isSignedIntegerType();
6396
6397 bool EqualityOnly = false;
6398
6399 if (CommonSigned) {
6400 // The common type is signed, therefore no signed to unsigned conversion.
6401 if (!OtherRange.NonNegative) {
6402 // Check that the constant is representable in type OtherT.
6403 if (ConstantSigned) {
6404 if (OtherWidth >= Value.getMinSignedBits())
6405 return;
6406 } else { // !ConstantSigned
6407 if (OtherWidth >= Value.getActiveBits() + 1)
6408 return;
6409 }
6410 } else { // !OtherSigned
6411 // Check that the constant is representable in type OtherT.
6412 // Negative values are out of range.
6413 if (ConstantSigned) {
6414 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6415 return;
6416 } else { // !ConstantSigned
6417 if (OtherWidth >= Value.getActiveBits())
6418 return;
6419 }
Richard Trieu560910c2012-11-14 22:50:24 +00006420 }
Richard Trieu0f097742014-04-04 04:13:47 +00006421 } else { // !CommonSigned
6422 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006423 if (OtherWidth >= Value.getActiveBits())
6424 return;
Craig Toppercf360162014-06-18 05:13:11 +00006425 } else { // OtherSigned
6426 assert(!ConstantSigned &&
6427 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006428 // Check to see if the constant is representable in OtherT.
6429 if (OtherWidth > Value.getActiveBits())
6430 return;
6431 // Check to see if the constant is equivalent to a negative value
6432 // cast to CommonT.
6433 if (S.Context.getIntWidth(ConstantT) ==
6434 S.Context.getIntWidth(CommonT) &&
6435 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6436 return;
6437 // The constant value rests between values that OtherT can represent
6438 // after conversion. Relational comparison still works, but equality
6439 // comparisons will be tautological.
6440 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006441 }
6442 }
Richard Trieu0f097742014-04-04 04:13:47 +00006443
6444 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6445
6446 if (op == BO_EQ || op == BO_NE) {
6447 IsTrue = op == BO_NE;
6448 } else if (EqualityOnly) {
6449 return;
6450 } else if (RhsConstant) {
6451 if (op == BO_GT || op == BO_GE)
6452 IsTrue = !PositiveConstant;
6453 else // op == BO_LT || op == BO_LE
6454 IsTrue = PositiveConstant;
6455 } else {
6456 if (op == BO_LT || op == BO_LE)
6457 IsTrue = !PositiveConstant;
6458 else // op == BO_GT || op == BO_GE
6459 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006460 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006461 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00006462 // Other isKnownToHaveBooleanValue
6463 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6464 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6465 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6466
6467 static const struct LinkedConditions {
6468 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6469 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6470 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6471 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6472 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6473 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6474
6475 } TruthTable = {
6476 // Constant on LHS. | Constant on RHS. |
6477 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6478 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6479 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6480 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6481 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6482 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6483 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6484 };
6485
6486 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6487
6488 enum ConstantValue ConstVal = Zero;
6489 if (Value.isUnsigned() || Value.isNonNegative()) {
6490 if (Value == 0) {
6491 LiteralOrBoolConstant =
6492 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6493 ConstVal = Zero;
6494 } else if (Value == 1) {
6495 LiteralOrBoolConstant =
6496 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6497 ConstVal = One;
6498 } else {
6499 LiteralOrBoolConstant = LiteralConstant;
6500 ConstVal = GT_One;
6501 }
6502 } else {
6503 ConstVal = LT_Zero;
6504 }
6505
6506 CompareBoolWithConstantResult CmpRes;
6507
6508 switch (op) {
6509 case BO_LT:
6510 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6511 break;
6512 case BO_GT:
6513 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6514 break;
6515 case BO_LE:
6516 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6517 break;
6518 case BO_GE:
6519 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6520 break;
6521 case BO_EQ:
6522 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6523 break;
6524 case BO_NE:
6525 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6526 break;
6527 default:
6528 CmpRes = Unkwn;
6529 break;
6530 }
6531
6532 if (CmpRes == AFals) {
6533 IsTrue = false;
6534 } else if (CmpRes == ATrue) {
6535 IsTrue = true;
6536 } else {
6537 return;
6538 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006539 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006540
6541 // If this is a comparison to an enum constant, include that
6542 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006543 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006544 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6545 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6546
6547 SmallString<64> PrettySourceValue;
6548 llvm::raw_svector_ostream OS(PrettySourceValue);
6549 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00006550 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006551 else
6552 OS << Value;
6553
Richard Trieu0f097742014-04-04 04:13:47 +00006554 S.DiagRuntimeBehavior(
6555 E->getOperatorLoc(), E,
6556 S.PDiag(diag::warn_out_of_range_compare)
6557 << OS.str() << LiteralOrBoolConstant
6558 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6559 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006560}
6561
John McCallcc7e5bf2010-05-06 08:58:33 +00006562/// Analyze the operands of the given comparison. Implements the
6563/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006564static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00006565 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6566 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006567}
John McCall263a48b2010-01-04 23:31:57 +00006568
John McCallca01b222010-01-04 23:21:16 +00006569/// \brief Implements -Wsign-compare.
6570///
Richard Trieu82402a02011-09-15 21:56:47 +00006571/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006572static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006573 // The type the comparison is being performed in.
6574 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006575
6576 // Only analyze comparison operators where both sides have been converted to
6577 // the same type.
6578 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6579 return AnalyzeImpConvsInComparison(S, E);
6580
6581 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006582 if (E->isValueDependent())
6583 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006584
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006585 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6586 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006587
6588 bool IsComparisonConstant = false;
6589
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006590 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006591 // of 'true' or 'false'.
6592 if (T->isIntegralType(S.Context)) {
6593 llvm::APSInt RHSValue;
6594 bool IsRHSIntegralLiteral =
6595 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6596 llvm::APSInt LHSValue;
6597 bool IsLHSIntegralLiteral =
6598 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6599 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6600 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6601 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6602 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6603 else
6604 IsComparisonConstant =
6605 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006606 } else if (!T->hasUnsignedIntegerRepresentation())
6607 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006608
John McCallcc7e5bf2010-05-06 08:58:33 +00006609 // We don't do anything special if this isn't an unsigned integral
6610 // comparison: we're only interested in integral comparisons, and
6611 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00006612 //
6613 // We also don't care about value-dependent expressions or expressions
6614 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006615 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00006616 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006617
John McCallcc7e5bf2010-05-06 08:58:33 +00006618 // Check to see if one of the (unmodified) operands is of different
6619 // signedness.
6620 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00006621 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6622 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00006623 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00006624 signedOperand = LHS;
6625 unsignedOperand = RHS;
6626 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6627 signedOperand = RHS;
6628 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00006629 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00006630 CheckTrivialUnsignedComparison(S, E);
6631 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006632 }
6633
John McCallcc7e5bf2010-05-06 08:58:33 +00006634 // Otherwise, calculate the effective range of the signed operand.
6635 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00006636
John McCallcc7e5bf2010-05-06 08:58:33 +00006637 // Go ahead and analyze implicit conversions in the operands. Note
6638 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00006639 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6640 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00006641
John McCallcc7e5bf2010-05-06 08:58:33 +00006642 // If the signed range is non-negative, -Wsign-compare won't fire,
6643 // but we should still check for comparisons which are always true
6644 // or false.
6645 if (signedRange.NonNegative)
6646 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006647
6648 // For (in)equality comparisons, if the unsigned operand is a
6649 // constant which cannot collide with a overflowed signed operand,
6650 // then reinterpreting the signed operand as unsigned will not
6651 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00006652 if (E->isEqualityOp()) {
6653 unsigned comparisonWidth = S.Context.getIntWidth(T);
6654 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00006655
John McCallcc7e5bf2010-05-06 08:58:33 +00006656 // We should never be unable to prove that the unsigned operand is
6657 // non-negative.
6658 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6659
6660 if (unsignedRange.Width < comparisonWidth)
6661 return;
6662 }
6663
Douglas Gregorbfb4a212012-05-01 01:53:49 +00006664 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6665 S.PDiag(diag::warn_mixed_sign_comparison)
6666 << LHS->getType() << RHS->getType()
6667 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00006668}
6669
John McCall1f425642010-11-11 03:21:53 +00006670/// Analyzes an attempt to assign the given value to a bitfield.
6671///
6672/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006673static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6674 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00006675 assert(Bitfield->isBitField());
6676 if (Bitfield->isInvalidDecl())
6677 return false;
6678
John McCalldeebbcf2010-11-11 05:33:51 +00006679 // White-list bool bitfields.
6680 if (Bitfield->getType()->isBooleanType())
6681 return false;
6682
Douglas Gregor789adec2011-02-04 13:09:01 +00006683 // Ignore value- or type-dependent expressions.
6684 if (Bitfield->getBitWidth()->isValueDependent() ||
6685 Bitfield->getBitWidth()->isTypeDependent() ||
6686 Init->isValueDependent() ||
6687 Init->isTypeDependent())
6688 return false;
6689
John McCall1f425642010-11-11 03:21:53 +00006690 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6691
Richard Smith5fab0c92011-12-28 19:48:30 +00006692 llvm::APSInt Value;
6693 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00006694 return false;
6695
John McCall1f425642010-11-11 03:21:53 +00006696 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00006697 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00006698
6699 if (OriginalWidth <= FieldWidth)
6700 return false;
6701
Eli Friedmanc267a322012-01-26 23:11:39 +00006702 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006703 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00006704 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00006705
Eli Friedmanc267a322012-01-26 23:11:39 +00006706 // Check whether the stored value is equal to the original value.
6707 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00006708 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00006709 return false;
6710
Eli Friedmanc267a322012-01-26 23:11:39 +00006711 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00006712 // therefore don't strictly fit into a signed bitfield of width 1.
6713 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00006714 return false;
6715
John McCall1f425642010-11-11 03:21:53 +00006716 std::string PrettyValue = Value.toString(10);
6717 std::string PrettyTrunc = TruncatedValue.toString(10);
6718
6719 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6720 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6721 << Init->getSourceRange();
6722
6723 return true;
6724}
6725
John McCalld2a53122010-11-09 23:24:47 +00006726/// Analyze the given simple or compound assignment for warning-worthy
6727/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006728static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006729 // Just recurse on the LHS.
6730 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6731
6732 // We want to recurse on the RHS as normal unless we're assigning to
6733 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006734 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006735 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006736 E->getOperatorLoc())) {
6737 // Recurse, ignoring any implicit conversions on the RHS.
6738 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6739 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006740 }
6741 }
6742
6743 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6744}
6745
John McCall263a48b2010-01-04 23:31:57 +00006746/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006747static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006748 SourceLocation CContext, unsigned diag,
6749 bool pruneControlFlow = false) {
6750 if (pruneControlFlow) {
6751 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6752 S.PDiag(diag)
6753 << SourceType << T << E->getSourceRange()
6754 << SourceRange(CContext));
6755 return;
6756 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006757 S.Diag(E->getExprLoc(), diag)
6758 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6759}
6760
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006761/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006762static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006763 SourceLocation CContext, unsigned diag,
6764 bool pruneControlFlow = false) {
6765 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006766}
6767
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006768/// Diagnose an implicit cast from a literal expression. Does not warn when the
6769/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006770void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6771 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006772 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006773 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006774 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006775 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6776 T->hasUnsignedIntegerRepresentation());
6777 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006778 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006779 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006780 return;
6781
Eli Friedman07185912013-08-29 23:44:43 +00006782 // FIXME: Force the precision of the source value down so we don't print
6783 // digits which are usually useless (we don't really care here if we
6784 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6785 // would automatically print the shortest representation, but it's a bit
6786 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006787 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006788 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6789 precision = (precision * 59 + 195) / 196;
6790 Value.toString(PrettySourceValue, precision);
6791
David Blaikie9b88cc02012-05-15 17:18:27 +00006792 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006793 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6794 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6795 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006796 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006797
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006798 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006799 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6800 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006801}
6802
John McCall18a2c2c2010-11-09 22:22:12 +00006803std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6804 if (!Range.Width) return "0";
6805
6806 llvm::APSInt ValueInRange = Value;
6807 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006808 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006809 return ValueInRange.toString(10);
6810}
6811
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006812static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6813 if (!isa<ImplicitCastExpr>(Ex))
6814 return false;
6815
6816 Expr *InnerE = Ex->IgnoreParenImpCasts();
6817 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6818 const Type *Source =
6819 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6820 if (Target->isDependentType())
6821 return false;
6822
6823 const BuiltinType *FloatCandidateBT =
6824 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6825 const Type *BoolCandidateType = ToBool ? Target : Source;
6826
6827 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6828 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6829}
6830
6831void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6832 SourceLocation CC) {
6833 unsigned NumArgs = TheCall->getNumArgs();
6834 for (unsigned i = 0; i < NumArgs; ++i) {
6835 Expr *CurrA = TheCall->getArg(i);
6836 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6837 continue;
6838
6839 bool IsSwapped = ((i > 0) &&
6840 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6841 IsSwapped |= ((i < (NumArgs - 1)) &&
6842 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6843 if (IsSwapped) {
6844 // Warn on this floating-point to bool conversion.
6845 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6846 CurrA->getType(), CC,
6847 diag::warn_impcast_floating_point_to_bool);
6848 }
6849 }
6850}
6851
Richard Trieu5b993502014-10-15 03:42:06 +00006852static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6853 SourceLocation CC) {
6854 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6855 E->getExprLoc()))
6856 return;
6857
6858 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6859 const Expr::NullPointerConstantKind NullKind =
6860 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6861 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6862 return;
6863
6864 // Return if target type is a safe conversion.
6865 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6866 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6867 return;
6868
6869 SourceLocation Loc = E->getSourceRange().getBegin();
6870
6871 // __null is usually wrapped in a macro. Go up a macro if that is the case.
6872 if (NullKind == Expr::NPCK_GNUNull) {
6873 if (Loc.isMacroID())
6874 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6875 }
6876
6877 // Only warn if the null and context location are in the same macro expansion.
6878 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6879 return;
6880
6881 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6882 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6883 << FixItHint::CreateReplacement(Loc,
6884 S.getFixItZeroLiteralForType(T, Loc));
6885}
6886
John McCallcc7e5bf2010-05-06 08:58:33 +00006887void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00006888 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006889 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00006890
John McCallcc7e5bf2010-05-06 08:58:33 +00006891 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6892 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6893 if (Source == Target) return;
6894 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00006895
Chandler Carruthc22845a2011-07-26 05:40:03 +00006896 // If the conversion context location is invalid don't complain. We also
6897 // don't want to emit a warning if the issue occurs from the expansion of
6898 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6899 // delay this check as long as possible. Once we detect we are in that
6900 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006901 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00006902 return;
6903
Richard Trieu021baa32011-09-23 20:10:00 +00006904 // Diagnose implicit casts to bool.
6905 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6906 if (isa<StringLiteral>(E))
6907 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00006908 // and expressions, for instance, assert(0 && "error here"), are
6909 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00006910 return DiagnoseImpCast(S, E, T, CC,
6911 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00006912 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6913 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6914 // This covers the literal expressions that evaluate to Objective-C
6915 // objects.
6916 return DiagnoseImpCast(S, E, T, CC,
6917 diag::warn_impcast_objective_c_literal_to_bool);
6918 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006919 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6920 // Warn on pointer to bool conversion that is always true.
6921 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6922 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00006923 }
Richard Trieu021baa32011-09-23 20:10:00 +00006924 }
John McCall263a48b2010-01-04 23:31:57 +00006925
6926 // Strip vector types.
6927 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006928 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006929 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006930 return;
John McCallacf0ee52010-10-08 02:01:28 +00006931 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006932 }
Chris Lattneree7286f2011-06-14 04:51:15 +00006933
6934 // If the vector cast is cast between two vectors of the same size, it is
6935 // a bitcast, not a conversion.
6936 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6937 return;
John McCall263a48b2010-01-04 23:31:57 +00006938
6939 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6940 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6941 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00006942 if (auto VecTy = dyn_cast<VectorType>(Target))
6943 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00006944
6945 // Strip complex types.
6946 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006947 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006948 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006949 return;
6950
John McCallacf0ee52010-10-08 02:01:28 +00006951 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006952 }
John McCall263a48b2010-01-04 23:31:57 +00006953
6954 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6955 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6956 }
6957
6958 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6959 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6960
6961 // If the source is floating point...
6962 if (SourceBT && SourceBT->isFloatingPoint()) {
6963 // ...and the target is floating point...
6964 if (TargetBT && TargetBT->isFloatingPoint()) {
6965 // ...then warn if we're dropping FP rank.
6966
6967 // Builtin FP kinds are ordered by increasing FP rank.
6968 if (SourceBT->getKind() > TargetBT->getKind()) {
6969 // Don't warn about float constants that are precisely
6970 // representable in the target type.
6971 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006972 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00006973 // Value might be a float, a float vector, or a float complex.
6974 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00006975 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6976 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00006977 return;
6978 }
6979
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006980 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006981 return;
6982
John McCallacf0ee52010-10-08 02:01:28 +00006983 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00006984 }
6985 return;
6986 }
6987
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006988 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00006989 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006990 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006991 return;
6992
Chandler Carruth22c7a792011-02-17 11:05:49 +00006993 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00006994 // We also want to warn on, e.g., "int i = -1.234"
6995 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6996 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6997 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6998
Chandler Carruth016ef402011-04-10 08:36:24 +00006999 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
7000 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00007001 } else {
7002 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
7003 }
7004 }
John McCall263a48b2010-01-04 23:31:57 +00007005
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007006 // If the target is bool, warn if expr is a function or method call.
7007 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
7008 isa<CallExpr>(E)) {
7009 // Check last argument of function call to see if it is an
7010 // implicit cast from a type matching the type the result
7011 // is being cast to.
7012 CallExpr *CEx = cast<CallExpr>(E);
7013 unsigned NumArgs = CEx->getNumArgs();
7014 if (NumArgs > 0) {
7015 Expr *LastA = CEx->getArg(NumArgs - 1);
7016 Expr *InnerE = LastA->IgnoreParenImpCasts();
7017 const Type *InnerType =
7018 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7019 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
7020 // Warn on this floating-point to bool conversion
7021 DiagnoseImpCast(S, E, T, CC,
7022 diag::warn_impcast_floating_point_to_bool);
7023 }
7024 }
7025 }
John McCall263a48b2010-01-04 23:31:57 +00007026 return;
7027 }
7028
Richard Trieu5b993502014-10-15 03:42:06 +00007029 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00007030
David Blaikie9366d2b2012-06-19 21:19:06 +00007031 if (!Source->isIntegerType() || !Target->isIntegerType())
7032 return;
7033
David Blaikie7555b6a2012-05-15 16:56:36 +00007034 // TODO: remove this early return once the false positives for constant->bool
7035 // in templates, macros, etc, are reduced or removed.
7036 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
7037 return;
7038
John McCallcc7e5bf2010-05-06 08:58:33 +00007039 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00007040 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00007041
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007042 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00007043 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007044 // TODO: this should happen for bitfield stores, too.
7045 llvm::APSInt Value(32);
7046 if (E->isIntegerConstantExpr(Value, S.Context)) {
7047 if (S.SourceMgr.isInSystemMacro(CC))
7048 return;
7049
John McCall18a2c2c2010-11-09 22:22:12 +00007050 std::string PrettySourceValue = Value.toString(10);
7051 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007052
Ted Kremenek33ba9952011-10-22 02:37:33 +00007053 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7054 S.PDiag(diag::warn_impcast_integer_precision_constant)
7055 << PrettySourceValue << PrettyTargetValue
7056 << E->getType() << T << E->getSourceRange()
7057 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00007058 return;
7059 }
7060
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007061 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
7062 if (S.SourceMgr.isInSystemMacro(CC))
7063 return;
7064
David Blaikie9455da02012-04-12 22:40:54 +00007065 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00007066 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
7067 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00007068 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00007069 }
7070
7071 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
7072 (!TargetRange.NonNegative && SourceRange.NonNegative &&
7073 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007074
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007075 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007076 return;
7077
John McCallcc7e5bf2010-05-06 08:58:33 +00007078 unsigned DiagID = diag::warn_impcast_integer_sign;
7079
7080 // Traditionally, gcc has warned about this under -Wsign-compare.
7081 // We also want to warn about it in -Wconversion.
7082 // So if -Wconversion is off, use a completely identical diagnostic
7083 // in the sign-compare group.
7084 // The conditional-checking code will
7085 if (ICContext) {
7086 DiagID = diag::warn_impcast_integer_sign_conditional;
7087 *ICContext = true;
7088 }
7089
John McCallacf0ee52010-10-08 02:01:28 +00007090 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00007091 }
7092
Douglas Gregora78f1932011-02-22 02:45:07 +00007093 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00007094 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
7095 // type, to give us better diagnostics.
7096 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007097 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00007098 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7099 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
7100 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
7101 SourceType = S.Context.getTypeDeclType(Enum);
7102 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
7103 }
7104 }
7105
Douglas Gregora78f1932011-02-22 02:45:07 +00007106 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
7107 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00007108 if (SourceEnum->getDecl()->hasNameForLinkage() &&
7109 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007110 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007111 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007112 return;
7113
Douglas Gregor364f7db2011-03-12 00:14:31 +00007114 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00007115 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007116 }
Douglas Gregora78f1932011-02-22 02:45:07 +00007117
John McCall263a48b2010-01-04 23:31:57 +00007118 return;
7119}
7120
David Blaikie18e9ac72012-05-15 21:57:38 +00007121void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7122 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007123
7124void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00007125 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007126 E = E->IgnoreParenImpCasts();
7127
7128 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00007129 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007130
John McCallacf0ee52010-10-08 02:01:28 +00007131 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007132 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007133 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00007134 return;
7135}
7136
David Blaikie18e9ac72012-05-15 21:57:38 +00007137void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7138 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00007139 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007140
7141 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00007142 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
7143 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007144
7145 // If -Wconversion would have warned about either of the candidates
7146 // for a signedness conversion to the context type...
7147 if (!Suspicious) return;
7148
7149 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007150 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00007151 return;
7152
John McCallcc7e5bf2010-05-06 08:58:33 +00007153 // ...then check whether it would have warned about either of the
7154 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00007155 if (E->getType() == T) return;
7156
7157 Suspicious = false;
7158 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
7159 E->getType(), CC, &Suspicious);
7160 if (!Suspicious)
7161 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00007162 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007163}
7164
Richard Trieu65724892014-11-15 06:37:39 +00007165/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7166/// Input argument E is a logical expression.
7167static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
7168 if (S.getLangOpts().Bool)
7169 return;
7170 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
7171}
7172
John McCallcc7e5bf2010-05-06 08:58:33 +00007173/// AnalyzeImplicitConversions - Find and report any interesting
7174/// implicit conversions in the given expression. There are a couple
7175/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007176void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00007177 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00007178 Expr *E = OrigE->IgnoreParenImpCasts();
7179
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00007180 if (E->isTypeDependent() || E->isValueDependent())
7181 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00007182
John McCallcc7e5bf2010-05-06 08:58:33 +00007183 // For conditional operators, we analyze the arguments as if they
7184 // were being fed directly into the output.
7185 if (isa<ConditionalOperator>(E)) {
7186 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00007187 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007188 return;
7189 }
7190
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007191 // Check implicit argument conversions for function calls.
7192 if (CallExpr *Call = dyn_cast<CallExpr>(E))
7193 CheckImplicitArgumentConversions(S, Call, CC);
7194
John McCallcc7e5bf2010-05-06 08:58:33 +00007195 // Go ahead and check any implicit conversions we might have skipped.
7196 // The non-canonical typecheck is just an optimization;
7197 // CheckImplicitConversion will filter out dead implicit conversions.
7198 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007199 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007200
7201 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00007202
7203 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00007204 if (POE->getResultExpr())
7205 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00007206 }
7207
Fariborz Jahanian947efbc2015-02-26 17:59:54 +00007208 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
7209 if (OVE->getSourceExpr())
7210 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
7211 return;
7212 }
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00007213
John McCallcc7e5bf2010-05-06 08:58:33 +00007214 // Skip past explicit casts.
7215 if (isa<ExplicitCastExpr>(E)) {
7216 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00007217 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007218 }
7219
John McCalld2a53122010-11-09 23:24:47 +00007220 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7221 // Do a somewhat different check with comparison operators.
7222 if (BO->isComparisonOp())
7223 return AnalyzeComparison(S, BO);
7224
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007225 // And with simple assignments.
7226 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00007227 return AnalyzeAssignment(S, BO);
7228 }
John McCallcc7e5bf2010-05-06 08:58:33 +00007229
7230 // These break the otherwise-useful invariant below. Fortunately,
7231 // we don't really need to recurse into them, because any internal
7232 // expressions should have been analyzed already when they were
7233 // built into statements.
7234 if (isa<StmtExpr>(E)) return;
7235
7236 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00007237 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00007238
7239 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00007240 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00007241 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00007242 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00007243 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00007244 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00007245 if (!ChildExpr)
7246 continue;
7247
Richard Trieu955231d2014-01-25 01:10:35 +00007248 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00007249 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00007250 // Ignore checking string literals that are in logical and operators.
7251 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00007252 continue;
7253 AnalyzeImplicitConversions(S, ChildExpr, CC);
7254 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007255
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007256 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00007257 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
7258 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007259 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00007260
7261 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
7262 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007263 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007264 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007265
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007266 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
7267 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00007268 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007269}
7270
7271} // end anonymous namespace
7272
Richard Trieu3bb8b562014-02-26 02:36:06 +00007273enum {
7274 AddressOf,
7275 FunctionPointer,
7276 ArrayPointer
7277};
7278
Richard Trieuc1888e02014-06-28 23:25:37 +00007279// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
7280// Returns true when emitting a warning about taking the address of a reference.
7281static bool CheckForReference(Sema &SemaRef, const Expr *E,
7282 PartialDiagnostic PD) {
7283 E = E->IgnoreParenImpCasts();
7284
7285 const FunctionDecl *FD = nullptr;
7286
7287 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7288 if (!DRE->getDecl()->getType()->isReferenceType())
7289 return false;
7290 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7291 if (!M->getMemberDecl()->getType()->isReferenceType())
7292 return false;
7293 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00007294 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00007295 return false;
7296 FD = Call->getDirectCallee();
7297 } else {
7298 return false;
7299 }
7300
7301 SemaRef.Diag(E->getExprLoc(), PD);
7302
7303 // If possible, point to location of function.
7304 if (FD) {
7305 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
7306 }
7307
7308 return true;
7309}
7310
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007311// Returns true if the SourceLocation is expanded from any macro body.
7312// Returns false if the SourceLocation is invalid, is from not in a macro
7313// expansion, or is from expanded from a top-level macro argument.
7314static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
7315 if (Loc.isInvalid())
7316 return false;
7317
7318 while (Loc.isMacroID()) {
7319 if (SM.isMacroBodyExpansion(Loc))
7320 return true;
7321 Loc = SM.getImmediateMacroCallerLoc(Loc);
7322 }
7323
7324 return false;
7325}
7326
Richard Trieu3bb8b562014-02-26 02:36:06 +00007327/// \brief Diagnose pointers that are always non-null.
7328/// \param E the expression containing the pointer
7329/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
7330/// compared to a null pointer
7331/// \param IsEqual True when the comparison is equal to a null pointer
7332/// \param Range Extra SourceRange to highlight in the diagnostic
7333void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
7334 Expr::NullPointerConstantKind NullKind,
7335 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00007336 if (!E)
7337 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007338
7339 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007340 if (E->getExprLoc().isMacroID()) {
7341 const SourceManager &SM = getSourceManager();
7342 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
7343 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00007344 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007345 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007346 E = E->IgnoreImpCasts();
7347
7348 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
7349
Richard Trieuf7432752014-06-06 21:39:26 +00007350 if (isa<CXXThisExpr>(E)) {
7351 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
7352 : diag::warn_this_bool_conversion;
7353 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
7354 return;
7355 }
7356
Richard Trieu3bb8b562014-02-26 02:36:06 +00007357 bool IsAddressOf = false;
7358
7359 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7360 if (UO->getOpcode() != UO_AddrOf)
7361 return;
7362 IsAddressOf = true;
7363 E = UO->getSubExpr();
7364 }
7365
Richard Trieuc1888e02014-06-28 23:25:37 +00007366 if (IsAddressOf) {
7367 unsigned DiagID = IsCompare
7368 ? diag::warn_address_of_reference_null_compare
7369 : diag::warn_address_of_reference_bool_conversion;
7370 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
7371 << IsEqual;
7372 if (CheckForReference(*this, E, PD)) {
7373 return;
7374 }
7375 }
7376
Richard Trieu3bb8b562014-02-26 02:36:06 +00007377 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00007378 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007379 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
7380 D = R->getDecl();
7381 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7382 D = M->getMemberDecl();
7383 }
7384
7385 // Weak Decls can be null.
7386 if (!D || D->isWeak())
7387 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007388
7389 // Check for parameter decl with nonnull attribute
7390 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
7391 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
7392 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
7393 unsigned NumArgs = FD->getNumParams();
7394 llvm::SmallBitVector AttrNonNull(NumArgs);
7395 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
7396 if (!NonNull->args_size()) {
7397 AttrNonNull.set(0, NumArgs);
7398 break;
7399 }
7400 for (unsigned Val : NonNull->args()) {
7401 if (Val >= NumArgs)
7402 continue;
7403 AttrNonNull.set(Val);
7404 }
7405 }
7406 if (!AttrNonNull.empty())
7407 for (unsigned i = 0; i < NumArgs; ++i)
Aaron Ballman2521f362014-12-11 19:35:42 +00007408 if (FD->getParamDecl(i) == PV &&
7409 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007410 std::string Str;
7411 llvm::raw_string_ostream S(Str);
7412 E->printPretty(S, nullptr, getPrintingPolicy());
7413 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
7414 : diag::warn_cast_nonnull_to_bool;
7415 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
7416 << Range << IsEqual;
7417 return;
7418 }
7419 }
7420 }
7421
Richard Trieu3bb8b562014-02-26 02:36:06 +00007422 QualType T = D->getType();
7423 const bool IsArray = T->isArrayType();
7424 const bool IsFunction = T->isFunctionType();
7425
Richard Trieuc1888e02014-06-28 23:25:37 +00007426 // Address of function is used to silence the function warning.
7427 if (IsAddressOf && IsFunction) {
7428 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007429 }
7430
7431 // Found nothing.
7432 if (!IsAddressOf && !IsFunction && !IsArray)
7433 return;
7434
7435 // Pretty print the expression for the diagnostic.
7436 std::string Str;
7437 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00007438 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00007439
7440 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7441 : diag::warn_impcast_pointer_to_bool;
7442 unsigned DiagType;
7443 if (IsAddressOf)
7444 DiagType = AddressOf;
7445 else if (IsFunction)
7446 DiagType = FunctionPointer;
7447 else if (IsArray)
7448 DiagType = ArrayPointer;
7449 else
7450 llvm_unreachable("Could not determine diagnostic.");
7451 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7452 << Range << IsEqual;
7453
7454 if (!IsFunction)
7455 return;
7456
7457 // Suggest '&' to silence the function warning.
7458 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7459 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7460
7461 // Check to see if '()' fixit should be emitted.
7462 QualType ReturnType;
7463 UnresolvedSet<4> NonTemplateOverloads;
7464 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7465 if (ReturnType.isNull())
7466 return;
7467
7468 if (IsCompare) {
7469 // There are two cases here. If there is null constant, the only suggest
7470 // for a pointer return type. If the null is 0, then suggest if the return
7471 // type is a pointer or an integer type.
7472 if (!ReturnType->isPointerType()) {
7473 if (NullKind == Expr::NPCK_ZeroExpression ||
7474 NullKind == Expr::NPCK_ZeroLiteral) {
7475 if (!ReturnType->isIntegerType())
7476 return;
7477 } else {
7478 return;
7479 }
7480 }
7481 } else { // !IsCompare
7482 // For function to bool, only suggest if the function pointer has bool
7483 // return type.
7484 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7485 return;
7486 }
7487 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007488 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00007489}
7490
7491
John McCallcc7e5bf2010-05-06 08:58:33 +00007492/// Diagnoses "dangerous" implicit conversions within the given
7493/// expression (which is a full expression). Implements -Wconversion
7494/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007495///
7496/// \param CC the "context" location of the implicit conversion, i.e.
7497/// the most location of the syntactic entity requiring the implicit
7498/// conversion
7499void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007500 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00007501 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00007502 return;
7503
7504 // Don't diagnose for value- or type-dependent expressions.
7505 if (E->isTypeDependent() || E->isValueDependent())
7506 return;
7507
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007508 // Check for array bounds violations in cases where the check isn't triggered
7509 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7510 // ArraySubscriptExpr is on the RHS of a variable initialization.
7511 CheckArrayAccess(E);
7512
John McCallacf0ee52010-10-08 02:01:28 +00007513 // This is not the right CC for (e.g.) a variable initialization.
7514 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007515}
7516
Richard Trieu65724892014-11-15 06:37:39 +00007517/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7518/// Input argument E is a logical expression.
7519void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7520 ::CheckBoolLikeConversion(*this, E, CC);
7521}
7522
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007523/// Diagnose when expression is an integer constant expression and its evaluation
7524/// results in integer overflow
7525void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00007526 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7527 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007528}
7529
Richard Smithc406cb72013-01-17 01:17:56 +00007530namespace {
7531/// \brief Visitor for expressions which looks for unsequenced operations on the
7532/// same object.
7533class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007534 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7535
Richard Smithc406cb72013-01-17 01:17:56 +00007536 /// \brief A tree of sequenced regions within an expression. Two regions are
7537 /// unsequenced if one is an ancestor or a descendent of the other. When we
7538 /// finish processing an expression with sequencing, such as a comma
7539 /// expression, we fold its tree nodes into its parent, since they are
7540 /// unsequenced with respect to nodes we will visit later.
7541 class SequenceTree {
7542 struct Value {
7543 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7544 unsigned Parent : 31;
7545 bool Merged : 1;
7546 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007547 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00007548
7549 public:
7550 /// \brief A region within an expression which may be sequenced with respect
7551 /// to some other region.
7552 class Seq {
7553 explicit Seq(unsigned N) : Index(N) {}
7554 unsigned Index;
7555 friend class SequenceTree;
7556 public:
7557 Seq() : Index(0) {}
7558 };
7559
7560 SequenceTree() { Values.push_back(Value(0)); }
7561 Seq root() const { return Seq(0); }
7562
7563 /// \brief Create a new sequence of operations, which is an unsequenced
7564 /// subset of \p Parent. This sequence of operations is sequenced with
7565 /// respect to other children of \p Parent.
7566 Seq allocate(Seq Parent) {
7567 Values.push_back(Value(Parent.Index));
7568 return Seq(Values.size() - 1);
7569 }
7570
7571 /// \brief Merge a sequence of operations into its parent.
7572 void merge(Seq S) {
7573 Values[S.Index].Merged = true;
7574 }
7575
7576 /// \brief Determine whether two operations are unsequenced. This operation
7577 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7578 /// should have been merged into its parent as appropriate.
7579 bool isUnsequenced(Seq Cur, Seq Old) {
7580 unsigned C = representative(Cur.Index);
7581 unsigned Target = representative(Old.Index);
7582 while (C >= Target) {
7583 if (C == Target)
7584 return true;
7585 C = Values[C].Parent;
7586 }
7587 return false;
7588 }
7589
7590 private:
7591 /// \brief Pick a representative for a sequence.
7592 unsigned representative(unsigned K) {
7593 if (Values[K].Merged)
7594 // Perform path compression as we go.
7595 return Values[K].Parent = representative(Values[K].Parent);
7596 return K;
7597 }
7598 };
7599
7600 /// An object for which we can track unsequenced uses.
7601 typedef NamedDecl *Object;
7602
7603 /// Different flavors of object usage which we track. We only track the
7604 /// least-sequenced usage of each kind.
7605 enum UsageKind {
7606 /// A read of an object. Multiple unsequenced reads are OK.
7607 UK_Use,
7608 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00007609 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00007610 UK_ModAsValue,
7611 /// A modification of an object which is not sequenced before the value
7612 /// computation of the expression, such as n++.
7613 UK_ModAsSideEffect,
7614
7615 UK_Count = UK_ModAsSideEffect + 1
7616 };
7617
7618 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00007619 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00007620 Expr *Use;
7621 SequenceTree::Seq Seq;
7622 };
7623
7624 struct UsageInfo {
7625 UsageInfo() : Diagnosed(false) {}
7626 Usage Uses[UK_Count];
7627 /// Have we issued a diagnostic for this variable already?
7628 bool Diagnosed;
7629 };
7630 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7631
7632 Sema &SemaRef;
7633 /// Sequenced regions within the expression.
7634 SequenceTree Tree;
7635 /// Declaration modifications and references which we have seen.
7636 UsageInfoMap UsageMap;
7637 /// The region we are currently within.
7638 SequenceTree::Seq Region;
7639 /// Filled in with declarations which were modified as a side-effect
7640 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007641 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00007642 /// Expressions to check later. We defer checking these to reduce
7643 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007644 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00007645
7646 /// RAII object wrapping the visitation of a sequenced subexpression of an
7647 /// expression. At the end of this process, the side-effects of the evaluation
7648 /// become sequenced with respect to the value computation of the result, so
7649 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7650 /// UK_ModAsValue.
7651 struct SequencedSubexpression {
7652 SequencedSubexpression(SequenceChecker &Self)
7653 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7654 Self.ModAsSideEffect = &ModAsSideEffect;
7655 }
7656 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00007657 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7658 MI != ME; ++MI) {
7659 UsageInfo &U = Self.UsageMap[MI->first];
7660 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7661 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7662 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00007663 }
7664 Self.ModAsSideEffect = OldModAsSideEffect;
7665 }
7666
7667 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007668 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7669 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00007670 };
7671
Richard Smith40238f02013-06-20 22:21:56 +00007672 /// RAII object wrapping the visitation of a subexpression which we might
7673 /// choose to evaluate as a constant. If any subexpression is evaluated and
7674 /// found to be non-constant, this allows us to suppress the evaluation of
7675 /// the outer expression.
7676 class EvaluationTracker {
7677 public:
7678 EvaluationTracker(SequenceChecker &Self)
7679 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7680 Self.EvalTracker = this;
7681 }
7682 ~EvaluationTracker() {
7683 Self.EvalTracker = Prev;
7684 if (Prev)
7685 Prev->EvalOK &= EvalOK;
7686 }
7687
7688 bool evaluate(const Expr *E, bool &Result) {
7689 if (!EvalOK || E->isValueDependent())
7690 return false;
7691 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7692 return EvalOK;
7693 }
7694
7695 private:
7696 SequenceChecker &Self;
7697 EvaluationTracker *Prev;
7698 bool EvalOK;
7699 } *EvalTracker;
7700
Richard Smithc406cb72013-01-17 01:17:56 +00007701 /// \brief Find the object which is produced by the specified expression,
7702 /// if any.
7703 Object getObject(Expr *E, bool Mod) const {
7704 E = E->IgnoreParenCasts();
7705 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7706 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7707 return getObject(UO->getSubExpr(), Mod);
7708 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7709 if (BO->getOpcode() == BO_Comma)
7710 return getObject(BO->getRHS(), Mod);
7711 if (Mod && BO->isAssignmentOp())
7712 return getObject(BO->getLHS(), Mod);
7713 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7714 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7715 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7716 return ME->getMemberDecl();
7717 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7718 // FIXME: If this is a reference, map through to its value.
7719 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00007720 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00007721 }
7722
7723 /// \brief Note that an object was modified or used by an expression.
7724 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7725 Usage &U = UI.Uses[UK];
7726 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7727 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7728 ModAsSideEffect->push_back(std::make_pair(O, U));
7729 U.Use = Ref;
7730 U.Seq = Region;
7731 }
7732 }
7733 /// \brief Check whether a modification or use conflicts with a prior usage.
7734 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7735 bool IsModMod) {
7736 if (UI.Diagnosed)
7737 return;
7738
7739 const Usage &U = UI.Uses[OtherKind];
7740 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7741 return;
7742
7743 Expr *Mod = U.Use;
7744 Expr *ModOrUse = Ref;
7745 if (OtherKind == UK_Use)
7746 std::swap(Mod, ModOrUse);
7747
7748 SemaRef.Diag(Mod->getExprLoc(),
7749 IsModMod ? diag::warn_unsequenced_mod_mod
7750 : diag::warn_unsequenced_mod_use)
7751 << O << SourceRange(ModOrUse->getExprLoc());
7752 UI.Diagnosed = true;
7753 }
7754
7755 void notePreUse(Object O, Expr *Use) {
7756 UsageInfo &U = UsageMap[O];
7757 // Uses conflict with other modifications.
7758 checkUsage(O, U, Use, UK_ModAsValue, false);
7759 }
7760 void notePostUse(Object O, Expr *Use) {
7761 UsageInfo &U = UsageMap[O];
7762 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7763 addUsage(U, O, Use, UK_Use);
7764 }
7765
7766 void notePreMod(Object O, Expr *Mod) {
7767 UsageInfo &U = UsageMap[O];
7768 // Modifications conflict with other modifications and with uses.
7769 checkUsage(O, U, Mod, UK_ModAsValue, true);
7770 checkUsage(O, U, Mod, UK_Use, false);
7771 }
7772 void notePostMod(Object O, Expr *Use, UsageKind UK) {
7773 UsageInfo &U = UsageMap[O];
7774 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7775 addUsage(U, O, Use, UK);
7776 }
7777
7778public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007779 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00007780 : Base(S.Context), SemaRef(S), Region(Tree.root()),
7781 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007782 Visit(E);
7783 }
7784
7785 void VisitStmt(Stmt *S) {
7786 // Skip all statements which aren't expressions for now.
7787 }
7788
7789 void VisitExpr(Expr *E) {
7790 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00007791 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007792 }
7793
7794 void VisitCastExpr(CastExpr *E) {
7795 Object O = Object();
7796 if (E->getCastKind() == CK_LValueToRValue)
7797 O = getObject(E->getSubExpr(), false);
7798
7799 if (O)
7800 notePreUse(O, E);
7801 VisitExpr(E);
7802 if (O)
7803 notePostUse(O, E);
7804 }
7805
7806 void VisitBinComma(BinaryOperator *BO) {
7807 // C++11 [expr.comma]p1:
7808 // Every value computation and side effect associated with the left
7809 // expression is sequenced before every value computation and side
7810 // effect associated with the right expression.
7811 SequenceTree::Seq LHS = Tree.allocate(Region);
7812 SequenceTree::Seq RHS = Tree.allocate(Region);
7813 SequenceTree::Seq OldRegion = Region;
7814
7815 {
7816 SequencedSubexpression SeqLHS(*this);
7817 Region = LHS;
7818 Visit(BO->getLHS());
7819 }
7820
7821 Region = RHS;
7822 Visit(BO->getRHS());
7823
7824 Region = OldRegion;
7825
7826 // Forget that LHS and RHS are sequenced. They are both unsequenced
7827 // with respect to other stuff.
7828 Tree.merge(LHS);
7829 Tree.merge(RHS);
7830 }
7831
7832 void VisitBinAssign(BinaryOperator *BO) {
7833 // The modification is sequenced after the value computation of the LHS
7834 // and RHS, so check it before inspecting the operands and update the
7835 // map afterwards.
7836 Object O = getObject(BO->getLHS(), true);
7837 if (!O)
7838 return VisitExpr(BO);
7839
7840 notePreMod(O, BO);
7841
7842 // C++11 [expr.ass]p7:
7843 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7844 // only once.
7845 //
7846 // Therefore, for a compound assignment operator, O is considered used
7847 // everywhere except within the evaluation of E1 itself.
7848 if (isa<CompoundAssignOperator>(BO))
7849 notePreUse(O, BO);
7850
7851 Visit(BO->getLHS());
7852
7853 if (isa<CompoundAssignOperator>(BO))
7854 notePostUse(O, BO);
7855
7856 Visit(BO->getRHS());
7857
Richard Smith83e37bee2013-06-26 23:16:51 +00007858 // C++11 [expr.ass]p1:
7859 // the assignment is sequenced [...] before the value computation of the
7860 // assignment expression.
7861 // C11 6.5.16/3 has no such rule.
7862 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7863 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007864 }
7865 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7866 VisitBinAssign(CAO);
7867 }
7868
7869 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7870 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7871 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7872 Object O = getObject(UO->getSubExpr(), true);
7873 if (!O)
7874 return VisitExpr(UO);
7875
7876 notePreMod(O, UO);
7877 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00007878 // C++11 [expr.pre.incr]p1:
7879 // the expression ++x is equivalent to x+=1
7880 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7881 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007882 }
7883
7884 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7885 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7886 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7887 Object O = getObject(UO->getSubExpr(), true);
7888 if (!O)
7889 return VisitExpr(UO);
7890
7891 notePreMod(O, UO);
7892 Visit(UO->getSubExpr());
7893 notePostMod(O, UO, UK_ModAsSideEffect);
7894 }
7895
7896 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7897 void VisitBinLOr(BinaryOperator *BO) {
7898 // The side-effects of the LHS of an '&&' are sequenced before the
7899 // value computation of the RHS, and hence before the value computation
7900 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7901 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00007902 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007903 {
7904 SequencedSubexpression Sequenced(*this);
7905 Visit(BO->getLHS());
7906 }
7907
7908 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007909 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007910 if (!Result)
7911 Visit(BO->getRHS());
7912 } else {
7913 // Check for unsequenced operations in the RHS, treating it as an
7914 // entirely separate evaluation.
7915 //
7916 // FIXME: If there are operations in the RHS which are unsequenced
7917 // with respect to operations outside the RHS, and those operations
7918 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00007919 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007920 }
Richard Smithc406cb72013-01-17 01:17:56 +00007921 }
7922 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00007923 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007924 {
7925 SequencedSubexpression Sequenced(*this);
7926 Visit(BO->getLHS());
7927 }
7928
7929 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007930 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007931 if (Result)
7932 Visit(BO->getRHS());
7933 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00007934 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007935 }
Richard Smithc406cb72013-01-17 01:17:56 +00007936 }
7937
7938 // Only visit the condition, unless we can be sure which subexpression will
7939 // be chosen.
7940 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00007941 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00007942 {
7943 SequencedSubexpression Sequenced(*this);
7944 Visit(CO->getCond());
7945 }
Richard Smithc406cb72013-01-17 01:17:56 +00007946
7947 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007948 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00007949 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007950 else {
Richard Smithd33f5202013-01-17 23:18:09 +00007951 WorkList.push_back(CO->getTrueExpr());
7952 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007953 }
Richard Smithc406cb72013-01-17 01:17:56 +00007954 }
7955
Richard Smithe3dbfe02013-06-30 10:40:20 +00007956 void VisitCallExpr(CallExpr *CE) {
7957 // C++11 [intro.execution]p15:
7958 // When calling a function [...], every value computation and side effect
7959 // associated with any argument expression, or with the postfix expression
7960 // designating the called function, is sequenced before execution of every
7961 // expression or statement in the body of the function [and thus before
7962 // the value computation of its result].
7963 SequencedSubexpression Sequenced(*this);
7964 Base::VisitCallExpr(CE);
7965
7966 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7967 }
7968
Richard Smithc406cb72013-01-17 01:17:56 +00007969 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007970 // This is a call, so all subexpressions are sequenced before the result.
7971 SequencedSubexpression Sequenced(*this);
7972
Richard Smithc406cb72013-01-17 01:17:56 +00007973 if (!CCE->isListInitialization())
7974 return VisitExpr(CCE);
7975
7976 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007977 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007978 SequenceTree::Seq Parent = Region;
7979 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7980 E = CCE->arg_end();
7981 I != E; ++I) {
7982 Region = Tree.allocate(Parent);
7983 Elts.push_back(Region);
7984 Visit(*I);
7985 }
7986
7987 // Forget that the initializers are sequenced.
7988 Region = Parent;
7989 for (unsigned I = 0; I < Elts.size(); ++I)
7990 Tree.merge(Elts[I]);
7991 }
7992
7993 void VisitInitListExpr(InitListExpr *ILE) {
7994 if (!SemaRef.getLangOpts().CPlusPlus11)
7995 return VisitExpr(ILE);
7996
7997 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007998 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007999 SequenceTree::Seq Parent = Region;
8000 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
8001 Expr *E = ILE->getInit(I);
8002 if (!E) continue;
8003 Region = Tree.allocate(Parent);
8004 Elts.push_back(Region);
8005 Visit(E);
8006 }
8007
8008 // Forget that the initializers are sequenced.
8009 Region = Parent;
8010 for (unsigned I = 0; I < Elts.size(); ++I)
8011 Tree.merge(Elts[I]);
8012 }
8013};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008014}
Richard Smithc406cb72013-01-17 01:17:56 +00008015
8016void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008017 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00008018 WorkList.push_back(E);
8019 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00008020 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00008021 SequenceChecker(*this, Item, WorkList);
8022 }
Richard Smithc406cb72013-01-17 01:17:56 +00008023}
8024
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008025void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
8026 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008027 CheckImplicitConversions(E, CheckLoc);
8028 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008029 if (!IsConstexpr && !E->isValueDependent())
8030 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008031}
8032
John McCall1f425642010-11-11 03:21:53 +00008033void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
8034 FieldDecl *BitField,
8035 Expr *Init) {
8036 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
8037}
8038
David Majnemer61a5bbf2015-04-07 22:08:51 +00008039static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
8040 SourceLocation Loc) {
8041 if (!PType->isVariablyModifiedType())
8042 return;
8043 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
8044 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
8045 return;
8046 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00008047 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
8048 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
8049 return;
8050 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00008051 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
8052 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
8053 return;
8054 }
8055
8056 const ArrayType *AT = S.Context.getAsArrayType(PType);
8057 if (!AT)
8058 return;
8059
8060 if (AT->getSizeModifier() != ArrayType::Star) {
8061 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
8062 return;
8063 }
8064
8065 S.Diag(Loc, diag::err_array_star_in_function_definition);
8066}
8067
Mike Stump0c2ec772010-01-21 03:59:47 +00008068/// CheckParmsForFunctionDef - Check that the parameters of the given
8069/// function are appropriate for the definition of a function. This
8070/// takes care of any checks that cannot be performed on the
8071/// declaration itself, e.g., that the types of each of the function
8072/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00008073bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
8074 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00008075 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008076 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00008077 for (; P != PEnd; ++P) {
8078 ParmVarDecl *Param = *P;
8079
Mike Stump0c2ec772010-01-21 03:59:47 +00008080 // C99 6.7.5.3p4: the parameters in a parameter type list in a
8081 // function declarator that is part of a function definition of
8082 // that function shall not have incomplete type.
8083 //
8084 // This is also C++ [dcl.fct]p6.
8085 if (!Param->isInvalidDecl() &&
8086 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008087 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008088 Param->setInvalidDecl();
8089 HasInvalidParm = true;
8090 }
8091
8092 // C99 6.9.1p5: If the declarator includes a parameter type list, the
8093 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00008094 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00008095 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00008096 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008097 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00008098 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00008099
8100 // C99 6.7.5.3p12:
8101 // If the function declarator is not part of a definition of that
8102 // function, parameters may have incomplete type and may use the [*]
8103 // notation in their sequences of declarator specifiers to specify
8104 // variable length array types.
8105 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00008106 // FIXME: This diagnostic should point the '[*]' if source-location
8107 // information is added for it.
8108 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008109
8110 // MSVC destroys objects passed by value in the callee. Therefore a
8111 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008112 // object's destructor. However, we don't perform any direct access check
8113 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00008114 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
8115 .getCXXABI()
8116 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00008117 if (!Param->isInvalidDecl()) {
8118 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
8119 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
8120 if (!ClassDecl->isInvalidDecl() &&
8121 !ClassDecl->hasIrrelevantDestructor() &&
8122 !ClassDecl->isDependentContext()) {
8123 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8124 MarkFunctionReferenced(Param->getLocation(), Destructor);
8125 DiagnoseUseOfDecl(Destructor, Param->getLocation());
8126 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008127 }
8128 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008129 }
Mike Stump0c2ec772010-01-21 03:59:47 +00008130 }
8131
8132 return HasInvalidParm;
8133}
John McCall2b5c1b22010-08-12 21:44:57 +00008134
8135/// CheckCastAlign - Implements -Wcast-align, which warns when a
8136/// pointer cast increases the alignment requirements.
8137void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
8138 // This is actually a lot of work to potentially be doing on every
8139 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008140 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00008141 return;
8142
8143 // Ignore dependent types.
8144 if (T->isDependentType() || Op->getType()->isDependentType())
8145 return;
8146
8147 // Require that the destination be a pointer type.
8148 const PointerType *DestPtr = T->getAs<PointerType>();
8149 if (!DestPtr) return;
8150
8151 // If the destination has alignment 1, we're done.
8152 QualType DestPointee = DestPtr->getPointeeType();
8153 if (DestPointee->isIncompleteType()) return;
8154 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
8155 if (DestAlign.isOne()) return;
8156
8157 // Require that the source be a pointer type.
8158 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
8159 if (!SrcPtr) return;
8160 QualType SrcPointee = SrcPtr->getPointeeType();
8161
8162 // Whitelist casts from cv void*. We already implicitly
8163 // whitelisted casts to cv void*, since they have alignment 1.
8164 // Also whitelist casts involving incomplete types, which implicitly
8165 // includes 'void'.
8166 if (SrcPointee->isIncompleteType()) return;
8167
8168 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
8169 if (SrcAlign >= DestAlign) return;
8170
8171 Diag(TRange.getBegin(), diag::warn_cast_align)
8172 << Op->getType() << T
8173 << static_cast<unsigned>(SrcAlign.getQuantity())
8174 << static_cast<unsigned>(DestAlign.getQuantity())
8175 << TRange << Op->getSourceRange();
8176}
8177
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008178static const Type* getElementType(const Expr *BaseExpr) {
8179 const Type* EltType = BaseExpr->getType().getTypePtr();
8180 if (EltType->isAnyPointerType())
8181 return EltType->getPointeeType().getTypePtr();
8182 else if (EltType->isArrayType())
8183 return EltType->getBaseElementTypeUnsafe();
8184 return EltType;
8185}
8186
Chandler Carruth28389f02011-08-05 09:10:50 +00008187/// \brief Check whether this array fits the idiom of a size-one tail padded
8188/// array member of a struct.
8189///
8190/// We avoid emitting out-of-bounds access warnings for such arrays as they are
8191/// commonly used to emulate flexible arrays in C89 code.
8192static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
8193 const NamedDecl *ND) {
8194 if (Size != 1 || !ND) return false;
8195
8196 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
8197 if (!FD) return false;
8198
8199 // Don't consider sizes resulting from macro expansions or template argument
8200 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00008201
8202 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008203 while (TInfo) {
8204 TypeLoc TL = TInfo->getTypeLoc();
8205 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00008206 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
8207 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008208 TInfo = TDL->getTypeSourceInfo();
8209 continue;
8210 }
David Blaikie6adc78e2013-02-18 22:06:02 +00008211 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
8212 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00008213 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
8214 return false;
8215 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008216 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00008217 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008218
8219 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00008220 if (!RD) return false;
8221 if (RD->isUnion()) return false;
8222 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8223 if (!CRD->isStandardLayout()) return false;
8224 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008225
Benjamin Kramer8c543672011-08-06 03:04:42 +00008226 // See if this is the last field decl in the record.
8227 const Decl *D = FD;
8228 while ((D = D->getNextDeclInContext()))
8229 if (isa<FieldDecl>(D))
8230 return false;
8231 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00008232}
8233
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008234void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008235 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00008236 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008237 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008238 if (IndexExpr->isValueDependent())
8239 return;
8240
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00008241 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008242 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008243 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008244 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008245 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00008246 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00008247
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008248 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008249 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00008250 return;
Richard Smith13f67182011-12-16 19:31:14 +00008251 if (IndexNegated)
8252 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00008253
Craig Topperc3ec1492014-05-26 06:22:03 +00008254 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00008255 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8256 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00008257 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00008258 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00008259
Ted Kremeneke4b316c2011-02-23 23:06:04 +00008260 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008261 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00008262 if (!size.isStrictlyPositive())
8263 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008264
8265 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00008266 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008267 // Make sure we're comparing apples to apples when comparing index to size
8268 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
8269 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00008270 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00008271 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008272 if (ptrarith_typesize != array_typesize) {
8273 // There's a cast to a different size type involved
8274 uint64_t ratio = array_typesize / ptrarith_typesize;
8275 // TODO: Be smarter about handling cases where array_typesize is not a
8276 // multiple of ptrarith_typesize
8277 if (ptrarith_typesize * ratio == array_typesize)
8278 size *= llvm::APInt(size.getBitWidth(), ratio);
8279 }
8280 }
8281
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008282 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008283 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008284 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008285 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008286
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008287 // For array subscripting the index must be less than size, but for pointer
8288 // arithmetic also allow the index (offset) to be equal to size since
8289 // computing the next address after the end of the array is legal and
8290 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008291 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00008292 return;
8293
8294 // Also don't warn for arrays of size 1 which are members of some
8295 // structure. These are often used to approximate flexible arrays in C89
8296 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008297 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00008298 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008299
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008300 // Suppress the warning if the subscript expression (as identified by the
8301 // ']' location) and the index expression are both from macro expansions
8302 // within a system header.
8303 if (ASE) {
8304 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
8305 ASE->getRBracketLoc());
8306 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
8307 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
8308 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00008309 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008310 return;
8311 }
8312 }
8313
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008314 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008315 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008316 DiagID = diag::warn_array_index_exceeds_bounds;
8317
8318 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8319 PDiag(DiagID) << index.toString(10, true)
8320 << size.toString(10, true)
8321 << (unsigned)size.getLimitedValue(~0U)
8322 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008323 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008324 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008325 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008326 DiagID = diag::warn_ptr_arith_precedes_bounds;
8327 if (index.isNegative()) index = -index;
8328 }
8329
8330 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8331 PDiag(DiagID) << index.toString(10, true)
8332 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00008333 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00008334
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00008335 if (!ND) {
8336 // Try harder to find a NamedDecl to point at in the note.
8337 while (const ArraySubscriptExpr *ASE =
8338 dyn_cast<ArraySubscriptExpr>(BaseExpr))
8339 BaseExpr = ASE->getBase()->IgnoreParenCasts();
8340 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8341 ND = dyn_cast<NamedDecl>(DRE->getDecl());
8342 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8343 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8344 }
8345
Chandler Carruth1af88f12011-02-17 21:10:52 +00008346 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008347 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
8348 PDiag(diag::note_array_index_out_of_bounds)
8349 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00008350}
8351
Ted Kremenekdf26df72011-03-01 18:41:00 +00008352void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008353 int AllowOnePastEnd = 0;
8354 while (expr) {
8355 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00008356 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008357 case Stmt::ArraySubscriptExprClass: {
8358 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008359 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008360 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00008361 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008362 }
8363 case Stmt::UnaryOperatorClass: {
8364 // Only unwrap the * and & unary operators
8365 const UnaryOperator *UO = cast<UnaryOperator>(expr);
8366 expr = UO->getSubExpr();
8367 switch (UO->getOpcode()) {
8368 case UO_AddrOf:
8369 AllowOnePastEnd++;
8370 break;
8371 case UO_Deref:
8372 AllowOnePastEnd--;
8373 break;
8374 default:
8375 return;
8376 }
8377 break;
8378 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008379 case Stmt::ConditionalOperatorClass: {
8380 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
8381 if (const Expr *lhs = cond->getLHS())
8382 CheckArrayAccess(lhs);
8383 if (const Expr *rhs = cond->getRHS())
8384 CheckArrayAccess(rhs);
8385 return;
8386 }
8387 default:
8388 return;
8389 }
Peter Collingbourne91147592011-04-15 00:35:48 +00008390 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008391}
John McCall31168b02011-06-15 23:02:42 +00008392
8393//===--- CHECK: Objective-C retain cycles ----------------------------------//
8394
8395namespace {
8396 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00008397 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00008398 VarDecl *Variable;
8399 SourceRange Range;
8400 SourceLocation Loc;
8401 bool Indirect;
8402
8403 void setLocsFrom(Expr *e) {
8404 Loc = e->getExprLoc();
8405 Range = e->getSourceRange();
8406 }
8407 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008408}
John McCall31168b02011-06-15 23:02:42 +00008409
8410/// Consider whether capturing the given variable can possibly lead to
8411/// a retain cycle.
8412static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00008413 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00008414 // lifetime. In MRR, it's captured strongly if the variable is
8415 // __block and has an appropriate type.
8416 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8417 return false;
8418
8419 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008420 if (ref)
8421 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00008422 return true;
8423}
8424
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008425static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00008426 while (true) {
8427 e = e->IgnoreParens();
8428 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
8429 switch (cast->getCastKind()) {
8430 case CK_BitCast:
8431 case CK_LValueBitCast:
8432 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00008433 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00008434 e = cast->getSubExpr();
8435 continue;
8436
John McCall31168b02011-06-15 23:02:42 +00008437 default:
8438 return false;
8439 }
8440 }
8441
8442 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
8443 ObjCIvarDecl *ivar = ref->getDecl();
8444 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8445 return false;
8446
8447 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008448 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00008449 return false;
8450
8451 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8452 owner.Indirect = true;
8453 return true;
8454 }
8455
8456 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8457 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8458 if (!var) return false;
8459 return considerVariable(var, ref, owner);
8460 }
8461
John McCall31168b02011-06-15 23:02:42 +00008462 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8463 if (member->isArrow()) return false;
8464
8465 // Don't count this as an indirect ownership.
8466 e = member->getBase();
8467 continue;
8468 }
8469
John McCallfe96e0b2011-11-06 09:01:30 +00008470 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8471 // Only pay attention to pseudo-objects on property references.
8472 ObjCPropertyRefExpr *pre
8473 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8474 ->IgnoreParens());
8475 if (!pre) return false;
8476 if (pre->isImplicitProperty()) return false;
8477 ObjCPropertyDecl *property = pre->getExplicitProperty();
8478 if (!property->isRetaining() &&
8479 !(property->getPropertyIvarDecl() &&
8480 property->getPropertyIvarDecl()->getType()
8481 .getObjCLifetime() == Qualifiers::OCL_Strong))
8482 return false;
8483
8484 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008485 if (pre->isSuperReceiver()) {
8486 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8487 if (!owner.Variable)
8488 return false;
8489 owner.Loc = pre->getLocation();
8490 owner.Range = pre->getSourceRange();
8491 return true;
8492 }
John McCallfe96e0b2011-11-06 09:01:30 +00008493 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8494 ->getSourceExpr());
8495 continue;
8496 }
8497
John McCall31168b02011-06-15 23:02:42 +00008498 // Array ivars?
8499
8500 return false;
8501 }
8502}
8503
8504namespace {
8505 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8506 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8507 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008508 Context(Context), Variable(variable), Capturer(nullptr),
8509 VarWillBeReased(false) {}
8510 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00008511 VarDecl *Variable;
8512 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008513 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00008514
8515 void VisitDeclRefExpr(DeclRefExpr *ref) {
8516 if (ref->getDecl() == Variable && !Capturer)
8517 Capturer = ref;
8518 }
8519
John McCall31168b02011-06-15 23:02:42 +00008520 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8521 if (Capturer) return;
8522 Visit(ref->getBase());
8523 if (Capturer && ref->isFreeIvar())
8524 Capturer = ref;
8525 }
8526
8527 void VisitBlockExpr(BlockExpr *block) {
8528 // Look inside nested blocks
8529 if (block->getBlockDecl()->capturesVariable(Variable))
8530 Visit(block->getBlockDecl()->getBody());
8531 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00008532
8533 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8534 if (Capturer) return;
8535 if (OVE->getSourceExpr())
8536 Visit(OVE->getSourceExpr());
8537 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008538 void VisitBinaryOperator(BinaryOperator *BinOp) {
8539 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8540 return;
8541 Expr *LHS = BinOp->getLHS();
8542 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8543 if (DRE->getDecl() != Variable)
8544 return;
8545 if (Expr *RHS = BinOp->getRHS()) {
8546 RHS = RHS->IgnoreParenCasts();
8547 llvm::APSInt Value;
8548 VarWillBeReased =
8549 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8550 }
8551 }
8552 }
John McCall31168b02011-06-15 23:02:42 +00008553 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008554}
John McCall31168b02011-06-15 23:02:42 +00008555
8556/// Check whether the given argument is a block which captures a
8557/// variable.
8558static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8559 assert(owner.Variable && owner.Loc.isValid());
8560
8561 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00008562
8563 // Look through [^{...} copy] and Block_copy(^{...}).
8564 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8565 Selector Cmd = ME->getSelector();
8566 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8567 e = ME->getInstanceReceiver();
8568 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00008569 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00008570 e = e->IgnoreParenCasts();
8571 }
8572 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8573 if (CE->getNumArgs() == 1) {
8574 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00008575 if (Fn) {
8576 const IdentifierInfo *FnI = Fn->getIdentifier();
8577 if (FnI && FnI->isStr("_Block_copy")) {
8578 e = CE->getArg(0)->IgnoreParenCasts();
8579 }
8580 }
Jordan Rose67e887c2012-09-17 17:54:30 +00008581 }
8582 }
8583
John McCall31168b02011-06-15 23:02:42 +00008584 BlockExpr *block = dyn_cast<BlockExpr>(e);
8585 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00008586 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00008587
8588 FindCaptureVisitor visitor(S.Context, owner.Variable);
8589 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008590 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00008591}
8592
8593static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8594 RetainCycleOwner &owner) {
8595 assert(capturer);
8596 assert(owner.Variable && owner.Loc.isValid());
8597
8598 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8599 << owner.Variable << capturer->getSourceRange();
8600 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8601 << owner.Indirect << owner.Range;
8602}
8603
8604/// Check for a keyword selector that starts with the word 'add' or
8605/// 'set'.
8606static bool isSetterLikeSelector(Selector sel) {
8607 if (sel.isUnarySelector()) return false;
8608
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008609 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00008610 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008611 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00008612 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008613 else if (str.startswith("add")) {
8614 // Specially whitelist 'addOperationWithBlock:'.
8615 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8616 return false;
8617 str = str.substr(3);
8618 }
John McCall31168b02011-06-15 23:02:42 +00008619 else
8620 return false;
8621
8622 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00008623 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00008624}
8625
Benjamin Kramer3a743452015-03-09 15:03:32 +00008626static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
8627 ObjCMessageExpr *Message) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008628 if (S.NSMutableArrayPointer.isNull()) {
8629 IdentifierInfo *NSMutableArrayId =
8630 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableArray);
8631 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableArrayId,
8632 Message->getLocStart(),
8633 Sema::LookupOrdinaryName);
8634 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8635 if (!InterfaceDecl) {
8636 return None;
8637 }
8638 QualType NSMutableArrayObject =
8639 S.Context.getObjCInterfaceType(InterfaceDecl);
8640 S.NSMutableArrayPointer =
8641 S.Context.getObjCObjectPointerType(NSMutableArrayObject);
8642 }
8643
8644 if (S.NSMutableArrayPointer != Message->getReceiverType()) {
8645 return None;
8646 }
8647
8648 Selector Sel = Message->getSelector();
8649
8650 Optional<NSAPI::NSArrayMethodKind> MKOpt =
8651 S.NSAPIObj->getNSArrayMethodKind(Sel);
8652 if (!MKOpt) {
8653 return None;
8654 }
8655
8656 NSAPI::NSArrayMethodKind MK = *MKOpt;
8657
8658 switch (MK) {
8659 case NSAPI::NSMutableArr_addObject:
8660 case NSAPI::NSMutableArr_insertObjectAtIndex:
8661 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
8662 return 0;
8663 case NSAPI::NSMutableArr_replaceObjectAtIndex:
8664 return 1;
8665
8666 default:
8667 return None;
8668 }
8669
8670 return None;
8671}
8672
8673static
8674Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
8675 ObjCMessageExpr *Message) {
8676
8677 if (S.NSMutableDictionaryPointer.isNull()) {
8678 IdentifierInfo *NSMutableDictionaryId =
8679 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableDictionary);
8680 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableDictionaryId,
8681 Message->getLocStart(),
8682 Sema::LookupOrdinaryName);
8683 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8684 if (!InterfaceDecl) {
8685 return None;
8686 }
8687 QualType NSMutableDictionaryObject =
8688 S.Context.getObjCInterfaceType(InterfaceDecl);
8689 S.NSMutableDictionaryPointer =
8690 S.Context.getObjCObjectPointerType(NSMutableDictionaryObject);
8691 }
8692
8693 if (S.NSMutableDictionaryPointer != Message->getReceiverType()) {
8694 return None;
8695 }
8696
8697 Selector Sel = Message->getSelector();
8698
8699 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
8700 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
8701 if (!MKOpt) {
8702 return None;
8703 }
8704
8705 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
8706
8707 switch (MK) {
8708 case NSAPI::NSMutableDict_setObjectForKey:
8709 case NSAPI::NSMutableDict_setValueForKey:
8710 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
8711 return 0;
8712
8713 default:
8714 return None;
8715 }
8716
8717 return None;
8718}
8719
8720static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
8721
8722 ObjCInterfaceDecl *InterfaceDecl;
8723 if (S.NSMutableSetPointer.isNull()) {
8724 IdentifierInfo *NSMutableSetId =
8725 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableSet);
8726 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableSetId,
8727 Message->getLocStart(),
8728 Sema::LookupOrdinaryName);
8729 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8730 if (InterfaceDecl) {
8731 QualType NSMutableSetObject =
8732 S.Context.getObjCInterfaceType(InterfaceDecl);
8733 S.NSMutableSetPointer =
8734 S.Context.getObjCObjectPointerType(NSMutableSetObject);
8735 }
8736 }
8737
8738 if (S.NSCountedSetPointer.isNull()) {
8739 IdentifierInfo *NSCountedSetId =
8740 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSCountedSet);
8741 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSCountedSetId,
8742 Message->getLocStart(),
8743 Sema::LookupOrdinaryName);
8744 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8745 if (InterfaceDecl) {
8746 QualType NSCountedSetObject =
8747 S.Context.getObjCInterfaceType(InterfaceDecl);
8748 S.NSCountedSetPointer =
8749 S.Context.getObjCObjectPointerType(NSCountedSetObject);
8750 }
8751 }
8752
8753 if (S.NSMutableOrderedSetPointer.isNull()) {
8754 IdentifierInfo *NSOrderedSetId =
8755 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableOrderedSet);
8756 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSOrderedSetId,
8757 Message->getLocStart(),
8758 Sema::LookupOrdinaryName);
8759 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8760 if (InterfaceDecl) {
8761 QualType NSOrderedSetObject =
8762 S.Context.getObjCInterfaceType(InterfaceDecl);
8763 S.NSMutableOrderedSetPointer =
8764 S.Context.getObjCObjectPointerType(NSOrderedSetObject);
8765 }
8766 }
8767
8768 QualType ReceiverType = Message->getReceiverType();
8769
8770 bool IsMutableSet = !S.NSMutableSetPointer.isNull() &&
8771 ReceiverType == S.NSMutableSetPointer;
8772 bool IsMutableOrderedSet = !S.NSMutableOrderedSetPointer.isNull() &&
8773 ReceiverType == S.NSMutableOrderedSetPointer;
8774 bool IsCountedSet = !S.NSCountedSetPointer.isNull() &&
8775 ReceiverType == S.NSCountedSetPointer;
8776
8777 if (!IsMutableSet && !IsMutableOrderedSet && !IsCountedSet) {
8778 return None;
8779 }
8780
8781 Selector Sel = Message->getSelector();
8782
8783 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
8784 if (!MKOpt) {
8785 return None;
8786 }
8787
8788 NSAPI::NSSetMethodKind MK = *MKOpt;
8789
8790 switch (MK) {
8791 case NSAPI::NSMutableSet_addObject:
8792 case NSAPI::NSOrderedSet_setObjectAtIndex:
8793 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
8794 case NSAPI::NSOrderedSet_insertObjectAtIndex:
8795 return 0;
8796 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
8797 return 1;
8798 }
8799
8800 return None;
8801}
8802
8803void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
8804 if (!Message->isInstanceMessage()) {
8805 return;
8806 }
8807
8808 Optional<int> ArgOpt;
8809
8810 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
8811 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
8812 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
8813 return;
8814 }
8815
8816 int ArgIndex = *ArgOpt;
8817
8818 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
8819 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
8820 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
8821 }
8822
8823 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
8824 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
8825 Arg = OE->getSourceExpr()->IgnoreImpCasts();
8826 }
8827
8828 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
8829 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
8830 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
8831 ValueDecl *Decl = ReceiverRE->getDecl();
8832 Diag(Message->getSourceRange().getBegin(),
8833 diag::warn_objc_circular_container)
8834 << Decl->getName();
8835 Diag(Decl->getLocation(),
8836 diag::note_objc_circular_container_declared_here)
8837 << Decl->getName();
8838 }
8839 }
8840 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
8841 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
8842 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
8843 ObjCIvarDecl *Decl = IvarRE->getDecl();
8844 Diag(Message->getSourceRange().getBegin(),
8845 diag::warn_objc_circular_container)
8846 << Decl->getName();
8847 Diag(Decl->getLocation(),
8848 diag::note_objc_circular_container_declared_here)
8849 << Decl->getName();
8850 }
8851 }
8852 }
8853
8854}
8855
John McCall31168b02011-06-15 23:02:42 +00008856/// Check a message send to see if it's likely to cause a retain cycle.
8857void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8858 // Only check instance methods whose selector looks like a setter.
8859 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8860 return;
8861
8862 // Try to find a variable that the receiver is strongly owned by.
8863 RetainCycleOwner owner;
8864 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008865 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00008866 return;
8867 } else {
8868 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8869 owner.Variable = getCurMethodDecl()->getSelfDecl();
8870 owner.Loc = msg->getSuperLoc();
8871 owner.Range = msg->getSuperLoc();
8872 }
8873
8874 // Check whether the receiver is captured by any of the arguments.
8875 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
8876 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
8877 return diagnoseRetainCycle(*this, capturer, owner);
8878}
8879
8880/// Check a property assign to see if it's likely to cause a retain cycle.
8881void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
8882 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008883 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00008884 return;
8885
8886 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
8887 diagnoseRetainCycle(*this, capturer, owner);
8888}
8889
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008890void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
8891 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00008892 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008893 return;
8894
8895 // Because we don't have an expression for the variable, we have to set the
8896 // location explicitly here.
8897 Owner.Loc = Var->getLocation();
8898 Owner.Range = Var->getSourceRange();
8899
8900 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8901 diagnoseRetainCycle(*this, Capturer, Owner);
8902}
8903
Ted Kremenek9304da92012-12-21 08:04:28 +00008904static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8905 Expr *RHS, bool isProperty) {
8906 // Check if RHS is an Objective-C object literal, which also can get
8907 // immediately zapped in a weak reference. Note that we explicitly
8908 // allow ObjCStringLiterals, since those are designed to never really die.
8909 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008910
Ted Kremenek64873352012-12-21 22:46:35 +00008911 // This enum needs to match with the 'select' in
8912 // warn_objc_arc_literal_assign (off-by-1).
8913 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8914 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8915 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008916
8917 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00008918 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00008919 << (isProperty ? 0 : 1)
8920 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008921
8922 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00008923}
8924
Ted Kremenekc1f014a2012-12-21 19:45:30 +00008925static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8926 Qualifiers::ObjCLifetime LT,
8927 Expr *RHS, bool isProperty) {
8928 // Strip off any implicit cast added to get to the one ARC-specific.
8929 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8930 if (cast->getCastKind() == CK_ARCConsumeObject) {
8931 S.Diag(Loc, diag::warn_arc_retained_assign)
8932 << (LT == Qualifiers::OCL_ExplicitNone)
8933 << (isProperty ? 0 : 1)
8934 << RHS->getSourceRange();
8935 return true;
8936 }
8937 RHS = cast->getSubExpr();
8938 }
8939
8940 if (LT == Qualifiers::OCL_Weak &&
8941 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8942 return true;
8943
8944 return false;
8945}
8946
Ted Kremenekb36234d2012-12-21 08:04:20 +00008947bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8948 QualType LHS, Expr *RHS) {
8949 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8950
8951 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8952 return false;
8953
8954 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8955 return true;
8956
8957 return false;
8958}
8959
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008960void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8961 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008962 QualType LHSType;
8963 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00008964 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008965 ObjCPropertyRefExpr *PRE
8966 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8967 if (PRE && !PRE->isImplicitProperty()) {
8968 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8969 if (PD)
8970 LHSType = PD->getType();
8971 }
8972
8973 if (LHSType.isNull())
8974 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00008975
8976 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8977
8978 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008979 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00008980 getCurFunction()->markSafeWeakUse(LHS);
8981 }
8982
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008983 if (checkUnsafeAssigns(Loc, LHSType, RHS))
8984 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00008985
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008986 // FIXME. Check for other life times.
8987 if (LT != Qualifiers::OCL_None)
8988 return;
8989
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008990 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008991 if (PRE->isImplicitProperty())
8992 return;
8993 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8994 if (!PD)
8995 return;
8996
Bill Wendling44426052012-12-20 19:22:21 +00008997 unsigned Attributes = PD->getPropertyAttributes();
8998 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008999 // when 'assign' attribute was not explicitly specified
9000 // by user, ignore it and rely on property type itself
9001 // for lifetime info.
9002 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
9003 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
9004 LHSType->isObjCRetainableType())
9005 return;
9006
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009007 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00009008 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009009 Diag(Loc, diag::warn_arc_retained_property_assign)
9010 << RHS->getSourceRange();
9011 return;
9012 }
9013 RHS = cast->getSubExpr();
9014 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009015 }
Bill Wendling44426052012-12-20 19:22:21 +00009016 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00009017 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
9018 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00009019 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009020 }
9021}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009022
9023//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
9024
9025namespace {
9026bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
9027 SourceLocation StmtLoc,
9028 const NullStmt *Body) {
9029 // Do not warn if the body is a macro that expands to nothing, e.g:
9030 //
9031 // #define CALL(x)
9032 // if (condition)
9033 // CALL(0);
9034 //
9035 if (Body->hasLeadingEmptyMacro())
9036 return false;
9037
9038 // Get line numbers of statement and body.
9039 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +00009040 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009041 &StmtLineInvalid);
9042 if (StmtLineInvalid)
9043 return false;
9044
9045 bool BodyLineInvalid;
9046 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
9047 &BodyLineInvalid);
9048 if (BodyLineInvalid)
9049 return false;
9050
9051 // Warn if null statement and body are on the same line.
9052 if (StmtLine != BodyLine)
9053 return false;
9054
9055 return true;
9056}
9057} // Unnamed namespace
9058
9059void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
9060 const Stmt *Body,
9061 unsigned DiagID) {
9062 // Since this is a syntactic check, don't emit diagnostic for template
9063 // instantiations, this just adds noise.
9064 if (CurrentInstantiationScope)
9065 return;
9066
9067 // The body should be a null statement.
9068 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9069 if (!NBody)
9070 return;
9071
9072 // Do the usual checks.
9073 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9074 return;
9075
9076 Diag(NBody->getSemiLoc(), DiagID);
9077 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9078}
9079
9080void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
9081 const Stmt *PossibleBody) {
9082 assert(!CurrentInstantiationScope); // Ensured by caller
9083
9084 SourceLocation StmtLoc;
9085 const Stmt *Body;
9086 unsigned DiagID;
9087 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
9088 StmtLoc = FS->getRParenLoc();
9089 Body = FS->getBody();
9090 DiagID = diag::warn_empty_for_body;
9091 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
9092 StmtLoc = WS->getCond()->getSourceRange().getEnd();
9093 Body = WS->getBody();
9094 DiagID = diag::warn_empty_while_body;
9095 } else
9096 return; // Neither `for' nor `while'.
9097
9098 // The body should be a null statement.
9099 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9100 if (!NBody)
9101 return;
9102
9103 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009104 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009105 return;
9106
9107 // Do the usual checks.
9108 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9109 return;
9110
9111 // `for(...);' and `while(...);' are popular idioms, so in order to keep
9112 // noise level low, emit diagnostics only if for/while is followed by a
9113 // CompoundStmt, e.g.:
9114 // for (int i = 0; i < n; i++);
9115 // {
9116 // a(i);
9117 // }
9118 // or if for/while is followed by a statement with more indentation
9119 // than for/while itself:
9120 // for (int i = 0; i < n; i++);
9121 // a(i);
9122 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
9123 if (!ProbableTypo) {
9124 bool BodyColInvalid;
9125 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
9126 PossibleBody->getLocStart(),
9127 &BodyColInvalid);
9128 if (BodyColInvalid)
9129 return;
9130
9131 bool StmtColInvalid;
9132 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
9133 S->getLocStart(),
9134 &StmtColInvalid);
9135 if (StmtColInvalid)
9136 return;
9137
9138 if (BodyCol > StmtCol)
9139 ProbableTypo = true;
9140 }
9141
9142 if (ProbableTypo) {
9143 Diag(NBody->getSemiLoc(), DiagID);
9144 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9145 }
9146}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009147
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009148//===--- CHECK: Warn on self move with std::move. -------------------------===//
9149
9150/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
9151void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
9152 SourceLocation OpLoc) {
9153
9154 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
9155 return;
9156
9157 if (!ActiveTemplateInstantiations.empty())
9158 return;
9159
9160 // Strip parens and casts away.
9161 LHSExpr = LHSExpr->IgnoreParenImpCasts();
9162 RHSExpr = RHSExpr->IgnoreParenImpCasts();
9163
9164 // Check for a call expression
9165 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
9166 if (!CE || CE->getNumArgs() != 1)
9167 return;
9168
9169 // Check for a call to std::move
9170 const FunctionDecl *FD = CE->getDirectCallee();
9171 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
9172 !FD->getIdentifier()->isStr("move"))
9173 return;
9174
9175 // Get argument from std::move
9176 RHSExpr = CE->getArg(0);
9177
9178 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9179 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9180
9181 // Two DeclRefExpr's, check that the decls are the same.
9182 if (LHSDeclRef && RHSDeclRef) {
9183 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9184 return;
9185 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9186 RHSDeclRef->getDecl()->getCanonicalDecl())
9187 return;
9188
9189 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9190 << LHSExpr->getSourceRange()
9191 << RHSExpr->getSourceRange();
9192 return;
9193 }
9194
9195 // Member variables require a different approach to check for self moves.
9196 // MemberExpr's are the same if every nested MemberExpr refers to the same
9197 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
9198 // the base Expr's are CXXThisExpr's.
9199 const Expr *LHSBase = LHSExpr;
9200 const Expr *RHSBase = RHSExpr;
9201 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
9202 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
9203 if (!LHSME || !RHSME)
9204 return;
9205
9206 while (LHSME && RHSME) {
9207 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
9208 RHSME->getMemberDecl()->getCanonicalDecl())
9209 return;
9210
9211 LHSBase = LHSME->getBase();
9212 RHSBase = RHSME->getBase();
9213 LHSME = dyn_cast<MemberExpr>(LHSBase);
9214 RHSME = dyn_cast<MemberExpr>(RHSBase);
9215 }
9216
9217 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
9218 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
9219 if (LHSDeclRef && RHSDeclRef) {
9220 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9221 return;
9222 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9223 RHSDeclRef->getDecl()->getCanonicalDecl())
9224 return;
9225
9226 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9227 << LHSExpr->getSourceRange()
9228 << RHSExpr->getSourceRange();
9229 return;
9230 }
9231
9232 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
9233 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9234 << LHSExpr->getSourceRange()
9235 << RHSExpr->getSourceRange();
9236}
9237
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009238//===--- Layout compatibility ----------------------------------------------//
9239
9240namespace {
9241
9242bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
9243
9244/// \brief Check if two enumeration types are layout-compatible.
9245bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
9246 // C++11 [dcl.enum] p8:
9247 // Two enumeration types are layout-compatible if they have the same
9248 // underlying type.
9249 return ED1->isComplete() && ED2->isComplete() &&
9250 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
9251}
9252
9253/// \brief Check if two fields are layout-compatible.
9254bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
9255 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
9256 return false;
9257
9258 if (Field1->isBitField() != Field2->isBitField())
9259 return false;
9260
9261 if (Field1->isBitField()) {
9262 // Make sure that the bit-fields are the same length.
9263 unsigned Bits1 = Field1->getBitWidthValue(C);
9264 unsigned Bits2 = Field2->getBitWidthValue(C);
9265
9266 if (Bits1 != Bits2)
9267 return false;
9268 }
9269
9270 return true;
9271}
9272
9273/// \brief Check if two standard-layout structs are layout-compatible.
9274/// (C++11 [class.mem] p17)
9275bool isLayoutCompatibleStruct(ASTContext &C,
9276 RecordDecl *RD1,
9277 RecordDecl *RD2) {
9278 // If both records are C++ classes, check that base classes match.
9279 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
9280 // If one of records is a CXXRecordDecl we are in C++ mode,
9281 // thus the other one is a CXXRecordDecl, too.
9282 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
9283 // Check number of base classes.
9284 if (D1CXX->getNumBases() != D2CXX->getNumBases())
9285 return false;
9286
9287 // Check the base classes.
9288 for (CXXRecordDecl::base_class_const_iterator
9289 Base1 = D1CXX->bases_begin(),
9290 BaseEnd1 = D1CXX->bases_end(),
9291 Base2 = D2CXX->bases_begin();
9292 Base1 != BaseEnd1;
9293 ++Base1, ++Base2) {
9294 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
9295 return false;
9296 }
9297 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
9298 // If only RD2 is a C++ class, it should have zero base classes.
9299 if (D2CXX->getNumBases() > 0)
9300 return false;
9301 }
9302
9303 // Check the fields.
9304 RecordDecl::field_iterator Field2 = RD2->field_begin(),
9305 Field2End = RD2->field_end(),
9306 Field1 = RD1->field_begin(),
9307 Field1End = RD1->field_end();
9308 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
9309 if (!isLayoutCompatible(C, *Field1, *Field2))
9310 return false;
9311 }
9312 if (Field1 != Field1End || Field2 != Field2End)
9313 return false;
9314
9315 return true;
9316}
9317
9318/// \brief Check if two standard-layout unions are layout-compatible.
9319/// (C++11 [class.mem] p18)
9320bool isLayoutCompatibleUnion(ASTContext &C,
9321 RecordDecl *RD1,
9322 RecordDecl *RD2) {
9323 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009324 for (auto *Field2 : RD2->fields())
9325 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009326
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009327 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009328 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
9329 I = UnmatchedFields.begin(),
9330 E = UnmatchedFields.end();
9331
9332 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009333 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009334 bool Result = UnmatchedFields.erase(*I);
9335 (void) Result;
9336 assert(Result);
9337 break;
9338 }
9339 }
9340 if (I == E)
9341 return false;
9342 }
9343
9344 return UnmatchedFields.empty();
9345}
9346
9347bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
9348 if (RD1->isUnion() != RD2->isUnion())
9349 return false;
9350
9351 if (RD1->isUnion())
9352 return isLayoutCompatibleUnion(C, RD1, RD2);
9353 else
9354 return isLayoutCompatibleStruct(C, RD1, RD2);
9355}
9356
9357/// \brief Check if two types are layout-compatible in C++11 sense.
9358bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
9359 if (T1.isNull() || T2.isNull())
9360 return false;
9361
9362 // C++11 [basic.types] p11:
9363 // If two types T1 and T2 are the same type, then T1 and T2 are
9364 // layout-compatible types.
9365 if (C.hasSameType(T1, T2))
9366 return true;
9367
9368 T1 = T1.getCanonicalType().getUnqualifiedType();
9369 T2 = T2.getCanonicalType().getUnqualifiedType();
9370
9371 const Type::TypeClass TC1 = T1->getTypeClass();
9372 const Type::TypeClass TC2 = T2->getTypeClass();
9373
9374 if (TC1 != TC2)
9375 return false;
9376
9377 if (TC1 == Type::Enum) {
9378 return isLayoutCompatible(C,
9379 cast<EnumType>(T1)->getDecl(),
9380 cast<EnumType>(T2)->getDecl());
9381 } else if (TC1 == Type::Record) {
9382 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
9383 return false;
9384
9385 return isLayoutCompatible(C,
9386 cast<RecordType>(T1)->getDecl(),
9387 cast<RecordType>(T2)->getDecl());
9388 }
9389
9390 return false;
9391}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009392}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009393
9394//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
9395
9396namespace {
9397/// \brief Given a type tag expression find the type tag itself.
9398///
9399/// \param TypeExpr Type tag expression, as it appears in user's code.
9400///
9401/// \param VD Declaration of an identifier that appears in a type tag.
9402///
9403/// \param MagicValue Type tag magic value.
9404bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
9405 const ValueDecl **VD, uint64_t *MagicValue) {
9406 while(true) {
9407 if (!TypeExpr)
9408 return false;
9409
9410 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
9411
9412 switch (TypeExpr->getStmtClass()) {
9413 case Stmt::UnaryOperatorClass: {
9414 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
9415 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
9416 TypeExpr = UO->getSubExpr();
9417 continue;
9418 }
9419 return false;
9420 }
9421
9422 case Stmt::DeclRefExprClass: {
9423 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
9424 *VD = DRE->getDecl();
9425 return true;
9426 }
9427
9428 case Stmt::IntegerLiteralClass: {
9429 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
9430 llvm::APInt MagicValueAPInt = IL->getValue();
9431 if (MagicValueAPInt.getActiveBits() <= 64) {
9432 *MagicValue = MagicValueAPInt.getZExtValue();
9433 return true;
9434 } else
9435 return false;
9436 }
9437
9438 case Stmt::BinaryConditionalOperatorClass:
9439 case Stmt::ConditionalOperatorClass: {
9440 const AbstractConditionalOperator *ACO =
9441 cast<AbstractConditionalOperator>(TypeExpr);
9442 bool Result;
9443 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
9444 if (Result)
9445 TypeExpr = ACO->getTrueExpr();
9446 else
9447 TypeExpr = ACO->getFalseExpr();
9448 continue;
9449 }
9450 return false;
9451 }
9452
9453 case Stmt::BinaryOperatorClass: {
9454 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
9455 if (BO->getOpcode() == BO_Comma) {
9456 TypeExpr = BO->getRHS();
9457 continue;
9458 }
9459 return false;
9460 }
9461
9462 default:
9463 return false;
9464 }
9465 }
9466}
9467
9468/// \brief Retrieve the C type corresponding to type tag TypeExpr.
9469///
9470/// \param TypeExpr Expression that specifies a type tag.
9471///
9472/// \param MagicValues Registered magic values.
9473///
9474/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
9475/// kind.
9476///
9477/// \param TypeInfo Information about the corresponding C type.
9478///
9479/// \returns true if the corresponding C type was found.
9480bool GetMatchingCType(
9481 const IdentifierInfo *ArgumentKind,
9482 const Expr *TypeExpr, const ASTContext &Ctx,
9483 const llvm::DenseMap<Sema::TypeTagMagicValue,
9484 Sema::TypeTagData> *MagicValues,
9485 bool &FoundWrongKind,
9486 Sema::TypeTagData &TypeInfo) {
9487 FoundWrongKind = false;
9488
9489 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00009490 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009491
9492 uint64_t MagicValue;
9493
9494 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
9495 return false;
9496
9497 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00009498 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009499 if (I->getArgumentKind() != ArgumentKind) {
9500 FoundWrongKind = true;
9501 return false;
9502 }
9503 TypeInfo.Type = I->getMatchingCType();
9504 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
9505 TypeInfo.MustBeNull = I->getMustBeNull();
9506 return true;
9507 }
9508 return false;
9509 }
9510
9511 if (!MagicValues)
9512 return false;
9513
9514 llvm::DenseMap<Sema::TypeTagMagicValue,
9515 Sema::TypeTagData>::const_iterator I =
9516 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
9517 if (I == MagicValues->end())
9518 return false;
9519
9520 TypeInfo = I->second;
9521 return true;
9522}
9523} // unnamed namespace
9524
9525void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9526 uint64_t MagicValue, QualType Type,
9527 bool LayoutCompatible,
9528 bool MustBeNull) {
9529 if (!TypeTagForDatatypeMagicValues)
9530 TypeTagForDatatypeMagicValues.reset(
9531 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
9532
9533 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
9534 (*TypeTagForDatatypeMagicValues)[Magic] =
9535 TypeTagData(Type, LayoutCompatible, MustBeNull);
9536}
9537
9538namespace {
9539bool IsSameCharType(QualType T1, QualType T2) {
9540 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
9541 if (!BT1)
9542 return false;
9543
9544 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
9545 if (!BT2)
9546 return false;
9547
9548 BuiltinType::Kind T1Kind = BT1->getKind();
9549 BuiltinType::Kind T2Kind = BT2->getKind();
9550
9551 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
9552 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
9553 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
9554 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
9555}
9556} // unnamed namespace
9557
9558void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9559 const Expr * const *ExprArgs) {
9560 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
9561 bool IsPointerAttr = Attr->getIsPointer();
9562
9563 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
9564 bool FoundWrongKind;
9565 TypeTagData TypeInfo;
9566 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
9567 TypeTagForDatatypeMagicValues.get(),
9568 FoundWrongKind, TypeInfo)) {
9569 if (FoundWrongKind)
9570 Diag(TypeTagExpr->getExprLoc(),
9571 diag::warn_type_tag_for_datatype_wrong_kind)
9572 << TypeTagExpr->getSourceRange();
9573 return;
9574 }
9575
9576 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
9577 if (IsPointerAttr) {
9578 // Skip implicit cast of pointer to `void *' (as a function argument).
9579 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00009580 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00009581 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009582 ArgumentExpr = ICE->getSubExpr();
9583 }
9584 QualType ArgumentType = ArgumentExpr->getType();
9585
9586 // Passing a `void*' pointer shouldn't trigger a warning.
9587 if (IsPointerAttr && ArgumentType->isVoidPointerType())
9588 return;
9589
9590 if (TypeInfo.MustBeNull) {
9591 // Type tag with matching void type requires a null pointer.
9592 if (!ArgumentExpr->isNullPointerConstant(Context,
9593 Expr::NPC_ValueDependentIsNotNull)) {
9594 Diag(ArgumentExpr->getExprLoc(),
9595 diag::warn_type_safety_null_pointer_required)
9596 << ArgumentKind->getName()
9597 << ArgumentExpr->getSourceRange()
9598 << TypeTagExpr->getSourceRange();
9599 }
9600 return;
9601 }
9602
9603 QualType RequiredType = TypeInfo.Type;
9604 if (IsPointerAttr)
9605 RequiredType = Context.getPointerType(RequiredType);
9606
9607 bool mismatch = false;
9608 if (!TypeInfo.LayoutCompatible) {
9609 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
9610
9611 // C++11 [basic.fundamental] p1:
9612 // Plain char, signed char, and unsigned char are three distinct types.
9613 //
9614 // But we treat plain `char' as equivalent to `signed char' or `unsigned
9615 // char' depending on the current char signedness mode.
9616 if (mismatch)
9617 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
9618 RequiredType->getPointeeType())) ||
9619 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
9620 mismatch = false;
9621 } else
9622 if (IsPointerAttr)
9623 mismatch = !isLayoutCompatible(Context,
9624 ArgumentType->getPointeeType(),
9625 RequiredType->getPointeeType());
9626 else
9627 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
9628
9629 if (mismatch)
9630 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00009631 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009632 << TypeInfo.LayoutCompatible << RequiredType
9633 << ArgumentExpr->getSourceRange()
9634 << TypeTagExpr->getSourceRange();
9635}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009636