blob: c28325a790e0e956aa3def8858cf1fce00da8e75 [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
187 QualType ReturnTy = CE->getCallReturnType();
188 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;
John McCallbebede42011-02-26 05:39:39 +0000322
323 case Builtin::BI__builtin_classify_type:
324 if (checkArgCount(*this, TheCall, 1)) return true;
325 TheCall->setType(Context.IntTy);
326 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000327 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000328 if (checkArgCount(*this, TheCall, 1)) return true;
329 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000330 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000331 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000332 case Builtin::BI__sync_fetch_and_add_1:
333 case Builtin::BI__sync_fetch_and_add_2:
334 case Builtin::BI__sync_fetch_and_add_4:
335 case Builtin::BI__sync_fetch_and_add_8:
336 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000337 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000338 case Builtin::BI__sync_fetch_and_sub_1:
339 case Builtin::BI__sync_fetch_and_sub_2:
340 case Builtin::BI__sync_fetch_and_sub_4:
341 case Builtin::BI__sync_fetch_and_sub_8:
342 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000343 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000344 case Builtin::BI__sync_fetch_and_or_1:
345 case Builtin::BI__sync_fetch_and_or_2:
346 case Builtin::BI__sync_fetch_and_or_4:
347 case Builtin::BI__sync_fetch_and_or_8:
348 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000349 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000350 case Builtin::BI__sync_fetch_and_and_1:
351 case Builtin::BI__sync_fetch_and_and_2:
352 case Builtin::BI__sync_fetch_and_and_4:
353 case Builtin::BI__sync_fetch_and_and_8:
354 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000355 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000356 case Builtin::BI__sync_fetch_and_xor_1:
357 case Builtin::BI__sync_fetch_and_xor_2:
358 case Builtin::BI__sync_fetch_and_xor_4:
359 case Builtin::BI__sync_fetch_and_xor_8:
360 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000361 case Builtin::BI__sync_fetch_and_nand:
362 case Builtin::BI__sync_fetch_and_nand_1:
363 case Builtin::BI__sync_fetch_and_nand_2:
364 case Builtin::BI__sync_fetch_and_nand_4:
365 case Builtin::BI__sync_fetch_and_nand_8:
366 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000367 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000368 case Builtin::BI__sync_add_and_fetch_1:
369 case Builtin::BI__sync_add_and_fetch_2:
370 case Builtin::BI__sync_add_and_fetch_4:
371 case Builtin::BI__sync_add_and_fetch_8:
372 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000373 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000374 case Builtin::BI__sync_sub_and_fetch_1:
375 case Builtin::BI__sync_sub_and_fetch_2:
376 case Builtin::BI__sync_sub_and_fetch_4:
377 case Builtin::BI__sync_sub_and_fetch_8:
378 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000379 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000380 case Builtin::BI__sync_and_and_fetch_1:
381 case Builtin::BI__sync_and_and_fetch_2:
382 case Builtin::BI__sync_and_and_fetch_4:
383 case Builtin::BI__sync_and_and_fetch_8:
384 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000385 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000386 case Builtin::BI__sync_or_and_fetch_1:
387 case Builtin::BI__sync_or_and_fetch_2:
388 case Builtin::BI__sync_or_and_fetch_4:
389 case Builtin::BI__sync_or_and_fetch_8:
390 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000391 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000392 case Builtin::BI__sync_xor_and_fetch_1:
393 case Builtin::BI__sync_xor_and_fetch_2:
394 case Builtin::BI__sync_xor_and_fetch_4:
395 case Builtin::BI__sync_xor_and_fetch_8:
396 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000397 case Builtin::BI__sync_nand_and_fetch:
398 case Builtin::BI__sync_nand_and_fetch_1:
399 case Builtin::BI__sync_nand_and_fetch_2:
400 case Builtin::BI__sync_nand_and_fetch_4:
401 case Builtin::BI__sync_nand_and_fetch_8:
402 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000403 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000404 case Builtin::BI__sync_val_compare_and_swap_1:
405 case Builtin::BI__sync_val_compare_and_swap_2:
406 case Builtin::BI__sync_val_compare_and_swap_4:
407 case Builtin::BI__sync_val_compare_and_swap_8:
408 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000409 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000410 case Builtin::BI__sync_bool_compare_and_swap_1:
411 case Builtin::BI__sync_bool_compare_and_swap_2:
412 case Builtin::BI__sync_bool_compare_and_swap_4:
413 case Builtin::BI__sync_bool_compare_and_swap_8:
414 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000415 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000416 case Builtin::BI__sync_lock_test_and_set_1:
417 case Builtin::BI__sync_lock_test_and_set_2:
418 case Builtin::BI__sync_lock_test_and_set_4:
419 case Builtin::BI__sync_lock_test_and_set_8:
420 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000421 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000422 case Builtin::BI__sync_lock_release_1:
423 case Builtin::BI__sync_lock_release_2:
424 case Builtin::BI__sync_lock_release_4:
425 case Builtin::BI__sync_lock_release_8:
426 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000427 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000428 case Builtin::BI__sync_swap_1:
429 case Builtin::BI__sync_swap_2:
430 case Builtin::BI__sync_swap_4:
431 case Builtin::BI__sync_swap_8:
432 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000433 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000434#define BUILTIN(ID, TYPE, ATTRS)
435#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
436 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000437 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000438#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000439 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000440 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000441 return ExprError();
442 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000443 case Builtin::BI__builtin_addressof:
444 if (SemaBuiltinAddressof(*this, TheCall))
445 return ExprError();
446 break;
Richard Smith760520b2014-06-03 23:27:44 +0000447 case Builtin::BI__builtin_operator_new:
448 case Builtin::BI__builtin_operator_delete:
449 if (!getLangOpts().CPlusPlus) {
450 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
451 << (BuiltinID == Builtin::BI__builtin_operator_new
452 ? "__builtin_operator_new"
453 : "__builtin_operator_delete")
454 << "C++";
455 return ExprError();
456 }
457 // CodeGen assumes it can find the global new and delete to call,
458 // so ensure that they are declared.
459 DeclareGlobalNewDelete();
460 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000461
462 // check secure string manipulation functions where overflows
463 // are detectable at compile time
464 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000465 case Builtin::BI__builtin___memmove_chk:
466 case Builtin::BI__builtin___memset_chk:
467 case Builtin::BI__builtin___strlcat_chk:
468 case Builtin::BI__builtin___strlcpy_chk:
469 case Builtin::BI__builtin___strncat_chk:
470 case Builtin::BI__builtin___strncpy_chk:
471 case Builtin::BI__builtin___stpncpy_chk:
472 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
473 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000474 case Builtin::BI__builtin___memccpy_chk:
475 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
476 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000477 case Builtin::BI__builtin___snprintf_chk:
478 case Builtin::BI__builtin___vsnprintf_chk:
479 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
480 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000481
482 case Builtin::BI__builtin_call_with_static_chain:
483 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
484 return ExprError();
485 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000486
487 case Builtin::BI__exception_code:
488 case Builtin::BI_exception_code: {
489 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
490 diag::err_seh___except_block))
491 return ExprError();
492 break;
493 }
494 case Builtin::BI__exception_info:
495 case Builtin::BI_exception_info: {
496 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
497 diag::err_seh___except_filter))
498 return ExprError();
499 break;
500 }
501
Nate Begeman4904e322010-06-08 02:47:44 +0000502 }
Richard Smith760520b2014-06-03 23:27:44 +0000503
Nate Begeman4904e322010-06-08 02:47:44 +0000504 // Since the target specific builtins for each arch overlap, only check those
505 // of the arch we are compiling for.
506 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000507 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000508 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000509 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000510 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000511 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000512 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
513 return ExprError();
514 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000515 case llvm::Triple::aarch64:
516 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000517 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000518 return ExprError();
519 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000520 case llvm::Triple::mips:
521 case llvm::Triple::mipsel:
522 case llvm::Triple::mips64:
523 case llvm::Triple::mips64el:
524 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
525 return ExprError();
526 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000527 case llvm::Triple::x86:
528 case llvm::Triple::x86_64:
529 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
530 return ExprError();
531 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000532 default:
533 break;
534 }
535 }
536
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000537 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000538}
539
Nate Begeman91e1fea2010-06-14 05:21:25 +0000540// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000541static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000542 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000543 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000544 switch (Type.getEltType()) {
545 case NeonTypeFlags::Int8:
546 case NeonTypeFlags::Poly8:
547 return shift ? 7 : (8 << IsQuad) - 1;
548 case NeonTypeFlags::Int16:
549 case NeonTypeFlags::Poly16:
550 return shift ? 15 : (4 << IsQuad) - 1;
551 case NeonTypeFlags::Int32:
552 return shift ? 31 : (2 << IsQuad) - 1;
553 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000554 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000555 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000556 case NeonTypeFlags::Poly128:
557 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000558 case NeonTypeFlags::Float16:
559 assert(!shift && "cannot shift float types!");
560 return (4 << IsQuad) - 1;
561 case NeonTypeFlags::Float32:
562 assert(!shift && "cannot shift float types!");
563 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000564 case NeonTypeFlags::Float64:
565 assert(!shift && "cannot shift float types!");
566 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000567 }
David Blaikie8a40f702012-01-17 06:56:22 +0000568 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000569}
570
Bob Wilsone4d77232011-11-08 05:04:11 +0000571/// getNeonEltType - Return the QualType corresponding to the elements of
572/// the vector type specified by the NeonTypeFlags. This is used to check
573/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000574static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000575 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000576 switch (Flags.getEltType()) {
577 case NeonTypeFlags::Int8:
578 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
579 case NeonTypeFlags::Int16:
580 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
581 case NeonTypeFlags::Int32:
582 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
583 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000584 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000585 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
586 else
587 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
588 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000589 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000590 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000591 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000592 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000593 case NeonTypeFlags::Poly64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000594 return Context.UnsignedLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000595 case NeonTypeFlags::Poly128:
596 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000597 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000598 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000599 case NeonTypeFlags::Float32:
600 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000601 case NeonTypeFlags::Float64:
602 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000603 }
David Blaikie8a40f702012-01-17 06:56:22 +0000604 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000605}
606
Tim Northover12670412014-02-19 10:37:05 +0000607bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000608 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000609 uint64_t mask = 0;
610 unsigned TV = 0;
611 int PtrArgNum = -1;
612 bool HasConstPtr = false;
613 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000614#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000615#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000616#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000617 }
618
619 // For NEON intrinsics which are overloaded on vector element type, validate
620 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000621 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000622 if (mask) {
623 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
624 return true;
625
626 TV = Result.getLimitedValue(64);
627 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
628 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000629 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000630 }
631
632 if (PtrArgNum >= 0) {
633 // Check that pointer arguments have the specified type.
634 Expr *Arg = TheCall->getArg(PtrArgNum);
635 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
636 Arg = ICE->getSubExpr();
637 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
638 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000639
Tim Northovera2ee4332014-03-29 15:09:45 +0000640 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000641 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000642 bool IsInt64Long =
643 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
644 QualType EltTy =
645 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000646 if (HasConstPtr)
647 EltTy = EltTy.withConst();
648 QualType LHSTy = Context.getPointerType(EltTy);
649 AssignConvertType ConvTy;
650 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
651 if (RHS.isInvalid())
652 return true;
653 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
654 RHS.get(), AA_Assigning))
655 return true;
656 }
657
658 // For NEON intrinsics which take an immediate value as part of the
659 // instruction, range check them here.
660 unsigned i = 0, l = 0, u = 0;
661 switch (BuiltinID) {
662 default:
663 return false;
Tim Northover12670412014-02-19 10:37:05 +0000664#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000665#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000666#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000667 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000668
Richard Sandiford28940af2014-04-16 08:47:51 +0000669 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000670}
671
Tim Northovera2ee4332014-03-29 15:09:45 +0000672bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
673 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000674 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000675 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000676 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000677 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000678 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000679 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
680 BuiltinID == AArch64::BI__builtin_arm_strex ||
681 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000682 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000683 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000684 BuiltinID == ARM::BI__builtin_arm_ldaex ||
685 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
686 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000687
688 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
689
690 // Ensure that we have the proper number of arguments.
691 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
692 return true;
693
694 // Inspect the pointer argument of the atomic builtin. This should always be
695 // a pointer type, whose element is an integral scalar or pointer type.
696 // Because it is a pointer type, we don't have to worry about any implicit
697 // casts here.
698 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
699 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
700 if (PointerArgRes.isInvalid())
701 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000702 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000703
704 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
705 if (!pointerType) {
706 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
707 << PointerArg->getType() << PointerArg->getSourceRange();
708 return true;
709 }
710
711 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
712 // task is to insert the appropriate casts into the AST. First work out just
713 // what the appropriate type is.
714 QualType ValType = pointerType->getPointeeType();
715 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
716 if (IsLdrex)
717 AddrType.addConst();
718
719 // Issue a warning if the cast is dodgy.
720 CastKind CastNeeded = CK_NoOp;
721 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
722 CastNeeded = CK_BitCast;
723 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
724 << PointerArg->getType()
725 << Context.getPointerType(AddrType)
726 << AA_Passing << PointerArg->getSourceRange();
727 }
728
729 // Finally, do the cast and replace the argument with the corrected version.
730 AddrType = Context.getPointerType(AddrType);
731 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
732 if (PointerArgRes.isInvalid())
733 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000734 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000735
736 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
737
738 // In general, we allow ints, floats and pointers to be loaded and stored.
739 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
740 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
741 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
742 << PointerArg->getType() << PointerArg->getSourceRange();
743 return true;
744 }
745
746 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000747 if (Context.getTypeSize(ValType) > MaxWidth) {
748 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000749 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
750 << PointerArg->getType() << PointerArg->getSourceRange();
751 return true;
752 }
753
754 switch (ValType.getObjCLifetime()) {
755 case Qualifiers::OCL_None:
756 case Qualifiers::OCL_ExplicitNone:
757 // okay
758 break;
759
760 case Qualifiers::OCL_Weak:
761 case Qualifiers::OCL_Strong:
762 case Qualifiers::OCL_Autoreleasing:
763 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
764 << ValType << PointerArg->getSourceRange();
765 return true;
766 }
767
768
769 if (IsLdrex) {
770 TheCall->setType(ValType);
771 return false;
772 }
773
774 // Initialize the argument to be stored.
775 ExprResult ValArg = TheCall->getArg(0);
776 InitializedEntity Entity = InitializedEntity::InitializeParameter(
777 Context, ValType, /*consume*/ false);
778 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
779 if (ValArg.isInvalid())
780 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000781 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000782
783 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
784 // but the custom checker bypasses all default analysis.
785 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000786 return false;
787}
788
Nate Begeman4904e322010-06-08 02:47:44 +0000789bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000790 llvm::APSInt Result;
791
Tim Northover6aacd492013-07-16 09:47:53 +0000792 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000793 BuiltinID == ARM::BI__builtin_arm_ldaex ||
794 BuiltinID == ARM::BI__builtin_arm_strex ||
795 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000796 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000797 }
798
Yi Kong26d104a2014-08-13 19:18:14 +0000799 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
800 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
801 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
802 }
803
Tim Northover12670412014-02-19 10:37:05 +0000804 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
805 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000806
Yi Kong4efadfb2014-07-03 16:01:25 +0000807 // For intrinsics which take an immediate value as part of the instruction,
808 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000809 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000810 switch (BuiltinID) {
811 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000812 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
813 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000814 case ARM::BI__builtin_arm_vcvtr_f:
815 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000816 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +0000817 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +0000818 case ARM::BI__builtin_arm_isb:
819 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000820 }
Nate Begemand773fe62010-06-13 04:47:52 +0000821
Nate Begemanf568b072010-08-03 21:32:34 +0000822 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000823 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000824}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000825
Tim Northover573cbee2014-05-24 12:52:07 +0000826bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000827 CallExpr *TheCall) {
828 llvm::APSInt Result;
829
Tim Northover573cbee2014-05-24 12:52:07 +0000830 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000831 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
832 BuiltinID == AArch64::BI__builtin_arm_strex ||
833 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000834 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
835 }
836
Yi Konga5548432014-08-13 19:18:20 +0000837 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
838 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
839 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
840 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
841 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
842 }
843
Tim Northovera2ee4332014-03-29 15:09:45 +0000844 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
845 return true;
846
Yi Kong19a29ac2014-07-17 10:52:06 +0000847 // For intrinsics which take an immediate value as part of the instruction,
848 // range check them here.
849 unsigned i = 0, l = 0, u = 0;
850 switch (BuiltinID) {
851 default: return false;
852 case AArch64::BI__builtin_arm_dmb:
853 case AArch64::BI__builtin_arm_dsb:
854 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
855 }
856
Yi Kong19a29ac2014-07-17 10:52:06 +0000857 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +0000858}
859
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000860bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
861 unsigned i = 0, l = 0, u = 0;
862 switch (BuiltinID) {
863 default: return false;
864 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
865 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000866 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
867 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
868 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
869 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
870 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000871 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000872
Richard Sandiford28940af2014-04-16 08:47:51 +0000873 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000874}
875
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000876bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topperdd84ec52014-12-27 07:00:08 +0000877 unsigned i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000878 switch (BuiltinID) {
Craig Topperdd84ec52014-12-27 07:00:08 +0000879 default: return false;
880 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
881 case X86::BI__builtin_ia32_cmpps:
882 case X86::BI__builtin_ia32_cmpss:
883 case X86::BI__builtin_ia32_cmppd:
Craig Toppera3306ca2015-01-19 01:18:22 +0000884 case X86::BI__builtin_ia32_cmpsd:
885 case X86::BI__builtin_ia32_cmpps512_mask:
886 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000887 }
Craig Topperdd84ec52014-12-27 07:00:08 +0000888 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000889}
890
Richard Smith55ce3522012-06-25 20:30:08 +0000891/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
892/// parameter with the FormatAttr's correct format_idx and firstDataArg.
893/// Returns true when the format fits the function and the FormatStringInfo has
894/// been populated.
895bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
896 FormatStringInfo *FSI) {
897 FSI->HasVAListArg = Format->getFirstArg() == 0;
898 FSI->FormatIdx = Format->getFormatIdx() - 1;
899 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000900
Richard Smith55ce3522012-06-25 20:30:08 +0000901 // The way the format attribute works in GCC, the implicit this argument
902 // of member functions is counted. However, it doesn't appear in our own
903 // lists, so decrement format_idx in that case.
904 if (IsCXXMember) {
905 if(FSI->FormatIdx == 0)
906 return false;
907 --FSI->FormatIdx;
908 if (FSI->FirstDataArg != 0)
909 --FSI->FirstDataArg;
910 }
911 return true;
912}
Mike Stump11289f42009-09-09 15:08:12 +0000913
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000914/// Checks if a the given expression evaluates to null.
915///
916/// \brief Returns true if the value evaluates to null.
917static bool CheckNonNullExpr(Sema &S,
918 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000919 // As a special case, transparent unions initialized with zero are
920 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000921 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000922 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
923 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000924 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000925 if (const InitListExpr *ILE =
926 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000927 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000928 }
929
930 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000931 return (!Expr->isValueDependent() &&
932 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
933 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000934}
935
936static void CheckNonNullArgument(Sema &S,
937 const Expr *ArgExpr,
938 SourceLocation CallSiteLoc) {
939 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000940 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
941}
942
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000943bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
944 FormatStringInfo FSI;
945 if ((GetFormatStringType(Format) == FST_NSString) &&
946 getFormatStringInfo(Format, false, &FSI)) {
947 Idx = FSI.FormatIdx;
948 return true;
949 }
950 return false;
951}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000952/// \brief Diagnose use of %s directive in an NSString which is being passed
953/// as formatting string to formatting method.
954static void
955DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
956 const NamedDecl *FDecl,
957 Expr **Args,
958 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000959 unsigned Idx = 0;
960 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000961 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
962 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000963 Idx = 2;
964 Format = true;
965 }
966 else
967 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
968 if (S.GetFormatNSStringIdx(I, Idx)) {
969 Format = true;
970 break;
971 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000972 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000973 if (!Format || NumArgs <= Idx)
974 return;
975 const Expr *FormatExpr = Args[Idx];
976 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
977 FormatExpr = CSCE->getSubExpr();
978 const StringLiteral *FormatString;
979 if (const ObjCStringLiteral *OSL =
980 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
981 FormatString = OSL->getString();
982 else
983 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
984 if (!FormatString)
985 return;
986 if (S.FormatStringHasSArg(FormatString)) {
987 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
988 << "%s" << 1 << 1;
989 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
990 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000991 }
992}
993
Ted Kremenek2bc73332014-01-17 06:24:43 +0000994static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +0000995 const NamedDecl *FDecl,
Richard Smith588bd9b2014-08-27 04:59:42 +0000996 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +0000997 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000998 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +0000999 llvm::SmallBitVector NonNullArgs;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001000 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001001 if (!NonNull->args_size()) {
1002 // Easy case: all pointer arguments are nonnull.
1003 for (const auto *Arg : Args)
Hal Finkelee90a222014-09-26 05:04:30 +00001004 if (S.isValidPointerAttrType(Arg->getType()))
Richard Smith588bd9b2014-08-27 04:59:42 +00001005 CheckNonNullArgument(S, Arg, CallSiteLoc);
1006 return;
1007 }
1008
1009 for (unsigned Val : NonNull->args()) {
1010 if (Val >= Args.size())
1011 continue;
1012 if (NonNullArgs.empty())
1013 NonNullArgs.resize(Args.size());
1014 NonNullArgs.set(Val);
1015 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001016 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001017
1018 // Check the attributes on the parameters.
1019 ArrayRef<ParmVarDecl*> parms;
1020 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1021 parms = FD->parameters();
1022 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
1023 parms = MD->parameters();
1024
Richard Smith588bd9b2014-08-27 04:59:42 +00001025 unsigned ArgIndex = 0;
Ted Kremenek9aedc152014-01-17 06:24:56 +00001026 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
Richard Smith588bd9b2014-08-27 04:59:42 +00001027 I != E; ++I, ++ArgIndex) {
Ted Kremenek9aedc152014-01-17 06:24:56 +00001028 const ParmVarDecl *PVD = *I;
Richard Smith588bd9b2014-08-27 04:59:42 +00001029 if (PVD->hasAttr<NonNullAttr>() ||
1030 (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
1031 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek9aedc152014-01-17 06:24:56 +00001032 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001033
1034 // In case this is a variadic call, check any remaining arguments.
1035 for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
1036 if (NonNullArgs[ArgIndex])
1037 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +00001038}
1039
Richard Smith55ce3522012-06-25 20:30:08 +00001040/// Handles the checks for format strings, non-POD arguments to vararg
1041/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00001042void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
1043 unsigned NumParams, bool IsMemberFunction,
1044 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001045 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001046 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001047 if (CurContext->isDependentContext())
1048 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001049
Ted Kremenekb8176da2010-09-09 04:33:05 +00001050 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001051 llvm::SmallBitVector CheckedVarArgs;
1052 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001053 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001054 // Only create vector if there are format attributes.
1055 CheckedVarArgs.resize(Args.size());
1056
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001057 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001058 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001059 }
Richard Smithd7293d72013-08-05 18:49:43 +00001060 }
Richard Smith55ce3522012-06-25 20:30:08 +00001061
1062 // Refuse POD arguments that weren't caught by the format string
1063 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001064 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001065 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001066 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001067 if (const Expr *Arg = Args[ArgIdx]) {
1068 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1069 checkVariadicArgument(Arg, CallType);
1070 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001071 }
Richard Smithd7293d72013-08-05 18:49:43 +00001072 }
Mike Stump11289f42009-09-09 15:08:12 +00001073
Richard Trieu41bc0992013-06-22 00:20:41 +00001074 if (FDecl) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001075 CheckNonNullArguments(*this, FDecl, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001076
Richard Trieu41bc0992013-06-22 00:20:41 +00001077 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001078 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1079 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001080 }
Richard Smith55ce3522012-06-25 20:30:08 +00001081}
1082
1083/// CheckConstructorCall - Check a constructor call for correctness and safety
1084/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001085void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1086 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001087 const FunctionProtoType *Proto,
1088 SourceLocation Loc) {
1089 VariadicCallType CallType =
1090 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +00001091 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +00001092 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
1093}
1094
1095/// CheckFunctionCall - Check a direct function call for various correctness
1096/// and safety properties not strictly enforced by the C type system.
1097bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1098 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001099 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1100 isa<CXXMethodDecl>(FDecl);
1101 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1102 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001103 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1104 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001105 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +00001106 Expr** Args = TheCall->getArgs();
1107 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001108 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001109 // If this is a call to a member operator, hide the first argument
1110 // from checkCall.
1111 // FIXME: Our choice of AST representation here is less than ideal.
1112 ++Args;
1113 --NumArgs;
1114 }
Craig Topper8c2a2a02014-08-30 16:55:39 +00001115 checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +00001116 IsMemberFunction, TheCall->getRParenLoc(),
1117 TheCall->getCallee()->getSourceRange(), CallType);
1118
1119 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1120 // None of the checks below are needed for functions that don't have
1121 // simple names (e.g., C++ conversion functions).
1122 if (!FnInfo)
1123 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001124
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001125 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001126 if (getLangOpts().ObjC1)
1127 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001128
Anna Zaks22122702012-01-17 00:37:07 +00001129 unsigned CMId = FDecl->getMemoryFunctionKind();
1130 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001131 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001132
Anna Zaks201d4892012-01-13 21:52:01 +00001133 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001134 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001135 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001136 else if (CMId == Builtin::BIstrncat)
1137 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001138 else
Anna Zaks22122702012-01-17 00:37:07 +00001139 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001140
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001141 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001142}
1143
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001144bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001145 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001146 VariadicCallType CallType =
1147 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001148
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001149 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +00001150 /*IsMemberFunction=*/false,
1151 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001152
1153 return false;
1154}
1155
Richard Trieu664c4c62013-06-20 21:03:13 +00001156bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1157 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001158 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
1159 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001160 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001161
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001162 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +00001163 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001164 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001165
Richard Trieu664c4c62013-06-20 21:03:13 +00001166 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001167 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001168 CallType = VariadicDoesNotApply;
1169 } else if (Ty->isBlockPointerType()) {
1170 CallType = VariadicBlock;
1171 } else { // Ty->isFunctionPointerType()
1172 CallType = VariadicFunction;
1173 }
Alp Toker9cacbab2014-01-20 20:26:09 +00001174 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001175
Craig Topper8c2a2a02014-08-30 16:55:39 +00001176 checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
1177 TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001178 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001179 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001180
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001181 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001182}
1183
Richard Trieu41bc0992013-06-22 00:20:41 +00001184/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1185/// such as function pointers returned from functions.
1186bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001187 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001188 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001189 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +00001190
Craig Topperc3ec1492014-05-26 06:22:03 +00001191 checkCall(/*FDecl=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001192 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001193 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001194 TheCall->getCallee()->getSourceRange(), CallType);
1195
1196 return false;
1197}
1198
Tim Northovere94a34c2014-03-11 10:49:14 +00001199static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1200 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1201 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1202 return false;
1203
1204 switch (Op) {
1205 case AtomicExpr::AO__c11_atomic_init:
1206 llvm_unreachable("There is no ordering argument for an init");
1207
1208 case AtomicExpr::AO__c11_atomic_load:
1209 case AtomicExpr::AO__atomic_load_n:
1210 case AtomicExpr::AO__atomic_load:
1211 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1212 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1213
1214 case AtomicExpr::AO__c11_atomic_store:
1215 case AtomicExpr::AO__atomic_store:
1216 case AtomicExpr::AO__atomic_store_n:
1217 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1218 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1219 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1220
1221 default:
1222 return true;
1223 }
1224}
1225
Richard Smithfeea8832012-04-12 05:08:17 +00001226ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1227 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001228 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1229 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001230
Richard Smithfeea8832012-04-12 05:08:17 +00001231 // All these operations take one of the following forms:
1232 enum {
1233 // C __c11_atomic_init(A *, C)
1234 Init,
1235 // C __c11_atomic_load(A *, int)
1236 Load,
1237 // void __atomic_load(A *, CP, int)
1238 Copy,
1239 // C __c11_atomic_add(A *, M, int)
1240 Arithmetic,
1241 // C __atomic_exchange_n(A *, CP, int)
1242 Xchg,
1243 // void __atomic_exchange(A *, C *, CP, int)
1244 GNUXchg,
1245 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1246 C11CmpXchg,
1247 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1248 GNUCmpXchg
1249 } Form = Init;
1250 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1251 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1252 // where:
1253 // C is an appropriate type,
1254 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1255 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1256 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1257 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001258
Richard Smithfeea8832012-04-12 05:08:17 +00001259 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1260 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
1261 && "need to update code for modified C11 atomics");
1262 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1263 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1264 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1265 Op == AtomicExpr::AO__atomic_store_n ||
1266 Op == AtomicExpr::AO__atomic_exchange_n ||
1267 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1268 bool IsAddSub = false;
1269
1270 switch (Op) {
1271 case AtomicExpr::AO__c11_atomic_init:
1272 Form = Init;
1273 break;
1274
1275 case AtomicExpr::AO__c11_atomic_load:
1276 case AtomicExpr::AO__atomic_load_n:
1277 Form = Load;
1278 break;
1279
1280 case AtomicExpr::AO__c11_atomic_store:
1281 case AtomicExpr::AO__atomic_load:
1282 case AtomicExpr::AO__atomic_store:
1283 case AtomicExpr::AO__atomic_store_n:
1284 Form = Copy;
1285 break;
1286
1287 case AtomicExpr::AO__c11_atomic_fetch_add:
1288 case AtomicExpr::AO__c11_atomic_fetch_sub:
1289 case AtomicExpr::AO__atomic_fetch_add:
1290 case AtomicExpr::AO__atomic_fetch_sub:
1291 case AtomicExpr::AO__atomic_add_fetch:
1292 case AtomicExpr::AO__atomic_sub_fetch:
1293 IsAddSub = true;
1294 // Fall through.
1295 case AtomicExpr::AO__c11_atomic_fetch_and:
1296 case AtomicExpr::AO__c11_atomic_fetch_or:
1297 case AtomicExpr::AO__c11_atomic_fetch_xor:
1298 case AtomicExpr::AO__atomic_fetch_and:
1299 case AtomicExpr::AO__atomic_fetch_or:
1300 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001301 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001302 case AtomicExpr::AO__atomic_and_fetch:
1303 case AtomicExpr::AO__atomic_or_fetch:
1304 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001305 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001306 Form = Arithmetic;
1307 break;
1308
1309 case AtomicExpr::AO__c11_atomic_exchange:
1310 case AtomicExpr::AO__atomic_exchange_n:
1311 Form = Xchg;
1312 break;
1313
1314 case AtomicExpr::AO__atomic_exchange:
1315 Form = GNUXchg;
1316 break;
1317
1318 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1319 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1320 Form = C11CmpXchg;
1321 break;
1322
1323 case AtomicExpr::AO__atomic_compare_exchange:
1324 case AtomicExpr::AO__atomic_compare_exchange_n:
1325 Form = GNUCmpXchg;
1326 break;
1327 }
1328
1329 // Check we have the right number of arguments.
1330 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001331 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001332 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001333 << TheCall->getCallee()->getSourceRange();
1334 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001335 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1336 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001337 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001338 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001339 << TheCall->getCallee()->getSourceRange();
1340 return ExprError();
1341 }
1342
Richard Smithfeea8832012-04-12 05:08:17 +00001343 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001344 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001345 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1346 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1347 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001348 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001349 << Ptr->getType() << Ptr->getSourceRange();
1350 return ExprError();
1351 }
1352
Richard Smithfeea8832012-04-12 05:08:17 +00001353 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1354 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1355 QualType ValType = AtomTy; // 'C'
1356 if (IsC11) {
1357 if (!AtomTy->isAtomicType()) {
1358 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1359 << Ptr->getType() << Ptr->getSourceRange();
1360 return ExprError();
1361 }
Richard Smithe00921a2012-09-15 06:09:58 +00001362 if (AtomTy.isConstQualified()) {
1363 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1364 << Ptr->getType() << Ptr->getSourceRange();
1365 return ExprError();
1366 }
Richard Smithfeea8832012-04-12 05:08:17 +00001367 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001368 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001369
Richard Smithfeea8832012-04-12 05:08:17 +00001370 // For an arithmetic operation, the implied arithmetic must be well-formed.
1371 if (Form == Arithmetic) {
1372 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1373 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1374 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1375 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1376 return ExprError();
1377 }
1378 if (!IsAddSub && !ValType->isIntegerType()) {
1379 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1380 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1381 return ExprError();
1382 }
1383 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1384 // For __atomic_*_n operations, the value type must be a scalar integral or
1385 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001386 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001387 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1388 return ExprError();
1389 }
1390
Eli Friedmanaa769812013-09-11 03:49:34 +00001391 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1392 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001393 // For GNU atomics, require a trivially-copyable type. This is not part of
1394 // the GNU atomics specification, but we enforce it for sanity.
1395 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001396 << Ptr->getType() << Ptr->getSourceRange();
1397 return ExprError();
1398 }
1399
Richard Smithfeea8832012-04-12 05:08:17 +00001400 // FIXME: For any builtin other than a load, the ValType must not be
1401 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001402
1403 switch (ValType.getObjCLifetime()) {
1404 case Qualifiers::OCL_None:
1405 case Qualifiers::OCL_ExplicitNone:
1406 // okay
1407 break;
1408
1409 case Qualifiers::OCL_Weak:
1410 case Qualifiers::OCL_Strong:
1411 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001412 // FIXME: Can this happen? By this point, ValType should be known
1413 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001414 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1415 << ValType << Ptr->getSourceRange();
1416 return ExprError();
1417 }
1418
1419 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001420 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001421 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001422 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001423 ResultType = Context.BoolTy;
1424
Richard Smithfeea8832012-04-12 05:08:17 +00001425 // The type of a parameter passed 'by value'. In the GNU atomics, such
1426 // arguments are actually passed as pointers.
1427 QualType ByValType = ValType; // 'CP'
1428 if (!IsC11 && !IsN)
1429 ByValType = Ptr->getType();
1430
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001431 // The first argument --- the pointer --- has a fixed type; we
1432 // deduce the types of the rest of the arguments accordingly. Walk
1433 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001434 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001435 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001436 if (i < NumVals[Form] + 1) {
1437 switch (i) {
1438 case 1:
1439 // The second argument is the non-atomic operand. For arithmetic, this
1440 // is always passed by value, and for a compare_exchange it is always
1441 // passed by address. For the rest, GNU uses by-address and C11 uses
1442 // by-value.
1443 assert(Form != Load);
1444 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1445 Ty = ValType;
1446 else if (Form == Copy || Form == Xchg)
1447 Ty = ByValType;
1448 else if (Form == Arithmetic)
1449 Ty = Context.getPointerDiffType();
1450 else
1451 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1452 break;
1453 case 2:
1454 // The third argument to compare_exchange / GNU exchange is a
1455 // (pointer to a) desired value.
1456 Ty = ByValType;
1457 break;
1458 case 3:
1459 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1460 Ty = Context.BoolTy;
1461 break;
1462 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001463 } else {
1464 // The order(s) are always converted to int.
1465 Ty = Context.IntTy;
1466 }
Richard Smithfeea8832012-04-12 05:08:17 +00001467
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001468 InitializedEntity Entity =
1469 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001470 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001471 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1472 if (Arg.isInvalid())
1473 return true;
1474 TheCall->setArg(i, Arg.get());
1475 }
1476
Richard Smithfeea8832012-04-12 05:08:17 +00001477 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001478 SmallVector<Expr*, 5> SubExprs;
1479 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001480 switch (Form) {
1481 case Init:
1482 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001483 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001484 break;
1485 case Load:
1486 SubExprs.push_back(TheCall->getArg(1)); // Order
1487 break;
1488 case Copy:
1489 case Arithmetic:
1490 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001491 SubExprs.push_back(TheCall->getArg(2)); // Order
1492 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001493 break;
1494 case GNUXchg:
1495 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1496 SubExprs.push_back(TheCall->getArg(3)); // Order
1497 SubExprs.push_back(TheCall->getArg(1)); // Val1
1498 SubExprs.push_back(TheCall->getArg(2)); // Val2
1499 break;
1500 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001501 SubExprs.push_back(TheCall->getArg(3)); // Order
1502 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001503 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001504 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001505 break;
1506 case GNUCmpXchg:
1507 SubExprs.push_back(TheCall->getArg(4)); // Order
1508 SubExprs.push_back(TheCall->getArg(1)); // Val1
1509 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1510 SubExprs.push_back(TheCall->getArg(2)); // Val2
1511 SubExprs.push_back(TheCall->getArg(3)); // Weak
1512 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001513 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001514
1515 if (SubExprs.size() >= 2 && Form != Init) {
1516 llvm::APSInt Result(32);
1517 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1518 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001519 Diag(SubExprs[1]->getLocStart(),
1520 diag::warn_atomic_op_has_invalid_memory_order)
1521 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001522 }
1523
Fariborz Jahanian615de762013-05-28 17:37:39 +00001524 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1525 SubExprs, ResultType, Op,
1526 TheCall->getRParenLoc());
1527
1528 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1529 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1530 Context.AtomicUsesUnsupportedLibcall(AE))
1531 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1532 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001533
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001534 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001535}
1536
1537
John McCall29ad95b2011-08-27 01:09:30 +00001538/// checkBuiltinArgument - Given a call to a builtin function, perform
1539/// normal type-checking on the given argument, updating the call in
1540/// place. This is useful when a builtin function requires custom
1541/// type-checking for some of its arguments but not necessarily all of
1542/// them.
1543///
1544/// Returns true on error.
1545static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1546 FunctionDecl *Fn = E->getDirectCallee();
1547 assert(Fn && "builtin call without direct callee!");
1548
1549 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1550 InitializedEntity Entity =
1551 InitializedEntity::InitializeParameter(S.Context, Param);
1552
1553 ExprResult Arg = E->getArg(0);
1554 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1555 if (Arg.isInvalid())
1556 return true;
1557
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001558 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001559 return false;
1560}
1561
Chris Lattnerdc046542009-05-08 06:58:22 +00001562/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1563/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1564/// type of its first argument. The main ActOnCallExpr routines have already
1565/// promoted the types of arguments because all of these calls are prototyped as
1566/// void(...).
1567///
1568/// This function goes through and does final semantic checking for these
1569/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001570ExprResult
1571Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001572 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001573 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1574 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1575
1576 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001577 if (TheCall->getNumArgs() < 1) {
1578 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1579 << 0 << 1 << TheCall->getNumArgs()
1580 << TheCall->getCallee()->getSourceRange();
1581 return ExprError();
1582 }
Mike Stump11289f42009-09-09 15:08:12 +00001583
Chris Lattnerdc046542009-05-08 06:58:22 +00001584 // Inspect the first argument of the atomic builtin. This should always be
1585 // a pointer type, whose element is an integral scalar or pointer type.
1586 // Because it is a pointer type, we don't have to worry about any implicit
1587 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001588 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001589 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001590 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1591 if (FirstArgResult.isInvalid())
1592 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001593 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001594 TheCall->setArg(0, FirstArg);
1595
John McCall31168b02011-06-15 23:02:42 +00001596 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1597 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001598 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1599 << FirstArg->getType() << FirstArg->getSourceRange();
1600 return ExprError();
1601 }
Mike Stump11289f42009-09-09 15:08:12 +00001602
John McCall31168b02011-06-15 23:02:42 +00001603 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001604 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001605 !ValType->isBlockPointerType()) {
1606 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1607 << FirstArg->getType() << FirstArg->getSourceRange();
1608 return ExprError();
1609 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001610
John McCall31168b02011-06-15 23:02:42 +00001611 switch (ValType.getObjCLifetime()) {
1612 case Qualifiers::OCL_None:
1613 case Qualifiers::OCL_ExplicitNone:
1614 // okay
1615 break;
1616
1617 case Qualifiers::OCL_Weak:
1618 case Qualifiers::OCL_Strong:
1619 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001620 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001621 << ValType << FirstArg->getSourceRange();
1622 return ExprError();
1623 }
1624
John McCallb50451a2011-10-05 07:41:44 +00001625 // Strip any qualifiers off ValType.
1626 ValType = ValType.getUnqualifiedType();
1627
Chandler Carruth3973af72010-07-18 20:54:12 +00001628 // The majority of builtins return a value, but a few have special return
1629 // types, so allow them to override appropriately below.
1630 QualType ResultType = ValType;
1631
Chris Lattnerdc046542009-05-08 06:58:22 +00001632 // We need to figure out which concrete builtin this maps onto. For example,
1633 // __sync_fetch_and_add with a 2 byte object turns into
1634 // __sync_fetch_and_add_2.
1635#define BUILTIN_ROW(x) \
1636 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1637 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001638
Chris Lattnerdc046542009-05-08 06:58:22 +00001639 static const unsigned BuiltinIndices[][5] = {
1640 BUILTIN_ROW(__sync_fetch_and_add),
1641 BUILTIN_ROW(__sync_fetch_and_sub),
1642 BUILTIN_ROW(__sync_fetch_and_or),
1643 BUILTIN_ROW(__sync_fetch_and_and),
1644 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00001645 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00001646
Chris Lattnerdc046542009-05-08 06:58:22 +00001647 BUILTIN_ROW(__sync_add_and_fetch),
1648 BUILTIN_ROW(__sync_sub_and_fetch),
1649 BUILTIN_ROW(__sync_and_and_fetch),
1650 BUILTIN_ROW(__sync_or_and_fetch),
1651 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00001652 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001653
Chris Lattnerdc046542009-05-08 06:58:22 +00001654 BUILTIN_ROW(__sync_val_compare_and_swap),
1655 BUILTIN_ROW(__sync_bool_compare_and_swap),
1656 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001657 BUILTIN_ROW(__sync_lock_release),
1658 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001659 };
Mike Stump11289f42009-09-09 15:08:12 +00001660#undef BUILTIN_ROW
1661
Chris Lattnerdc046542009-05-08 06:58:22 +00001662 // Determine the index of the size.
1663 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001664 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001665 case 1: SizeIndex = 0; break;
1666 case 2: SizeIndex = 1; break;
1667 case 4: SizeIndex = 2; break;
1668 case 8: SizeIndex = 3; break;
1669 case 16: SizeIndex = 4; break;
1670 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001671 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1672 << FirstArg->getType() << FirstArg->getSourceRange();
1673 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001674 }
Mike Stump11289f42009-09-09 15:08:12 +00001675
Chris Lattnerdc046542009-05-08 06:58:22 +00001676 // Each of these builtins has one pointer argument, followed by some number of
1677 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1678 // that we ignore. Find out which row of BuiltinIndices to read from as well
1679 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001680 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001681 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00001682 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00001683 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001684 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001685 case Builtin::BI__sync_fetch_and_add:
1686 case Builtin::BI__sync_fetch_and_add_1:
1687 case Builtin::BI__sync_fetch_and_add_2:
1688 case Builtin::BI__sync_fetch_and_add_4:
1689 case Builtin::BI__sync_fetch_and_add_8:
1690 case Builtin::BI__sync_fetch_and_add_16:
1691 BuiltinIndex = 0;
1692 break;
1693
1694 case Builtin::BI__sync_fetch_and_sub:
1695 case Builtin::BI__sync_fetch_and_sub_1:
1696 case Builtin::BI__sync_fetch_and_sub_2:
1697 case Builtin::BI__sync_fetch_and_sub_4:
1698 case Builtin::BI__sync_fetch_and_sub_8:
1699 case Builtin::BI__sync_fetch_and_sub_16:
1700 BuiltinIndex = 1;
1701 break;
1702
1703 case Builtin::BI__sync_fetch_and_or:
1704 case Builtin::BI__sync_fetch_and_or_1:
1705 case Builtin::BI__sync_fetch_and_or_2:
1706 case Builtin::BI__sync_fetch_and_or_4:
1707 case Builtin::BI__sync_fetch_and_or_8:
1708 case Builtin::BI__sync_fetch_and_or_16:
1709 BuiltinIndex = 2;
1710 break;
1711
1712 case Builtin::BI__sync_fetch_and_and:
1713 case Builtin::BI__sync_fetch_and_and_1:
1714 case Builtin::BI__sync_fetch_and_and_2:
1715 case Builtin::BI__sync_fetch_and_and_4:
1716 case Builtin::BI__sync_fetch_and_and_8:
1717 case Builtin::BI__sync_fetch_and_and_16:
1718 BuiltinIndex = 3;
1719 break;
Mike Stump11289f42009-09-09 15:08:12 +00001720
Douglas Gregor73722482011-11-28 16:30:08 +00001721 case Builtin::BI__sync_fetch_and_xor:
1722 case Builtin::BI__sync_fetch_and_xor_1:
1723 case Builtin::BI__sync_fetch_and_xor_2:
1724 case Builtin::BI__sync_fetch_and_xor_4:
1725 case Builtin::BI__sync_fetch_and_xor_8:
1726 case Builtin::BI__sync_fetch_and_xor_16:
1727 BuiltinIndex = 4;
1728 break;
1729
Hal Finkeld2208b52014-10-02 20:53:50 +00001730 case Builtin::BI__sync_fetch_and_nand:
1731 case Builtin::BI__sync_fetch_and_nand_1:
1732 case Builtin::BI__sync_fetch_and_nand_2:
1733 case Builtin::BI__sync_fetch_and_nand_4:
1734 case Builtin::BI__sync_fetch_and_nand_8:
1735 case Builtin::BI__sync_fetch_and_nand_16:
1736 BuiltinIndex = 5;
1737 WarnAboutSemanticsChange = true;
1738 break;
1739
Douglas Gregor73722482011-11-28 16:30:08 +00001740 case Builtin::BI__sync_add_and_fetch:
1741 case Builtin::BI__sync_add_and_fetch_1:
1742 case Builtin::BI__sync_add_and_fetch_2:
1743 case Builtin::BI__sync_add_and_fetch_4:
1744 case Builtin::BI__sync_add_and_fetch_8:
1745 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001746 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00001747 break;
1748
1749 case Builtin::BI__sync_sub_and_fetch:
1750 case Builtin::BI__sync_sub_and_fetch_1:
1751 case Builtin::BI__sync_sub_and_fetch_2:
1752 case Builtin::BI__sync_sub_and_fetch_4:
1753 case Builtin::BI__sync_sub_and_fetch_8:
1754 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001755 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00001756 break;
1757
1758 case Builtin::BI__sync_and_and_fetch:
1759 case Builtin::BI__sync_and_and_fetch_1:
1760 case Builtin::BI__sync_and_and_fetch_2:
1761 case Builtin::BI__sync_and_and_fetch_4:
1762 case Builtin::BI__sync_and_and_fetch_8:
1763 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001764 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00001765 break;
1766
1767 case Builtin::BI__sync_or_and_fetch:
1768 case Builtin::BI__sync_or_and_fetch_1:
1769 case Builtin::BI__sync_or_and_fetch_2:
1770 case Builtin::BI__sync_or_and_fetch_4:
1771 case Builtin::BI__sync_or_and_fetch_8:
1772 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001773 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00001774 break;
1775
1776 case Builtin::BI__sync_xor_and_fetch:
1777 case Builtin::BI__sync_xor_and_fetch_1:
1778 case Builtin::BI__sync_xor_and_fetch_2:
1779 case Builtin::BI__sync_xor_and_fetch_4:
1780 case Builtin::BI__sync_xor_and_fetch_8:
1781 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001782 BuiltinIndex = 10;
1783 break;
1784
1785 case Builtin::BI__sync_nand_and_fetch:
1786 case Builtin::BI__sync_nand_and_fetch_1:
1787 case Builtin::BI__sync_nand_and_fetch_2:
1788 case Builtin::BI__sync_nand_and_fetch_4:
1789 case Builtin::BI__sync_nand_and_fetch_8:
1790 case Builtin::BI__sync_nand_and_fetch_16:
1791 BuiltinIndex = 11;
1792 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00001793 break;
Mike Stump11289f42009-09-09 15:08:12 +00001794
Chris Lattnerdc046542009-05-08 06:58:22 +00001795 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001796 case Builtin::BI__sync_val_compare_and_swap_1:
1797 case Builtin::BI__sync_val_compare_and_swap_2:
1798 case Builtin::BI__sync_val_compare_and_swap_4:
1799 case Builtin::BI__sync_val_compare_and_swap_8:
1800 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001801 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00001802 NumFixed = 2;
1803 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001804
Chris Lattnerdc046542009-05-08 06:58:22 +00001805 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001806 case Builtin::BI__sync_bool_compare_and_swap_1:
1807 case Builtin::BI__sync_bool_compare_and_swap_2:
1808 case Builtin::BI__sync_bool_compare_and_swap_4:
1809 case Builtin::BI__sync_bool_compare_and_swap_8:
1810 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001811 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001812 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001813 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001814 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001815
1816 case Builtin::BI__sync_lock_test_and_set:
1817 case Builtin::BI__sync_lock_test_and_set_1:
1818 case Builtin::BI__sync_lock_test_and_set_2:
1819 case Builtin::BI__sync_lock_test_and_set_4:
1820 case Builtin::BI__sync_lock_test_and_set_8:
1821 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001822 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00001823 break;
1824
Chris Lattnerdc046542009-05-08 06:58:22 +00001825 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001826 case Builtin::BI__sync_lock_release_1:
1827 case Builtin::BI__sync_lock_release_2:
1828 case Builtin::BI__sync_lock_release_4:
1829 case Builtin::BI__sync_lock_release_8:
1830 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001831 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00001832 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001833 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001834 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001835
1836 case Builtin::BI__sync_swap:
1837 case Builtin::BI__sync_swap_1:
1838 case Builtin::BI__sync_swap_2:
1839 case Builtin::BI__sync_swap_4:
1840 case Builtin::BI__sync_swap_8:
1841 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001842 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00001843 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001844 }
Mike Stump11289f42009-09-09 15:08:12 +00001845
Chris Lattnerdc046542009-05-08 06:58:22 +00001846 // Now that we know how many fixed arguments we expect, first check that we
1847 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001848 if (TheCall->getNumArgs() < 1+NumFixed) {
1849 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1850 << 0 << 1+NumFixed << TheCall->getNumArgs()
1851 << TheCall->getCallee()->getSourceRange();
1852 return ExprError();
1853 }
Mike Stump11289f42009-09-09 15:08:12 +00001854
Hal Finkeld2208b52014-10-02 20:53:50 +00001855 if (WarnAboutSemanticsChange) {
1856 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
1857 << TheCall->getCallee()->getSourceRange();
1858 }
1859
Chris Lattner5b9241b2009-05-08 15:36:58 +00001860 // Get the decl for the concrete builtin from this, we can tell what the
1861 // concrete integer type we should convert to is.
1862 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1863 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001864 FunctionDecl *NewBuiltinDecl;
1865 if (NewBuiltinID == BuiltinID)
1866 NewBuiltinDecl = FDecl;
1867 else {
1868 // Perform builtin lookup to avoid redeclaring it.
1869 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1870 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1871 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1872 assert(Res.getFoundDecl());
1873 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00001874 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001875 return ExprError();
1876 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001877
John McCallcf142162010-08-07 06:22:56 +00001878 // The first argument --- the pointer --- has a fixed type; we
1879 // deduce the types of the rest of the arguments accordingly. Walk
1880 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001881 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001882 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001883
Chris Lattnerdc046542009-05-08 06:58:22 +00001884 // GCC does an implicit conversion to the pointer or integer ValType. This
1885 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001886 // Initialize the argument.
1887 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1888 ValType, /*consume*/ false);
1889 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001890 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001891 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001892
Chris Lattnerdc046542009-05-08 06:58:22 +00001893 // Okay, we have something that *can* be converted to the right type. Check
1894 // to see if there is a potentially weird extension going on here. This can
1895 // happen when you do an atomic operation on something like an char* and
1896 // pass in 42. The 42 gets converted to char. This is even more strange
1897 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001898 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001899 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00001900 }
Mike Stump11289f42009-09-09 15:08:12 +00001901
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001902 ASTContext& Context = this->getASTContext();
1903
1904 // Create a new DeclRefExpr to refer to the new decl.
1905 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1906 Context,
1907 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001908 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001909 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001910 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001911 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001912 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001913 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001914
Chris Lattnerdc046542009-05-08 06:58:22 +00001915 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001916 // FIXME: This loses syntactic information.
1917 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1918 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1919 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001920 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00001921
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001922 // Change the result type of the call to match the original value type. This
1923 // is arbitrary, but the codegen for these builtins ins design to handle it
1924 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001925 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001926
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001927 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001928}
1929
Chris Lattner6436fb62009-02-18 06:01:06 +00001930/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001931/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001932/// Note: It might also make sense to do the UTF-16 conversion here (would
1933/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001934bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001935 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001936 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1937
Douglas Gregorfb65e592011-07-27 05:40:30 +00001938 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001939 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1940 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001941 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001942 }
Mike Stump11289f42009-09-09 15:08:12 +00001943
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001944 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001945 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001946 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001947 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001948 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001949 UTF16 *ToPtr = &ToBuf[0];
1950
1951 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1952 &ToPtr, ToPtr + NumBytes,
1953 strictConversion);
1954 // Check for conversion failure.
1955 if (Result != conversionOK)
1956 Diag(Arg->getLocStart(),
1957 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1958 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001959 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001960}
1961
Chris Lattnere202e6a2007-12-20 00:05:45 +00001962/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1963/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001964bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1965 Expr *Fn = TheCall->getCallee();
1966 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001967 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001968 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001969 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1970 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001971 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001972 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001973 return true;
1974 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001975
1976 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001977 return Diag(TheCall->getLocEnd(),
1978 diag::err_typecheck_call_too_few_args_at_least)
1979 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001980 }
1981
John McCall29ad95b2011-08-27 01:09:30 +00001982 // Type-check the first argument normally.
1983 if (checkBuiltinArgument(*this, TheCall, 0))
1984 return true;
1985
Chris Lattnere202e6a2007-12-20 00:05:45 +00001986 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001987 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001988 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001989 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001990 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001991 else if (FunctionDecl *FD = getCurFunctionDecl())
1992 isVariadic = FD->isVariadic();
1993 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001994 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001995
Chris Lattnere202e6a2007-12-20 00:05:45 +00001996 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001997 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1998 return true;
1999 }
Mike Stump11289f42009-09-09 15:08:12 +00002000
Chris Lattner43be2e62007-12-19 23:59:04 +00002001 // Verify that the second argument to the builtin is the last argument of the
2002 // current function or method.
2003 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002004 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002005
Nico Weber9eea7642013-05-24 23:31:57 +00002006 // These are valid if SecondArgIsLastNamedArgument is false after the next
2007 // block.
2008 QualType Type;
2009 SourceLocation ParamLoc;
2010
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002011 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2012 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002013 // FIXME: This isn't correct for methods (results in bogus warning).
2014 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002015 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002016 if (CurBlock)
2017 LastArg = *(CurBlock->TheDecl->param_end()-1);
2018 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002019 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002020 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002021 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002022 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002023
2024 Type = PV->getType();
2025 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002026 }
2027 }
Mike Stump11289f42009-09-09 15:08:12 +00002028
Chris Lattner43be2e62007-12-19 23:59:04 +00002029 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002030 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002031 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002032 else if (Type->isReferenceType()) {
2033 Diag(Arg->getLocStart(),
2034 diag::warn_va_start_of_reference_type_is_undefined);
2035 Diag(ParamLoc, diag::note_parameter_type) << Type;
2036 }
2037
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002038 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002039 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002040}
Chris Lattner43be2e62007-12-19 23:59:04 +00002041
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002042bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2043 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2044 // const char *named_addr);
2045
2046 Expr *Func = Call->getCallee();
2047
2048 if (Call->getNumArgs() < 3)
2049 return Diag(Call->getLocEnd(),
2050 diag::err_typecheck_call_too_few_args_at_least)
2051 << 0 /*function call*/ << 3 << Call->getNumArgs();
2052
2053 // Determine whether the current function is variadic or not.
2054 bool IsVariadic;
2055 if (BlockScopeInfo *CurBlock = getCurBlock())
2056 IsVariadic = CurBlock->TheDecl->isVariadic();
2057 else if (FunctionDecl *FD = getCurFunctionDecl())
2058 IsVariadic = FD->isVariadic();
2059 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2060 IsVariadic = MD->isVariadic();
2061 else
2062 llvm_unreachable("unexpected statement type");
2063
2064 if (!IsVariadic) {
2065 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2066 return true;
2067 }
2068
2069 // Type-check the first argument normally.
2070 if (checkBuiltinArgument(*this, Call, 0))
2071 return true;
2072
2073 static const struct {
2074 unsigned ArgNo;
2075 QualType Type;
2076 } ArgumentTypes[] = {
2077 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2078 { 2, Context.getSizeType() },
2079 };
2080
2081 for (const auto &AT : ArgumentTypes) {
2082 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2083 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2084 continue;
2085 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2086 << Arg->getType() << AT.Type << 1 /* different class */
2087 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2088 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2089 }
2090
2091 return false;
2092}
2093
Chris Lattner2da14fb2007-12-20 00:26:33 +00002094/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2095/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002096bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2097 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002098 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002099 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002100 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002101 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002102 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002103 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002104 << SourceRange(TheCall->getArg(2)->getLocStart(),
2105 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002106
John Wiegley01296292011-04-08 18:41:53 +00002107 ExprResult OrigArg0 = TheCall->getArg(0);
2108 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002109
Chris Lattner2da14fb2007-12-20 00:26:33 +00002110 // Do standard promotions between the two arguments, returning their common
2111 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002112 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002113 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2114 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002115
2116 // Make sure any conversions are pushed back into the call; this is
2117 // type safe since unordered compare builtins are declared as "_Bool
2118 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002119 TheCall->setArg(0, OrigArg0.get());
2120 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002121
John Wiegley01296292011-04-08 18:41:53 +00002122 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002123 return false;
2124
Chris Lattner2da14fb2007-12-20 00:26:33 +00002125 // If the common type isn't a real floating type, then the arguments were
2126 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002127 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002128 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002129 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002130 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2131 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002132
Chris Lattner2da14fb2007-12-20 00:26:33 +00002133 return false;
2134}
2135
Benjamin Kramer634fc102010-02-15 22:42:31 +00002136/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2137/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002138/// to check everything. We expect the last argument to be a floating point
2139/// value.
2140bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2141 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002142 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002143 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002144 if (TheCall->getNumArgs() > NumArgs)
2145 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002146 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002147 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002148 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002149 (*(TheCall->arg_end()-1))->getLocEnd());
2150
Benjamin Kramer64aae502010-02-16 10:07:31 +00002151 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002152
Eli Friedman7e4faac2009-08-31 20:06:00 +00002153 if (OrigArg->isTypeDependent())
2154 return false;
2155
Chris Lattner68784ef2010-05-06 05:50:07 +00002156 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002157 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002158 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002159 diag::err_typecheck_call_invalid_unary_fp)
2160 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002161
Chris Lattner68784ef2010-05-06 05:50:07 +00002162 // If this is an implicit conversion from float -> double, remove it.
2163 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2164 Expr *CastArg = Cast->getSubExpr();
2165 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2166 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2167 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002168 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002169 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002170 }
2171 }
2172
Eli Friedman7e4faac2009-08-31 20:06:00 +00002173 return false;
2174}
2175
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002176/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2177// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002178ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002179 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002180 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002181 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002182 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2183 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002184
Nate Begemana0110022010-06-08 00:16:34 +00002185 // Determine which of the following types of shufflevector we're checking:
2186 // 1) unary, vector mask: (lhs, mask)
2187 // 2) binary, vector mask: (lhs, rhs, mask)
2188 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2189 QualType resType = TheCall->getArg(0)->getType();
2190 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002191
Douglas Gregorc25f7662009-05-19 22:10:17 +00002192 if (!TheCall->getArg(0)->isTypeDependent() &&
2193 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002194 QualType LHSType = TheCall->getArg(0)->getType();
2195 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002196
Craig Topperbaca3892013-07-29 06:47:04 +00002197 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2198 return ExprError(Diag(TheCall->getLocStart(),
2199 diag::err_shufflevector_non_vector)
2200 << SourceRange(TheCall->getArg(0)->getLocStart(),
2201 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002202
Nate Begemana0110022010-06-08 00:16:34 +00002203 numElements = LHSType->getAs<VectorType>()->getNumElements();
2204 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002205
Nate Begemana0110022010-06-08 00:16:34 +00002206 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2207 // with mask. If so, verify that RHS is an integer vector type with the
2208 // same number of elts as lhs.
2209 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002210 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002211 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002212 return ExprError(Diag(TheCall->getLocStart(),
2213 diag::err_shufflevector_incompatible_vector)
2214 << SourceRange(TheCall->getArg(1)->getLocStart(),
2215 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002216 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002217 return ExprError(Diag(TheCall->getLocStart(),
2218 diag::err_shufflevector_incompatible_vector)
2219 << SourceRange(TheCall->getArg(0)->getLocStart(),
2220 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002221 } else if (numElements != numResElements) {
2222 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002223 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002224 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002225 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002226 }
2227
2228 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002229 if (TheCall->getArg(i)->isTypeDependent() ||
2230 TheCall->getArg(i)->isValueDependent())
2231 continue;
2232
Nate Begemana0110022010-06-08 00:16:34 +00002233 llvm::APSInt Result(32);
2234 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2235 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002236 diag::err_shufflevector_nonconstant_argument)
2237 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002238
Craig Topper50ad5b72013-08-03 17:40:38 +00002239 // Allow -1 which will be translated to undef in the IR.
2240 if (Result.isSigned() && Result.isAllOnesValue())
2241 continue;
2242
Chris Lattner7ab824e2008-08-10 02:05:13 +00002243 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002244 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002245 diag::err_shufflevector_argument_too_large)
2246 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002247 }
2248
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002249 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002250
Chris Lattner7ab824e2008-08-10 02:05:13 +00002251 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002252 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002253 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002254 }
2255
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002256 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2257 TheCall->getCallee()->getLocStart(),
2258 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002259}
Chris Lattner43be2e62007-12-19 23:59:04 +00002260
Hal Finkelc4d7c822013-09-18 03:29:45 +00002261/// SemaConvertVectorExpr - Handle __builtin_convertvector
2262ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2263 SourceLocation BuiltinLoc,
2264 SourceLocation RParenLoc) {
2265 ExprValueKind VK = VK_RValue;
2266 ExprObjectKind OK = OK_Ordinary;
2267 QualType DstTy = TInfo->getType();
2268 QualType SrcTy = E->getType();
2269
2270 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2271 return ExprError(Diag(BuiltinLoc,
2272 diag::err_convertvector_non_vector)
2273 << E->getSourceRange());
2274 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2275 return ExprError(Diag(BuiltinLoc,
2276 diag::err_convertvector_non_vector_type));
2277
2278 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2279 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2280 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2281 if (SrcElts != DstElts)
2282 return ExprError(Diag(BuiltinLoc,
2283 diag::err_convertvector_incompatible_vector)
2284 << E->getSourceRange());
2285 }
2286
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002287 return new (Context)
2288 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002289}
2290
Daniel Dunbarb7257262008-07-21 22:59:13 +00002291/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2292// This is declared to take (const void*, ...) and can take two
2293// optional constant int args.
2294bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002295 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002296
Chris Lattner3b054132008-11-19 05:08:23 +00002297 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002298 return Diag(TheCall->getLocEnd(),
2299 diag::err_typecheck_call_too_many_args_at_most)
2300 << 0 /*function call*/ << 3 << NumArgs
2301 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002302
2303 // Argument 0 is checked for us and the remaining arguments must be
2304 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002305 for (unsigned i = 1; i != NumArgs; ++i)
2306 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002307 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002308
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002309 return false;
2310}
2311
Hal Finkelf0417332014-07-17 14:25:55 +00002312/// SemaBuiltinAssume - Handle __assume (MS Extension).
2313// __assume does not evaluate its arguments, and should warn if its argument
2314// has side effects.
2315bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2316 Expr *Arg = TheCall->getArg(0);
2317 if (Arg->isInstantiationDependent()) return false;
2318
2319 if (Arg->HasSideEffects(Context))
2320 return Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002321 << Arg->getSourceRange()
2322 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2323
2324 return false;
2325}
2326
2327/// Handle __builtin_assume_aligned. This is declared
2328/// as (const void*, size_t, ...) and can take one optional constant int arg.
2329bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2330 unsigned NumArgs = TheCall->getNumArgs();
2331
2332 if (NumArgs > 3)
2333 return Diag(TheCall->getLocEnd(),
2334 diag::err_typecheck_call_too_many_args_at_most)
2335 << 0 /*function call*/ << 3 << NumArgs
2336 << TheCall->getSourceRange();
2337
2338 // The alignment must be a constant integer.
2339 Expr *Arg = TheCall->getArg(1);
2340
2341 // We can't check the value of a dependent argument.
2342 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2343 llvm::APSInt Result;
2344 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2345 return true;
2346
2347 if (!Result.isPowerOf2())
2348 return Diag(TheCall->getLocStart(),
2349 diag::err_alignment_not_power_of_two)
2350 << Arg->getSourceRange();
2351 }
2352
2353 if (NumArgs > 2) {
2354 ExprResult Arg(TheCall->getArg(2));
2355 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2356 Context.getSizeType(), false);
2357 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2358 if (Arg.isInvalid()) return true;
2359 TheCall->setArg(2, Arg.get());
2360 }
Hal Finkelf0417332014-07-17 14:25:55 +00002361
2362 return false;
2363}
2364
Eric Christopher8d0c6212010-04-17 02:26:23 +00002365/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2366/// TheCall is a constant expression.
2367bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2368 llvm::APSInt &Result) {
2369 Expr *Arg = TheCall->getArg(ArgNum);
2370 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2371 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2372
2373 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2374
2375 if (!Arg->isIntegerConstantExpr(Result, Context))
2376 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002377 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002378
Chris Lattnerd545ad12009-09-23 06:06:36 +00002379 return false;
2380}
2381
Richard Sandiford28940af2014-04-16 08:47:51 +00002382/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2383/// TheCall is a constant expression in the range [Low, High].
2384bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2385 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002386 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002387
2388 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002389 Expr *Arg = TheCall->getArg(ArgNum);
2390 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002391 return false;
2392
Eric Christopher8d0c6212010-04-17 02:26:23 +00002393 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002394 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002395 return true;
2396
Richard Sandiford28940af2014-04-16 08:47:51 +00002397 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002398 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002399 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002400
2401 return false;
2402}
2403
Eli Friedmanc97d0142009-05-03 06:04:26 +00002404/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002405/// This checks that val is a constant 1.
2406bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2407 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002408 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002409
Eric Christopher8d0c6212010-04-17 02:26:23 +00002410 // TODO: This is less than ideal. Overload this to take a value.
2411 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2412 return true;
2413
2414 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002415 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2416 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2417
2418 return false;
2419}
2420
Richard Smithd7293d72013-08-05 18:49:43 +00002421namespace {
2422enum StringLiteralCheckType {
2423 SLCT_NotALiteral,
2424 SLCT_UncheckedLiteral,
2425 SLCT_CheckedLiteral
2426};
2427}
2428
Richard Smith55ce3522012-06-25 20:30:08 +00002429// Determine if an expression is a string literal or constant string.
2430// If this function returns false on the arguments to a function expecting a
2431// format string, we will usually need to emit a warning.
2432// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002433static StringLiteralCheckType
2434checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2435 bool HasVAListArg, unsigned format_idx,
2436 unsigned firstDataArg, Sema::FormatStringType Type,
2437 Sema::VariadicCallType CallType, bool InFunctionCall,
2438 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002439 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002440 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002441 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002442
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002443 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002444
Richard Smithd7293d72013-08-05 18:49:43 +00002445 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002446 // Technically -Wformat-nonliteral does not warn about this case.
2447 // The behavior of printf and friends in this case is implementation
2448 // dependent. Ideally if the format string cannot be null then
2449 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002450 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002451
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002452 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002453 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002454 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002455 // The expression is a literal if both sub-expressions were, and it was
2456 // completely checked only if both sub-expressions were checked.
2457 const AbstractConditionalOperator *C =
2458 cast<AbstractConditionalOperator>(E);
2459 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002460 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002461 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002462 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002463 if (Left == SLCT_NotALiteral)
2464 return SLCT_NotALiteral;
2465 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002466 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002467 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002468 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002469 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002470 }
2471
2472 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002473 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2474 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002475 }
2476
John McCallc07a0c72011-02-17 10:25:35 +00002477 case Stmt::OpaqueValueExprClass:
2478 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2479 E = src;
2480 goto tryAgain;
2481 }
Richard Smith55ce3522012-06-25 20:30:08 +00002482 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002483
Ted Kremeneka8890832011-02-24 23:03:04 +00002484 case Stmt::PredefinedExprClass:
2485 // While __func__, etc., are technically not string literals, they
2486 // cannot contain format specifiers and thus are not a security
2487 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002488 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002489
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002490 case Stmt::DeclRefExprClass: {
2491 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002492
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002493 // As an exception, do not flag errors for variables binding to
2494 // const string literals.
2495 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2496 bool isConstant = false;
2497 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002498
Richard Smithd7293d72013-08-05 18:49:43 +00002499 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2500 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002501 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002502 isConstant = T.isConstant(S.Context) &&
2503 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002504 } else if (T->isObjCObjectPointerType()) {
2505 // In ObjC, there is usually no "const ObjectPointer" type,
2506 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002507 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002508 }
Mike Stump11289f42009-09-09 15:08:12 +00002509
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002510 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002511 if (const Expr *Init = VD->getAnyInitializer()) {
2512 // Look through initializers like const char c[] = { "foo" }
2513 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2514 if (InitList->isStringLiteralInit())
2515 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2516 }
Richard Smithd7293d72013-08-05 18:49:43 +00002517 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002518 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002519 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002520 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002521 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002522 }
Mike Stump11289f42009-09-09 15:08:12 +00002523
Anders Carlssonb012ca92009-06-28 19:55:58 +00002524 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2525 // special check to see if the format string is a function parameter
2526 // of the function calling the printf function. If the function
2527 // has an attribute indicating it is a printf-like function, then we
2528 // should suppress warnings concerning non-literals being used in a call
2529 // to a vprintf function. For example:
2530 //
2531 // void
2532 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2533 // va_list ap;
2534 // va_start(ap, fmt);
2535 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2536 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002537 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002538 if (HasVAListArg) {
2539 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2540 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2541 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002542 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002543 // adjust for implicit parameter
2544 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2545 if (MD->isInstance())
2546 ++PVIndex;
2547 // We also check if the formats are compatible.
2548 // We can't pass a 'scanf' string to a 'printf' function.
2549 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002550 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002551 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002552 }
2553 }
2554 }
2555 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002556 }
Mike Stump11289f42009-09-09 15:08:12 +00002557
Richard Smith55ce3522012-06-25 20:30:08 +00002558 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002559 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002560
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002561 case Stmt::CallExprClass:
2562 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002563 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002564 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2565 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2566 unsigned ArgIndex = FA->getFormatIdx();
2567 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2568 if (MD->isInstance())
2569 --ArgIndex;
2570 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002571
Richard Smithd7293d72013-08-05 18:49:43 +00002572 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002573 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002574 Type, CallType, InFunctionCall,
2575 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002576 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2577 unsigned BuiltinID = FD->getBuiltinID();
2578 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2579 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2580 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002581 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002582 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002583 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002584 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002585 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002586 }
2587 }
Mike Stump11289f42009-09-09 15:08:12 +00002588
Richard Smith55ce3522012-06-25 20:30:08 +00002589 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002590 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002591 case Stmt::ObjCStringLiteralClass:
2592 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002593 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002594
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002595 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002596 StrE = ObjCFExpr->getString();
2597 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002598 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002599
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002600 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002601 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2602 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002603 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002604 }
Mike Stump11289f42009-09-09 15:08:12 +00002605
Richard Smith55ce3522012-06-25 20:30:08 +00002606 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002607 }
Mike Stump11289f42009-09-09 15:08:12 +00002608
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002609 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002610 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002611 }
2612}
2613
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002614Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002615 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002616 .Case("scanf", FST_Scanf)
2617 .Cases("printf", "printf0", FST_Printf)
2618 .Cases("NSString", "CFString", FST_NSString)
2619 .Case("strftime", FST_Strftime)
2620 .Case("strfmon", FST_Strfmon)
2621 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2622 .Default(FST_Unknown);
2623}
2624
Jordan Rose3e0ec582012-07-19 18:10:23 +00002625/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002626/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002627/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002628bool Sema::CheckFormatArguments(const FormatAttr *Format,
2629 ArrayRef<const Expr *> Args,
2630 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002631 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002632 SourceLocation Loc, SourceRange Range,
2633 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002634 FormatStringInfo FSI;
2635 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002636 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002637 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002638 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002639 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002640}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002641
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002642bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002643 bool HasVAListArg, unsigned format_idx,
2644 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002645 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002646 SourceLocation Loc, SourceRange Range,
2647 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002648 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002649 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002650 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002651 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002652 }
Mike Stump11289f42009-09-09 15:08:12 +00002653
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002654 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002655
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002656 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002657 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002658 // Dynamically generated format strings are difficult to
2659 // automatically vet at compile time. Requiring that format strings
2660 // are string literals: (1) permits the checking of format strings by
2661 // the compiler and thereby (2) can practically remove the source of
2662 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002663
Mike Stump11289f42009-09-09 15:08:12 +00002664 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002665 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002666 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002667 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002668 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002669 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2670 format_idx, firstDataArg, Type, CallType,
2671 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002672 if (CT != SLCT_NotALiteral)
2673 // Literal format string found, check done!
2674 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002675
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002676 // Strftime is particular as it always uses a single 'time' argument,
2677 // so it is safe to pass a non-literal string.
2678 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002679 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002680
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002681 // Do not emit diag when the string param is a macro expansion and the
2682 // format is either NSString or CFString. This is a hack to prevent
2683 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2684 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002685 if (Type == FST_NSString &&
2686 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002687 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002688
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002689 // If there are no arguments specified, warn with -Wformat-security, otherwise
2690 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002691 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002692 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002693 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002694 << OrigFormatExpr->getSourceRange();
2695 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002696 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002697 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002698 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002699 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002700}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002701
Ted Kremenekab278de2010-01-28 23:39:18 +00002702namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002703class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2704protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002705 Sema &S;
2706 const StringLiteral *FExpr;
2707 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002708 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002709 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002710 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002711 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002712 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002713 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002714 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002715 bool usesPositionalArgs;
2716 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002717 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002718 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002719 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002720public:
Ted Kremenek02087932010-07-16 02:11:22 +00002721 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002722 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002723 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002724 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002725 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002726 Sema::VariadicCallType callType,
2727 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002728 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002729 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2730 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002731 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002732 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002733 inFunctionCall(inFunctionCall), CallType(callType),
2734 CheckedVarArgs(CheckedVarArgs) {
2735 CoveredArgs.resize(numDataArgs);
2736 CoveredArgs.reset();
2737 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002738
Ted Kremenek019d2242010-01-29 01:50:07 +00002739 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002740
Ted Kremenek02087932010-07-16 02:11:22 +00002741 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002742 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002743
Jordan Rose92303592012-09-08 04:00:03 +00002744 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002745 const analyze_format_string::FormatSpecifier &FS,
2746 const analyze_format_string::ConversionSpecifier &CS,
2747 const char *startSpecifier, unsigned specifierLen,
2748 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002749
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002750 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002751 const analyze_format_string::FormatSpecifier &FS,
2752 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002753
2754 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002755 const analyze_format_string::ConversionSpecifier &CS,
2756 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002757
Craig Toppere14c0f82014-03-12 04:55:44 +00002758 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002759
Craig Toppere14c0f82014-03-12 04:55:44 +00002760 void HandleInvalidPosition(const char *startSpecifier,
2761 unsigned specifierLen,
2762 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002763
Craig Toppere14c0f82014-03-12 04:55:44 +00002764 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002765
Craig Toppere14c0f82014-03-12 04:55:44 +00002766 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002767
Richard Trieu03cf7b72011-10-28 00:41:25 +00002768 template <typename Range>
2769 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2770 const Expr *ArgumentExpr,
2771 PartialDiagnostic PDiag,
2772 SourceLocation StringLoc,
2773 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002774 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002775
Ted Kremenek02087932010-07-16 02:11:22 +00002776protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002777 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2778 const char *startSpec,
2779 unsigned specifierLen,
2780 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002781
2782 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2783 const char *startSpec,
2784 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002785
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002786 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002787 CharSourceRange getSpecifierRange(const char *startSpecifier,
2788 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002789 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002790
Ted Kremenek5739de72010-01-29 01:06:55 +00002791 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002792
2793 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2794 const analyze_format_string::ConversionSpecifier &CS,
2795 const char *startSpecifier, unsigned specifierLen,
2796 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002797
2798 template <typename Range>
2799 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2800 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002801 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002802};
2803}
2804
Ted Kremenek02087932010-07-16 02:11:22 +00002805SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002806 return OrigFormatExpr->getSourceRange();
2807}
2808
Ted Kremenek02087932010-07-16 02:11:22 +00002809CharSourceRange CheckFormatHandler::
2810getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002811 SourceLocation Start = getLocationOfByte(startSpecifier);
2812 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2813
2814 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002815 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002816
2817 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002818}
2819
Ted Kremenek02087932010-07-16 02:11:22 +00002820SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002821 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002822}
2823
Ted Kremenek02087932010-07-16 02:11:22 +00002824void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2825 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002826 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2827 getLocationOfByte(startSpecifier),
2828 /*IsStringLocation*/true,
2829 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002830}
2831
Jordan Rose92303592012-09-08 04:00:03 +00002832void CheckFormatHandler::HandleInvalidLengthModifier(
2833 const analyze_format_string::FormatSpecifier &FS,
2834 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002835 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002836 using namespace analyze_format_string;
2837
2838 const LengthModifier &LM = FS.getLengthModifier();
2839 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2840
2841 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002842 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002843 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002844 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002845 getLocationOfByte(LM.getStart()),
2846 /*IsStringLocation*/true,
2847 getSpecifierRange(startSpecifier, specifierLen));
2848
2849 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2850 << FixedLM->toString()
2851 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2852
2853 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002854 FixItHint Hint;
2855 if (DiagID == diag::warn_format_nonsensical_length)
2856 Hint = FixItHint::CreateRemoval(LMRange);
2857
2858 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002859 getLocationOfByte(LM.getStart()),
2860 /*IsStringLocation*/true,
2861 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002862 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002863 }
2864}
2865
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002866void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002867 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002868 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002869 using namespace analyze_format_string;
2870
2871 const LengthModifier &LM = FS.getLengthModifier();
2872 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2873
2874 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002875 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002876 if (FixedLM) {
2877 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2878 << LM.toString() << 0,
2879 getLocationOfByte(LM.getStart()),
2880 /*IsStringLocation*/true,
2881 getSpecifierRange(startSpecifier, specifierLen));
2882
2883 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2884 << FixedLM->toString()
2885 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2886
2887 } else {
2888 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2889 << LM.toString() << 0,
2890 getLocationOfByte(LM.getStart()),
2891 /*IsStringLocation*/true,
2892 getSpecifierRange(startSpecifier, specifierLen));
2893 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002894}
2895
2896void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2897 const analyze_format_string::ConversionSpecifier &CS,
2898 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002899 using namespace analyze_format_string;
2900
2901 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002902 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002903 if (FixedCS) {
2904 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2905 << CS.toString() << /*conversion specifier*/1,
2906 getLocationOfByte(CS.getStart()),
2907 /*IsStringLocation*/true,
2908 getSpecifierRange(startSpecifier, specifierLen));
2909
2910 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2911 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2912 << FixedCS->toString()
2913 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2914 } else {
2915 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2916 << CS.toString() << /*conversion specifier*/1,
2917 getLocationOfByte(CS.getStart()),
2918 /*IsStringLocation*/true,
2919 getSpecifierRange(startSpecifier, specifierLen));
2920 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002921}
2922
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002923void CheckFormatHandler::HandlePosition(const char *startPos,
2924 unsigned posLen) {
2925 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2926 getLocationOfByte(startPos),
2927 /*IsStringLocation*/true,
2928 getSpecifierRange(startPos, posLen));
2929}
2930
Ted Kremenekd1668192010-02-27 01:41:03 +00002931void
Ted Kremenek02087932010-07-16 02:11:22 +00002932CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2933 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002934 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2935 << (unsigned) p,
2936 getLocationOfByte(startPos), /*IsStringLocation*/true,
2937 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002938}
2939
Ted Kremenek02087932010-07-16 02:11:22 +00002940void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002941 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002942 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2943 getLocationOfByte(startPos),
2944 /*IsStringLocation*/true,
2945 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002946}
2947
Ted Kremenek02087932010-07-16 02:11:22 +00002948void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002949 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002950 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002951 EmitFormatDiagnostic(
2952 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2953 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2954 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002955 }
Ted Kremenek02087932010-07-16 02:11:22 +00002956}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002957
Jordan Rose58bbe422012-07-19 18:10:08 +00002958// Note that this may return NULL if there was an error parsing or building
2959// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002960const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002961 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002962}
2963
2964void CheckFormatHandler::DoneProcessing() {
2965 // Does the number of data arguments exceed the number of
2966 // format conversions in the format string?
2967 if (!HasVAListArg) {
2968 // Find any arguments that weren't covered.
2969 CoveredArgs.flip();
2970 signed notCoveredArg = CoveredArgs.find_first();
2971 if (notCoveredArg >= 0) {
2972 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002973 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2974 SourceLocation Loc = E->getLocStart();
2975 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2976 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2977 Loc, /*IsStringLocation*/false,
2978 getFormatStringRange());
2979 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002980 }
Ted Kremenek02087932010-07-16 02:11:22 +00002981 }
2982 }
2983}
2984
Ted Kremenekce815422010-07-19 21:25:57 +00002985bool
2986CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2987 SourceLocation Loc,
2988 const char *startSpec,
2989 unsigned specifierLen,
2990 const char *csStart,
2991 unsigned csLen) {
2992
2993 bool keepGoing = true;
2994 if (argIndex < NumDataArgs) {
2995 // Consider the argument coverered, even though the specifier doesn't
2996 // make sense.
2997 CoveredArgs.set(argIndex);
2998 }
2999 else {
3000 // If argIndex exceeds the number of data arguments we
3001 // don't issue a warning because that is just a cascade of warnings (and
3002 // they may have intended '%%' anyway). We don't want to continue processing
3003 // the format string after this point, however, as we will like just get
3004 // gibberish when trying to match arguments.
3005 keepGoing = false;
3006 }
3007
Richard Trieu03cf7b72011-10-28 00:41:25 +00003008 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3009 << StringRef(csStart, csLen),
3010 Loc, /*IsStringLocation*/true,
3011 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003012
3013 return keepGoing;
3014}
3015
Richard Trieu03cf7b72011-10-28 00:41:25 +00003016void
3017CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3018 const char *startSpec,
3019 unsigned specifierLen) {
3020 EmitFormatDiagnostic(
3021 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3022 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3023}
3024
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003025bool
3026CheckFormatHandler::CheckNumArgs(
3027 const analyze_format_string::FormatSpecifier &FS,
3028 const analyze_format_string::ConversionSpecifier &CS,
3029 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3030
3031 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003032 PartialDiagnostic PDiag = FS.usesPositionalArg()
3033 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3034 << (argIndex+1) << NumDataArgs)
3035 : S.PDiag(diag::warn_printf_insufficient_data_args);
3036 EmitFormatDiagnostic(
3037 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3038 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003039 return false;
3040 }
3041 return true;
3042}
3043
Richard Trieu03cf7b72011-10-28 00:41:25 +00003044template<typename Range>
3045void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3046 SourceLocation Loc,
3047 bool IsStringLocation,
3048 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003049 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003050 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003051 Loc, IsStringLocation, StringRange, FixIt);
3052}
3053
3054/// \brief If the format string is not within the funcion call, emit a note
3055/// so that the function call and string are in diagnostic messages.
3056///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003057/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003058/// call and only one diagnostic message will be produced. Otherwise, an
3059/// extra note will be emitted pointing to location of the format string.
3060///
3061/// \param ArgumentExpr the expression that is passed as the format string
3062/// argument in the function call. Used for getting locations when two
3063/// diagnostics are emitted.
3064///
3065/// \param PDiag the callee should already have provided any strings for the
3066/// diagnostic message. This function only adds locations and fixits
3067/// to diagnostics.
3068///
3069/// \param Loc primary location for diagnostic. If two diagnostics are
3070/// required, one will be at Loc and a new SourceLocation will be created for
3071/// the other one.
3072///
3073/// \param IsStringLocation if true, Loc points to the format string should be
3074/// used for the note. Otherwise, Loc points to the argument list and will
3075/// be used with PDiag.
3076///
3077/// \param StringRange some or all of the string to highlight. This is
3078/// templated so it can accept either a CharSourceRange or a SourceRange.
3079///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003080/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003081template<typename Range>
3082void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3083 const Expr *ArgumentExpr,
3084 PartialDiagnostic PDiag,
3085 SourceLocation Loc,
3086 bool IsStringLocation,
3087 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003088 ArrayRef<FixItHint> FixIt) {
3089 if (InFunctionCall) {
3090 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3091 D << StringRange;
3092 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
3093 I != E; ++I) {
3094 D << *I;
3095 }
3096 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003097 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3098 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003099
3100 const Sema::SemaDiagnosticBuilder &Note =
3101 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3102 diag::note_format_string_defined);
3103
3104 Note << StringRange;
3105 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
3106 I != E; ++I) {
3107 Note << *I;
3108 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00003109 }
3110}
3111
Ted Kremenek02087932010-07-16 02:11:22 +00003112//===--- CHECK: Printf format string checking ------------------------------===//
3113
3114namespace {
3115class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003116 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00003117public:
3118 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3119 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003120 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003121 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003122 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003123 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003124 Sema::VariadicCallType CallType,
3125 llvm::SmallBitVector &CheckedVarArgs)
3126 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3127 numDataArgs, beg, hasVAListArg, Args,
3128 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3129 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003130 {}
3131
Craig Toppere14c0f82014-03-12 04:55:44 +00003132
Ted Kremenek02087932010-07-16 02:11:22 +00003133 bool HandleInvalidPrintfConversionSpecifier(
3134 const analyze_printf::PrintfSpecifier &FS,
3135 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003136 unsigned specifierLen) override;
3137
Ted Kremenek02087932010-07-16 02:11:22 +00003138 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3139 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003140 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003141 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3142 const char *StartSpecifier,
3143 unsigned SpecifierLen,
3144 const Expr *E);
3145
Ted Kremenek02087932010-07-16 02:11:22 +00003146 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3147 const char *startSpecifier, unsigned specifierLen);
3148 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3149 const analyze_printf::OptionalAmount &Amt,
3150 unsigned type,
3151 const char *startSpecifier, unsigned specifierLen);
3152 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3153 const analyze_printf::OptionalFlag &flag,
3154 const char *startSpecifier, unsigned specifierLen);
3155 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3156 const analyze_printf::OptionalFlag &ignoredFlag,
3157 const analyze_printf::OptionalFlag &flag,
3158 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003159 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003160 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00003161
Ted Kremenek02087932010-07-16 02:11:22 +00003162};
3163}
3164
3165bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3166 const analyze_printf::PrintfSpecifier &FS,
3167 const char *startSpecifier,
3168 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003169 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003170 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003171
Ted Kremenekce815422010-07-19 21:25:57 +00003172 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3173 getLocationOfByte(CS.getStart()),
3174 startSpecifier, specifierLen,
3175 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003176}
3177
Ted Kremenek02087932010-07-16 02:11:22 +00003178bool CheckPrintfHandler::HandleAmount(
3179 const analyze_format_string::OptionalAmount &Amt,
3180 unsigned k, const char *startSpecifier,
3181 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003182
3183 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003184 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003185 unsigned argIndex = Amt.getArgIndex();
3186 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003187 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3188 << k,
3189 getLocationOfByte(Amt.getStart()),
3190 /*IsStringLocation*/true,
3191 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003192 // Don't do any more checking. We will just emit
3193 // spurious errors.
3194 return false;
3195 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003196
Ted Kremenek5739de72010-01-29 01:06:55 +00003197 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00003198 // Although not in conformance with C99, we also allow the argument to be
3199 // an 'unsigned int' as that is a reasonably safe case. GCC also
3200 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003201 CoveredArgs.set(argIndex);
3202 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003203 if (!Arg)
3204 return false;
3205
Ted Kremenek5739de72010-01-29 01:06:55 +00003206 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003207
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003208 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3209 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003210
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003211 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003212 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003213 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003214 << T << Arg->getSourceRange(),
3215 getLocationOfByte(Amt.getStart()),
3216 /*IsStringLocation*/true,
3217 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003218 // Don't do any more checking. We will just emit
3219 // spurious errors.
3220 return false;
3221 }
3222 }
3223 }
3224 return true;
3225}
Ted Kremenek5739de72010-01-29 01:06:55 +00003226
Tom Careb49ec692010-06-17 19:00:27 +00003227void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003228 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003229 const analyze_printf::OptionalAmount &Amt,
3230 unsigned type,
3231 const char *startSpecifier,
3232 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003233 const analyze_printf::PrintfConversionSpecifier &CS =
3234 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003235
Richard Trieu03cf7b72011-10-28 00:41:25 +00003236 FixItHint fixit =
3237 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3238 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3239 Amt.getConstantLength()))
3240 : FixItHint();
3241
3242 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3243 << type << CS.toString(),
3244 getLocationOfByte(Amt.getStart()),
3245 /*IsStringLocation*/true,
3246 getSpecifierRange(startSpecifier, specifierLen),
3247 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003248}
3249
Ted Kremenek02087932010-07-16 02:11:22 +00003250void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003251 const analyze_printf::OptionalFlag &flag,
3252 const char *startSpecifier,
3253 unsigned specifierLen) {
3254 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003255 const analyze_printf::PrintfConversionSpecifier &CS =
3256 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003257 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3258 << flag.toString() << CS.toString(),
3259 getLocationOfByte(flag.getPosition()),
3260 /*IsStringLocation*/true,
3261 getSpecifierRange(startSpecifier, specifierLen),
3262 FixItHint::CreateRemoval(
3263 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003264}
3265
3266void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003267 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003268 const analyze_printf::OptionalFlag &ignoredFlag,
3269 const analyze_printf::OptionalFlag &flag,
3270 const char *startSpecifier,
3271 unsigned specifierLen) {
3272 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003273 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3274 << ignoredFlag.toString() << flag.toString(),
3275 getLocationOfByte(ignoredFlag.getPosition()),
3276 /*IsStringLocation*/true,
3277 getSpecifierRange(startSpecifier, specifierLen),
3278 FixItHint::CreateRemoval(
3279 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003280}
3281
Richard Smith55ce3522012-06-25 20:30:08 +00003282// Determines if the specified is a C++ class or struct containing
3283// a member with the specified name and kind (e.g. a CXXMethodDecl named
3284// "c_str()").
3285template<typename MemberKind>
3286static llvm::SmallPtrSet<MemberKind*, 1>
3287CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3288 const RecordType *RT = Ty->getAs<RecordType>();
3289 llvm::SmallPtrSet<MemberKind*, 1> Results;
3290
3291 if (!RT)
3292 return Results;
3293 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003294 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003295 return Results;
3296
Alp Tokerb6cc5922014-05-03 03:45:55 +00003297 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003298 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003299 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003300
3301 // We just need to include all members of the right kind turned up by the
3302 // filter, at this point.
3303 if (S.LookupQualifiedName(R, RT->getDecl()))
3304 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3305 NamedDecl *decl = (*I)->getUnderlyingDecl();
3306 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3307 Results.insert(FK);
3308 }
3309 return Results;
3310}
3311
Richard Smith2868a732014-02-28 01:36:39 +00003312/// Check if we could call '.c_str()' on an object.
3313///
3314/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3315/// allow the call, or if it would be ambiguous).
3316bool Sema::hasCStrMethod(const Expr *E) {
3317 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3318 MethodSet Results =
3319 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3320 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3321 MI != ME; ++MI)
3322 if ((*MI)->getMinRequiredArguments() == 0)
3323 return true;
3324 return false;
3325}
3326
Richard Smith55ce3522012-06-25 20:30:08 +00003327// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003328// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003329// Returns true when a c_str() conversion method is found.
3330bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003331 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003332 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3333
3334 MethodSet Results =
3335 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3336
3337 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3338 MI != ME; ++MI) {
3339 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003340 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003341 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003342 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003343 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003344 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3345 << "c_str()"
3346 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3347 return true;
3348 }
3349 }
3350
3351 return false;
3352}
3353
Ted Kremenekab278de2010-01-28 23:39:18 +00003354bool
Ted Kremenek02087932010-07-16 02:11:22 +00003355CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003356 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003357 const char *startSpecifier,
3358 unsigned specifierLen) {
3359
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003360 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003361 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003362 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003363
Ted Kremenek6cd69422010-07-19 22:01:06 +00003364 if (FS.consumesDataArgument()) {
3365 if (atFirstArg) {
3366 atFirstArg = false;
3367 usesPositionalArgs = FS.usesPositionalArg();
3368 }
3369 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003370 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3371 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003372 return false;
3373 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003374 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003375
Ted Kremenekd1668192010-02-27 01:41:03 +00003376 // First check if the field width, precision, and conversion specifier
3377 // have matching data arguments.
3378 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3379 startSpecifier, specifierLen)) {
3380 return false;
3381 }
3382
3383 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3384 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003385 return false;
3386 }
3387
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003388 if (!CS.consumesDataArgument()) {
3389 // FIXME: Technically specifying a precision or field width here
3390 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003391 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003392 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003393
Ted Kremenek4a49d982010-02-26 19:18:41 +00003394 // Consume the argument.
3395 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003396 if (argIndex < NumDataArgs) {
3397 // The check to see if the argIndex is valid will come later.
3398 // We set the bit here because we may exit early from this
3399 // function if we encounter some other error.
3400 CoveredArgs.set(argIndex);
3401 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003402
3403 // Check for using an Objective-C specific conversion specifier
3404 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003405 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003406 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3407 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003408 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003409
Tom Careb49ec692010-06-17 19:00:27 +00003410 // Check for invalid use of field width
3411 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003412 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003413 startSpecifier, specifierLen);
3414 }
3415
3416 // Check for invalid use of precision
3417 if (!FS.hasValidPrecision()) {
3418 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3419 startSpecifier, specifierLen);
3420 }
3421
3422 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003423 if (!FS.hasValidThousandsGroupingPrefix())
3424 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003425 if (!FS.hasValidLeadingZeros())
3426 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3427 if (!FS.hasValidPlusPrefix())
3428 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003429 if (!FS.hasValidSpacePrefix())
3430 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003431 if (!FS.hasValidAlternativeForm())
3432 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3433 if (!FS.hasValidLeftJustified())
3434 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3435
3436 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003437 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3438 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3439 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003440 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3441 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3442 startSpecifier, specifierLen);
3443
3444 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003445 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003446 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3447 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003448 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003449 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003450 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003451 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3452 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003453
Jordan Rose92303592012-09-08 04:00:03 +00003454 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3455 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3456
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003457 // The remaining checks depend on the data arguments.
3458 if (HasVAListArg)
3459 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003460
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003461 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003462 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003463
Jordan Rose58bbe422012-07-19 18:10:08 +00003464 const Expr *Arg = getDataArg(argIndex);
3465 if (!Arg)
3466 return true;
3467
3468 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003469}
3470
Jordan Roseaee34382012-09-05 22:56:26 +00003471static bool requiresParensToAddCast(const Expr *E) {
3472 // FIXME: We should have a general way to reason about operator
3473 // precedence and whether parens are actually needed here.
3474 // Take care of a few common cases where they aren't.
3475 const Expr *Inside = E->IgnoreImpCasts();
3476 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3477 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3478
3479 switch (Inside->getStmtClass()) {
3480 case Stmt::ArraySubscriptExprClass:
3481 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003482 case Stmt::CharacterLiteralClass:
3483 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003484 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003485 case Stmt::FloatingLiteralClass:
3486 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003487 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003488 case Stmt::ObjCArrayLiteralClass:
3489 case Stmt::ObjCBoolLiteralExprClass:
3490 case Stmt::ObjCBoxedExprClass:
3491 case Stmt::ObjCDictionaryLiteralClass:
3492 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003493 case Stmt::ObjCIvarRefExprClass:
3494 case Stmt::ObjCMessageExprClass:
3495 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003496 case Stmt::ObjCStringLiteralClass:
3497 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003498 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003499 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003500 case Stmt::UnaryOperatorClass:
3501 return false;
3502 default:
3503 return true;
3504 }
3505}
3506
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003507static std::pair<QualType, StringRef>
3508shouldNotPrintDirectly(const ASTContext &Context,
3509 QualType IntendedTy,
3510 const Expr *E) {
3511 // Use a 'while' to peel off layers of typedefs.
3512 QualType TyTy = IntendedTy;
3513 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3514 StringRef Name = UserTy->getDecl()->getName();
3515 QualType CastTy = llvm::StringSwitch<QualType>(Name)
3516 .Case("NSInteger", Context.LongTy)
3517 .Case("NSUInteger", Context.UnsignedLongTy)
3518 .Case("SInt32", Context.IntTy)
3519 .Case("UInt32", Context.UnsignedIntTy)
3520 .Default(QualType());
3521
3522 if (!CastTy.isNull())
3523 return std::make_pair(CastTy, Name);
3524
3525 TyTy = UserTy->desugar();
3526 }
3527
3528 // Strip parens if necessary.
3529 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
3530 return shouldNotPrintDirectly(Context,
3531 PE->getSubExpr()->getType(),
3532 PE->getSubExpr());
3533
3534 // If this is a conditional expression, then its result type is constructed
3535 // via usual arithmetic conversions and thus there might be no necessary
3536 // typedef sugar there. Recurse to operands to check for NSInteger &
3537 // Co. usage condition.
3538 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3539 QualType TrueTy, FalseTy;
3540 StringRef TrueName, FalseName;
3541
3542 std::tie(TrueTy, TrueName) =
3543 shouldNotPrintDirectly(Context,
3544 CO->getTrueExpr()->getType(),
3545 CO->getTrueExpr());
3546 std::tie(FalseTy, FalseName) =
3547 shouldNotPrintDirectly(Context,
3548 CO->getFalseExpr()->getType(),
3549 CO->getFalseExpr());
3550
3551 if (TrueTy == FalseTy)
3552 return std::make_pair(TrueTy, TrueName);
3553 else if (TrueTy.isNull())
3554 return std::make_pair(FalseTy, FalseName);
3555 else if (FalseTy.isNull())
3556 return std::make_pair(TrueTy, TrueName);
3557 }
3558
3559 return std::make_pair(QualType(), StringRef());
3560}
3561
Richard Smith55ce3522012-06-25 20:30:08 +00003562bool
3563CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3564 const char *StartSpecifier,
3565 unsigned SpecifierLen,
3566 const Expr *E) {
3567 using namespace analyze_format_string;
3568 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003569 // Now type check the data expression that matches the
3570 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003571 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3572 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003573 if (!AT.isValid())
3574 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003575
Jordan Rose598ec092012-12-05 18:44:40 +00003576 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003577 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3578 ExprTy = TET->getUnderlyingExpr()->getType();
3579 }
3580
Jordan Rose598ec092012-12-05 18:44:40 +00003581 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003582 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003583
Jordan Rose22b74712012-09-05 22:56:19 +00003584 // Look through argument promotions for our error message's reported type.
3585 // This includes the integral and floating promotions, but excludes array
3586 // and function pointer decay; seeing that an argument intended to be a
3587 // string has type 'char [6]' is probably more confusing than 'char *'.
3588 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3589 if (ICE->getCastKind() == CK_IntegralCast ||
3590 ICE->getCastKind() == CK_FloatingCast) {
3591 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003592 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003593
3594 // Check if we didn't match because of an implicit cast from a 'char'
3595 // or 'short' to an 'int'. This is done because printf is a varargs
3596 // function.
3597 if (ICE->getType() == S.Context.IntTy ||
3598 ICE->getType() == S.Context.UnsignedIntTy) {
3599 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003600 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003601 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003602 }
Jordan Rose98709982012-06-04 22:48:57 +00003603 }
Jordan Rose598ec092012-12-05 18:44:40 +00003604 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3605 // Special case for 'a', which has type 'int' in C.
3606 // Note, however, that we do /not/ want to treat multibyte constants like
3607 // 'MooV' as characters! This form is deprecated but still exists.
3608 if (ExprTy == S.Context.IntTy)
3609 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3610 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003611 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003612
Jordan Rosebc53ed12014-05-31 04:12:14 +00003613 // Look through enums to their underlying type.
3614 bool IsEnum = false;
3615 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3616 ExprTy = EnumTy->getDecl()->getIntegerType();
3617 IsEnum = true;
3618 }
3619
Jordan Rose0e5badd2012-12-05 18:44:49 +00003620 // %C in an Objective-C context prints a unichar, not a wchar_t.
3621 // If the argument is an integer of some kind, believe the %C and suggest
3622 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003623 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003624 if (ObjCContext &&
3625 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3626 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3627 !ExprTy->isCharType()) {
3628 // 'unichar' is defined as a typedef of unsigned short, but we should
3629 // prefer using the typedef if it is visible.
3630 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003631
3632 // While we are here, check if the value is an IntegerLiteral that happens
3633 // to be within the valid range.
3634 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3635 const llvm::APInt &V = IL->getValue();
3636 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3637 return true;
3638 }
3639
Jordan Rose0e5badd2012-12-05 18:44:49 +00003640 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3641 Sema::LookupOrdinaryName);
3642 if (S.LookupName(Result, S.getCurScope())) {
3643 NamedDecl *ND = Result.getFoundDecl();
3644 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3645 if (TD->getUnderlyingType() == IntendedTy)
3646 IntendedTy = S.Context.getTypedefType(TD);
3647 }
3648 }
3649 }
3650
3651 // Special-case some of Darwin's platform-independence types by suggesting
3652 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003653 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00003654 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003655 QualType CastTy;
3656 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
3657 if (!CastTy.isNull()) {
3658 IntendedTy = CastTy;
3659 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00003660 }
3661 }
3662
Jordan Rose22b74712012-09-05 22:56:19 +00003663 // We may be able to offer a FixItHint if it is a supported type.
3664 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003665 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003666 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003667
Jordan Rose22b74712012-09-05 22:56:19 +00003668 if (success) {
3669 // Get the fix string from the fixed format specifier
3670 SmallString<16> buf;
3671 llvm::raw_svector_ostream os(buf);
3672 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003673
Jordan Roseaee34382012-09-05 22:56:26 +00003674 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3675
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003676 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Jordan Rose0e5badd2012-12-05 18:44:49 +00003677 // In this case, the specifier is wrong and should be changed to match
3678 // the argument.
3679 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003680 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3681 << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003682 << E->getSourceRange(),
3683 E->getLocStart(),
3684 /*IsStringLocation*/false,
3685 SpecRange,
3686 FixItHint::CreateReplacement(SpecRange, os.str()));
3687
3688 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003689 // The canonical type for formatting this value is different from the
3690 // actual type of the expression. (This occurs, for example, with Darwin's
3691 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3692 // should be printed as 'long' for 64-bit compatibility.)
3693 // Rather than emitting a normal format/argument mismatch, we want to
3694 // add a cast to the recommended type (and correct the format string
3695 // if necessary).
3696 SmallString<16> CastBuf;
3697 llvm::raw_svector_ostream CastFix(CastBuf);
3698 CastFix << "(";
3699 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3700 CastFix << ")";
3701
3702 SmallVector<FixItHint,4> Hints;
3703 if (!AT.matchesType(S.Context, IntendedTy))
3704 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3705
3706 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3707 // If there's already a cast present, just replace it.
3708 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3709 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3710
3711 } else if (!requiresParensToAddCast(E)) {
3712 // If the expression has high enough precedence,
3713 // just write the C-style cast.
3714 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3715 CastFix.str()));
3716 } else {
3717 // Otherwise, add parens around the expression as well as the cast.
3718 CastFix << "(";
3719 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3720 CastFix.str()));
3721
Alp Tokerb6cc5922014-05-03 03:45:55 +00003722 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003723 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3724 }
3725
Jordan Rose0e5badd2012-12-05 18:44:49 +00003726 if (ShouldNotPrintDirectly) {
3727 // The expression has a type that should not be printed directly.
3728 // We extract the name from the typedef because we don't want to show
3729 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003730 StringRef Name;
3731 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
3732 Name = TypedefTy->getDecl()->getName();
3733 else
3734 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003735 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00003736 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003737 << E->getSourceRange(),
3738 E->getLocStart(), /*IsStringLocation=*/false,
3739 SpecRange, Hints);
3740 } else {
3741 // In this case, the expression could be printed using a different
3742 // specifier, but we've decided that the specifier is probably correct
3743 // and we should cast instead. Just use the normal warning message.
3744 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003745 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3746 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003747 << E->getSourceRange(),
3748 E->getLocStart(), /*IsStringLocation*/false,
3749 SpecRange, Hints);
3750 }
Jordan Roseaee34382012-09-05 22:56:26 +00003751 }
Jordan Rose22b74712012-09-05 22:56:19 +00003752 } else {
3753 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3754 SpecifierLen);
3755 // Since the warning for passing non-POD types to variadic functions
3756 // was deferred until now, we emit a warning for non-POD
3757 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003758 switch (S.isValidVarArgType(ExprTy)) {
3759 case Sema::VAK_Valid:
3760 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003761 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003762 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3763 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Richard Smithd7293d72013-08-05 18:49:43 +00003764 << CSR
3765 << E->getSourceRange(),
3766 E->getLocStart(), /*IsStringLocation*/false, CSR);
3767 break;
3768
3769 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00003770 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00003771 EmitFormatDiagnostic(
3772 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003773 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003774 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003775 << CallType
3776 << AT.getRepresentativeTypeName(S.Context)
3777 << CSR
3778 << E->getSourceRange(),
3779 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003780 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003781 break;
3782
3783 case Sema::VAK_Invalid:
3784 if (ExprTy->isObjCObjectType())
3785 EmitFormatDiagnostic(
3786 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3787 << S.getLangOpts().CPlusPlus11
3788 << ExprTy
3789 << CallType
3790 << AT.getRepresentativeTypeName(S.Context)
3791 << CSR
3792 << E->getSourceRange(),
3793 E->getLocStart(), /*IsStringLocation*/false, CSR);
3794 else
3795 // FIXME: If this is an initializer list, suggest removing the braces
3796 // or inserting a cast to the target type.
3797 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3798 << isa<InitListExpr>(E) << ExprTy << CallType
3799 << AT.getRepresentativeTypeName(S.Context)
3800 << E->getSourceRange();
3801 break;
3802 }
3803
3804 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3805 "format string specifier index out of range");
3806 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003807 }
3808
Ted Kremenekab278de2010-01-28 23:39:18 +00003809 return true;
3810}
3811
Ted Kremenek02087932010-07-16 02:11:22 +00003812//===--- CHECK: Scanf format string checking ------------------------------===//
3813
3814namespace {
3815class CheckScanfHandler : public CheckFormatHandler {
3816public:
3817 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3818 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003819 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003820 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003821 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003822 Sema::VariadicCallType CallType,
3823 llvm::SmallBitVector &CheckedVarArgs)
3824 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3825 numDataArgs, beg, hasVAListArg,
3826 Args, formatIdx, inFunctionCall, CallType,
3827 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003828 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003829
3830 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3831 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003832 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003833
3834 bool HandleInvalidScanfConversionSpecifier(
3835 const analyze_scanf::ScanfSpecifier &FS,
3836 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003837 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003838
Craig Toppere14c0f82014-03-12 04:55:44 +00003839 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003840};
Ted Kremenek019d2242010-01-29 01:50:07 +00003841}
Ted Kremenekab278de2010-01-28 23:39:18 +00003842
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003843void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3844 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003845 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3846 getLocationOfByte(end), /*IsStringLocation*/true,
3847 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003848}
3849
Ted Kremenekce815422010-07-19 21:25:57 +00003850bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3851 const analyze_scanf::ScanfSpecifier &FS,
3852 const char *startSpecifier,
3853 unsigned specifierLen) {
3854
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003855 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003856 FS.getConversionSpecifier();
3857
3858 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3859 getLocationOfByte(CS.getStart()),
3860 startSpecifier, specifierLen,
3861 CS.getStart(), CS.getLength());
3862}
3863
Ted Kremenek02087932010-07-16 02:11:22 +00003864bool CheckScanfHandler::HandleScanfSpecifier(
3865 const analyze_scanf::ScanfSpecifier &FS,
3866 const char *startSpecifier,
3867 unsigned specifierLen) {
3868
3869 using namespace analyze_scanf;
3870 using namespace analyze_format_string;
3871
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003872 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003873
Ted Kremenek6cd69422010-07-19 22:01:06 +00003874 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3875 // be used to decide if we are using positional arguments consistently.
3876 if (FS.consumesDataArgument()) {
3877 if (atFirstArg) {
3878 atFirstArg = false;
3879 usesPositionalArgs = FS.usesPositionalArg();
3880 }
3881 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003882 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3883 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003884 return false;
3885 }
Ted Kremenek02087932010-07-16 02:11:22 +00003886 }
3887
3888 // Check if the field with is non-zero.
3889 const OptionalAmount &Amt = FS.getFieldWidth();
3890 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3891 if (Amt.getConstantAmount() == 0) {
3892 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3893 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003894 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3895 getLocationOfByte(Amt.getStart()),
3896 /*IsStringLocation*/true, R,
3897 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003898 }
3899 }
3900
3901 if (!FS.consumesDataArgument()) {
3902 // FIXME: Technically specifying a precision or field width here
3903 // makes no sense. Worth issuing a warning at some point.
3904 return true;
3905 }
3906
3907 // Consume the argument.
3908 unsigned argIndex = FS.getArgIndex();
3909 if (argIndex < NumDataArgs) {
3910 // The check to see if the argIndex is valid will come later.
3911 // We set the bit here because we may exit early from this
3912 // function if we encounter some other error.
3913 CoveredArgs.set(argIndex);
3914 }
3915
Ted Kremenek4407ea42010-07-20 20:04:47 +00003916 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003917 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003918 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3919 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003920 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003921 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003922 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003923 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3924 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003925
Jordan Rose92303592012-09-08 04:00:03 +00003926 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3927 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3928
Ted Kremenek02087932010-07-16 02:11:22 +00003929 // The remaining checks depend on the data arguments.
3930 if (HasVAListArg)
3931 return true;
3932
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003933 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003934 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003935
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003936 // Check that the argument type matches the format specifier.
3937 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003938 if (!Ex)
3939 return true;
3940
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003941 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3942 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003943 ScanfSpecifier fixedFS = FS;
Jordan Rose177b0a32014-03-20 03:32:39 +00003944 bool success = fixedFS.fixType(Ex->getType(),
3945 Ex->IgnoreImpCasts()->getType(),
3946 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003947
3948 if (success) {
3949 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003950 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003951 llvm::raw_svector_ostream os(buf);
3952 fixedFS.toString(os);
3953
3954 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003955 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3956 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003957 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003958 Ex->getLocStart(),
3959 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003960 getSpecifierRange(startSpecifier, specifierLen),
3961 FixItHint::CreateReplacement(
3962 getSpecifierRange(startSpecifier, specifierLen),
3963 os.str()));
3964 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003965 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003966 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3967 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003968 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003969 Ex->getLocStart(),
3970 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003971 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003972 }
3973 }
3974
Ted Kremenek02087932010-07-16 02:11:22 +00003975 return true;
3976}
3977
3978void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003979 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003980 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003981 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003982 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003983 bool inFunctionCall, VariadicCallType CallType,
3984 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003985
Ted Kremenekab278de2010-01-28 23:39:18 +00003986 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003987 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003988 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003989 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003990 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3991 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003992 return;
3993 }
Ted Kremenek02087932010-07-16 02:11:22 +00003994
Ted Kremenekab278de2010-01-28 23:39:18 +00003995 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003996 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003997 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003998 // Account for cases where the string literal is truncated in a declaration.
3999 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4000 assert(T && "String literal not of constant array type!");
4001 size_t TypeSize = T->getSize().getZExtValue();
4002 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004003 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004004
4005 // Emit a warning if the string literal is truncated and does not contain an
4006 // embedded null character.
4007 if (TypeSize <= StrRef.size() &&
4008 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4009 CheckFormatHandler::EmitFormatDiagnostic(
4010 *this, inFunctionCall, Args[format_idx],
4011 PDiag(diag::warn_printf_format_string_not_null_terminated),
4012 FExpr->getLocStart(),
4013 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4014 return;
4015 }
4016
Ted Kremenekab278de2010-01-28 23:39:18 +00004017 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004018 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004019 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004020 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004021 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4022 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004023 return;
4024 }
Ted Kremenek02087932010-07-16 02:11:22 +00004025
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004026 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00004027 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004028 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004029 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004030 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004031
Hans Wennborg23926bd2011-12-15 10:25:47 +00004032 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004033 getLangOpts(),
4034 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004035 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004036 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004037 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004038 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004039 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004040
Hans Wennborg23926bd2011-12-15 10:25:47 +00004041 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004042 getLangOpts(),
4043 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004044 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004045 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004046}
4047
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004048bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4049 // Str - The format string. NOTE: this is NOT null-terminated!
4050 StringRef StrRef = FExpr->getString();
4051 const char *Str = StrRef.data();
4052 // Account for cases where the string literal is truncated in a declaration.
4053 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4054 assert(T && "String literal not of constant array type!");
4055 size_t TypeSize = T->getSize().getZExtValue();
4056 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4057 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4058 getLangOpts(),
4059 Context.getTargetInfo());
4060}
4061
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004062//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4063
4064// Returns the related absolute value function that is larger, of 0 if one
4065// does not exist.
4066static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4067 switch (AbsFunction) {
4068 default:
4069 return 0;
4070
4071 case Builtin::BI__builtin_abs:
4072 return Builtin::BI__builtin_labs;
4073 case Builtin::BI__builtin_labs:
4074 return Builtin::BI__builtin_llabs;
4075 case Builtin::BI__builtin_llabs:
4076 return 0;
4077
4078 case Builtin::BI__builtin_fabsf:
4079 return Builtin::BI__builtin_fabs;
4080 case Builtin::BI__builtin_fabs:
4081 return Builtin::BI__builtin_fabsl;
4082 case Builtin::BI__builtin_fabsl:
4083 return 0;
4084
4085 case Builtin::BI__builtin_cabsf:
4086 return Builtin::BI__builtin_cabs;
4087 case Builtin::BI__builtin_cabs:
4088 return Builtin::BI__builtin_cabsl;
4089 case Builtin::BI__builtin_cabsl:
4090 return 0;
4091
4092 case Builtin::BIabs:
4093 return Builtin::BIlabs;
4094 case Builtin::BIlabs:
4095 return Builtin::BIllabs;
4096 case Builtin::BIllabs:
4097 return 0;
4098
4099 case Builtin::BIfabsf:
4100 return Builtin::BIfabs;
4101 case Builtin::BIfabs:
4102 return Builtin::BIfabsl;
4103 case Builtin::BIfabsl:
4104 return 0;
4105
4106 case Builtin::BIcabsf:
4107 return Builtin::BIcabs;
4108 case Builtin::BIcabs:
4109 return Builtin::BIcabsl;
4110 case Builtin::BIcabsl:
4111 return 0;
4112 }
4113}
4114
4115// Returns the argument type of the absolute value function.
4116static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4117 unsigned AbsType) {
4118 if (AbsType == 0)
4119 return QualType();
4120
4121 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4122 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4123 if (Error != ASTContext::GE_None)
4124 return QualType();
4125
4126 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4127 if (!FT)
4128 return QualType();
4129
4130 if (FT->getNumParams() != 1)
4131 return QualType();
4132
4133 return FT->getParamType(0);
4134}
4135
4136// Returns the best absolute value function, or zero, based on type and
4137// current absolute value function.
4138static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4139 unsigned AbsFunctionKind) {
4140 unsigned BestKind = 0;
4141 uint64_t ArgSize = Context.getTypeSize(ArgType);
4142 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4143 Kind = getLargerAbsoluteValueFunction(Kind)) {
4144 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4145 if (Context.getTypeSize(ParamType) >= ArgSize) {
4146 if (BestKind == 0)
4147 BestKind = Kind;
4148 else if (Context.hasSameType(ParamType, ArgType)) {
4149 BestKind = Kind;
4150 break;
4151 }
4152 }
4153 }
4154 return BestKind;
4155}
4156
4157enum AbsoluteValueKind {
4158 AVK_Integer,
4159 AVK_Floating,
4160 AVK_Complex
4161};
4162
4163static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4164 if (T->isIntegralOrEnumerationType())
4165 return AVK_Integer;
4166 if (T->isRealFloatingType())
4167 return AVK_Floating;
4168 if (T->isAnyComplexType())
4169 return AVK_Complex;
4170
4171 llvm_unreachable("Type not integer, floating, or complex");
4172}
4173
4174// Changes the absolute value function to a different type. Preserves whether
4175// the function is a builtin.
4176static unsigned changeAbsFunction(unsigned AbsKind,
4177 AbsoluteValueKind ValueKind) {
4178 switch (ValueKind) {
4179 case AVK_Integer:
4180 switch (AbsKind) {
4181 default:
4182 return 0;
4183 case Builtin::BI__builtin_fabsf:
4184 case Builtin::BI__builtin_fabs:
4185 case Builtin::BI__builtin_fabsl:
4186 case Builtin::BI__builtin_cabsf:
4187 case Builtin::BI__builtin_cabs:
4188 case Builtin::BI__builtin_cabsl:
4189 return Builtin::BI__builtin_abs;
4190 case Builtin::BIfabsf:
4191 case Builtin::BIfabs:
4192 case Builtin::BIfabsl:
4193 case Builtin::BIcabsf:
4194 case Builtin::BIcabs:
4195 case Builtin::BIcabsl:
4196 return Builtin::BIabs;
4197 }
4198 case AVK_Floating:
4199 switch (AbsKind) {
4200 default:
4201 return 0;
4202 case Builtin::BI__builtin_abs:
4203 case Builtin::BI__builtin_labs:
4204 case Builtin::BI__builtin_llabs:
4205 case Builtin::BI__builtin_cabsf:
4206 case Builtin::BI__builtin_cabs:
4207 case Builtin::BI__builtin_cabsl:
4208 return Builtin::BI__builtin_fabsf;
4209 case Builtin::BIabs:
4210 case Builtin::BIlabs:
4211 case Builtin::BIllabs:
4212 case Builtin::BIcabsf:
4213 case Builtin::BIcabs:
4214 case Builtin::BIcabsl:
4215 return Builtin::BIfabsf;
4216 }
4217 case AVK_Complex:
4218 switch (AbsKind) {
4219 default:
4220 return 0;
4221 case Builtin::BI__builtin_abs:
4222 case Builtin::BI__builtin_labs:
4223 case Builtin::BI__builtin_llabs:
4224 case Builtin::BI__builtin_fabsf:
4225 case Builtin::BI__builtin_fabs:
4226 case Builtin::BI__builtin_fabsl:
4227 return Builtin::BI__builtin_cabsf;
4228 case Builtin::BIabs:
4229 case Builtin::BIlabs:
4230 case Builtin::BIllabs:
4231 case Builtin::BIfabsf:
4232 case Builtin::BIfabs:
4233 case Builtin::BIfabsl:
4234 return Builtin::BIcabsf;
4235 }
4236 }
4237 llvm_unreachable("Unable to convert function");
4238}
4239
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004240static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004241 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4242 if (!FnInfo)
4243 return 0;
4244
4245 switch (FDecl->getBuiltinID()) {
4246 default:
4247 return 0;
4248 case Builtin::BI__builtin_abs:
4249 case Builtin::BI__builtin_fabs:
4250 case Builtin::BI__builtin_fabsf:
4251 case Builtin::BI__builtin_fabsl:
4252 case Builtin::BI__builtin_labs:
4253 case Builtin::BI__builtin_llabs:
4254 case Builtin::BI__builtin_cabs:
4255 case Builtin::BI__builtin_cabsf:
4256 case Builtin::BI__builtin_cabsl:
4257 case Builtin::BIabs:
4258 case Builtin::BIlabs:
4259 case Builtin::BIllabs:
4260 case Builtin::BIfabs:
4261 case Builtin::BIfabsf:
4262 case Builtin::BIfabsl:
4263 case Builtin::BIcabs:
4264 case Builtin::BIcabsf:
4265 case Builtin::BIcabsl:
4266 return FDecl->getBuiltinID();
4267 }
4268 llvm_unreachable("Unknown Builtin type");
4269}
4270
4271// If the replacement is valid, emit a note with replacement function.
4272// Additionally, suggest including the proper header if not already included.
4273static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004274 unsigned AbsKind, QualType ArgType) {
4275 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004276 const char *HeaderName = nullptr;
4277 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004278 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4279 FunctionName = "std::abs";
4280 if (ArgType->isIntegralOrEnumerationType()) {
4281 HeaderName = "cstdlib";
4282 } else if (ArgType->isRealFloatingType()) {
4283 HeaderName = "cmath";
4284 } else {
4285 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004286 }
Richard Trieubeffb832014-04-15 23:47:53 +00004287
4288 // Lookup all std::abs
4289 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004290 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004291 R.suppressDiagnostics();
4292 S.LookupQualifiedName(R, Std);
4293
4294 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004295 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004296 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4297 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4298 } else {
4299 FDecl = dyn_cast<FunctionDecl>(I);
4300 }
4301 if (!FDecl)
4302 continue;
4303
4304 // Found std::abs(), check that they are the right ones.
4305 if (FDecl->getNumParams() != 1)
4306 continue;
4307
4308 // Check that the parameter type can handle the argument.
4309 QualType ParamType = FDecl->getParamDecl(0)->getType();
4310 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4311 S.Context.getTypeSize(ArgType) <=
4312 S.Context.getTypeSize(ParamType)) {
4313 // Found a function, don't need the header hint.
4314 EmitHeaderHint = false;
4315 break;
4316 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004317 }
Richard Trieubeffb832014-04-15 23:47:53 +00004318 }
4319 } else {
4320 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4321 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4322
4323 if (HeaderName) {
4324 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4325 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4326 R.suppressDiagnostics();
4327 S.LookupName(R, S.getCurScope());
4328
4329 if (R.isSingleResult()) {
4330 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4331 if (FD && FD->getBuiltinID() == AbsKind) {
4332 EmitHeaderHint = false;
4333 } else {
4334 return;
4335 }
4336 } else if (!R.empty()) {
4337 return;
4338 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004339 }
4340 }
4341
4342 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00004343 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004344
Richard Trieubeffb832014-04-15 23:47:53 +00004345 if (!HeaderName)
4346 return;
4347
4348 if (!EmitHeaderHint)
4349 return;
4350
Alp Toker5d96e0a2014-07-11 20:53:51 +00004351 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4352 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00004353}
4354
4355static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4356 if (!FDecl)
4357 return false;
4358
4359 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4360 return false;
4361
4362 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4363
4364 while (ND && ND->isInlineNamespace()) {
4365 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004366 }
Richard Trieubeffb832014-04-15 23:47:53 +00004367
4368 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4369 return false;
4370
4371 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4372 return false;
4373
4374 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004375}
4376
4377// Warn when using the wrong abs() function.
4378void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4379 const FunctionDecl *FDecl,
4380 IdentifierInfo *FnInfo) {
4381 if (Call->getNumArgs() != 1)
4382 return;
4383
4384 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00004385 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4386 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004387 return;
4388
4389 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4390 QualType ParamType = Call->getArg(0)->getType();
4391
Alp Toker5d96e0a2014-07-11 20:53:51 +00004392 // Unsigned types cannot be negative. Suggest removing the absolute value
4393 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004394 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00004395 const char *FunctionName =
4396 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004397 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4398 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00004399 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004400 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4401 return;
4402 }
4403
Richard Trieubeffb832014-04-15 23:47:53 +00004404 // std::abs has overloads which prevent most of the absolute value problems
4405 // from occurring.
4406 if (IsStdAbs)
4407 return;
4408
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004409 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4410 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4411
4412 // The argument and parameter are the same kind. Check if they are the right
4413 // size.
4414 if (ArgValueKind == ParamValueKind) {
4415 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4416 return;
4417
4418 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4419 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4420 << FDecl << ArgType << ParamType;
4421
4422 if (NewAbsKind == 0)
4423 return;
4424
4425 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004426 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004427 return;
4428 }
4429
4430 // ArgValueKind != ParamValueKind
4431 // The wrong type of absolute value function was used. Attempt to find the
4432 // proper one.
4433 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4434 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4435 if (NewAbsKind == 0)
4436 return;
4437
4438 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4439 << FDecl << ParamValueKind << ArgValueKind;
4440
4441 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004442 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004443 return;
4444}
4445
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004446//===--- CHECK: Standard memory functions ---------------------------------===//
4447
Nico Weber0e6daef2013-12-26 23:38:39 +00004448/// \brief Takes the expression passed to the size_t parameter of functions
4449/// such as memcmp, strncat, etc and warns if it's a comparison.
4450///
4451/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4452static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4453 IdentifierInfo *FnName,
4454 SourceLocation FnLoc,
4455 SourceLocation RParenLoc) {
4456 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4457 if (!Size)
4458 return false;
4459
4460 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4461 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4462 return false;
4463
Nico Weber0e6daef2013-12-26 23:38:39 +00004464 SourceRange SizeRange = Size->getSourceRange();
4465 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4466 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00004467 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004468 << FnName << FixItHint::CreateInsertion(
4469 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00004470 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00004471 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00004472 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00004473 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4474 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00004475
4476 return true;
4477}
4478
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004479/// \brief Determine whether the given type is or contains a dynamic class type
4480/// (e.g., whether it has a vtable).
4481static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4482 bool &IsContained) {
4483 // Look through array types while ignoring qualifiers.
4484 const Type *Ty = T->getBaseElementTypeUnsafe();
4485 IsContained = false;
4486
4487 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4488 RD = RD ? RD->getDefinition() : nullptr;
4489 if (!RD)
4490 return nullptr;
4491
4492 if (RD->isDynamicClass())
4493 return RD;
4494
4495 // Check all the fields. If any bases were dynamic, the class is dynamic.
4496 // It's impossible for a class to transitively contain itself by value, so
4497 // infinite recursion is impossible.
4498 for (auto *FD : RD->fields()) {
4499 bool SubContained;
4500 if (const CXXRecordDecl *ContainedRD =
4501 getContainedDynamicClass(FD->getType(), SubContained)) {
4502 IsContained = true;
4503 return ContainedRD;
4504 }
4505 }
4506
4507 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004508}
4509
Chandler Carruth889ed862011-06-21 23:04:20 +00004510/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004511/// otherwise returns NULL.
4512static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004513 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004514 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4515 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4516 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004517
Craig Topperc3ec1492014-05-26 06:22:03 +00004518 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004519}
4520
Chandler Carruth889ed862011-06-21 23:04:20 +00004521/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004522static QualType getSizeOfArgType(const Expr* E) {
4523 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4524 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4525 if (SizeOf->getKind() == clang::UETT_SizeOf)
4526 return SizeOf->getTypeOfArgument();
4527
4528 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004529}
4530
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004531/// \brief Check for dangerous or invalid arguments to memset().
4532///
Chandler Carruthac687262011-06-03 06:23:57 +00004533/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004534/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4535/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004536///
4537/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004538void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004539 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004540 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004541 assert(BId != 0);
4542
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004543 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004544 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004545 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004546 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004547 return;
4548
Anna Zaks22122702012-01-17 00:37:07 +00004549 unsigned LastArg = (BId == Builtin::BImemset ||
4550 BId == Builtin::BIstrndup ? 1 : 2);
4551 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004552 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004553
Nico Weber0e6daef2013-12-26 23:38:39 +00004554 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4555 Call->getLocStart(), Call->getRParenLoc()))
4556 return;
4557
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004558 // We have special checking when the length is a sizeof expression.
4559 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4560 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4561 llvm::FoldingSetNodeID SizeOfArgID;
4562
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004563 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4564 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004565 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004566
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004567 QualType DestTy = Dest->getType();
4568 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4569 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004570
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004571 // Never warn about void type pointers. This can be used to suppress
4572 // false positives.
4573 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004574 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004575
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004576 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4577 // actually comparing the expressions for equality. Because computing the
4578 // expression IDs can be expensive, we only do this if the diagnostic is
4579 // enabled.
4580 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004581 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4582 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004583 // We only compute IDs for expressions if the warning is enabled, and
4584 // cache the sizeof arg's ID.
4585 if (SizeOfArgID == llvm::FoldingSetNodeID())
4586 SizeOfArg->Profile(SizeOfArgID, Context, true);
4587 llvm::FoldingSetNodeID DestID;
4588 Dest->Profile(DestID, Context, true);
4589 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004590 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4591 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004592 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004593 StringRef ReadableName = FnName->getName();
4594
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004595 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004596 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004597 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004598 if (!PointeeTy->isIncompleteType() &&
4599 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004600 ActionIdx = 2; // If the pointee's size is sizeof(char),
4601 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004602
4603 // If the function is defined as a builtin macro, do not show macro
4604 // expansion.
4605 SourceLocation SL = SizeOfArg->getExprLoc();
4606 SourceRange DSR = Dest->getSourceRange();
4607 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004608 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004609
4610 if (SM.isMacroArgExpansion(SL)) {
4611 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4612 SL = SM.getSpellingLoc(SL);
4613 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4614 SM.getSpellingLoc(DSR.getEnd()));
4615 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4616 SM.getSpellingLoc(SSR.getEnd()));
4617 }
4618
Anna Zaksd08d9152012-05-30 23:14:52 +00004619 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004620 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004621 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004622 << PointeeTy
4623 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004624 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004625 << SSR);
4626 DiagRuntimeBehavior(SL, SizeOfArg,
4627 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4628 << ActionIdx
4629 << SSR);
4630
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004631 break;
4632 }
4633 }
4634
4635 // Also check for cases where the sizeof argument is the exact same
4636 // type as the memory argument, and where it points to a user-defined
4637 // record type.
4638 if (SizeOfArgTy != QualType()) {
4639 if (PointeeTy->isRecordType() &&
4640 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4641 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4642 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4643 << FnName << SizeOfArgTy << ArgIdx
4644 << PointeeTy << Dest->getSourceRange()
4645 << LenExpr->getSourceRange());
4646 break;
4647 }
Nico Weberc5e73862011-06-14 16:14:58 +00004648 }
4649
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004650 // Always complain about dynamic classes.
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004651 bool IsContained;
4652 if (const CXXRecordDecl *ContainedRD =
4653 getContainedDynamicClass(PointeeTy, IsContained)) {
Anna Zaks22122702012-01-17 00:37:07 +00004654
4655 unsigned OperationType = 0;
4656 // "overwritten" if we're warning about the destination for any call
4657 // but memcmp; otherwise a verb appropriate to the call.
4658 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4659 if (BId == Builtin::BImemcpy)
4660 OperationType = 1;
4661 else if(BId == Builtin::BImemmove)
4662 OperationType = 2;
4663 else if (BId == Builtin::BImemcmp)
4664 OperationType = 3;
4665 }
4666
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004667 DiagRuntimeBehavior(
4668 Dest->getExprLoc(), Dest,
4669 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004670 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004671 << FnName << IsContained << ContainedRD << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004672 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004673 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4674 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004675 DiagRuntimeBehavior(
4676 Dest->getExprLoc(), Dest,
4677 PDiag(diag::warn_arc_object_memaccess)
4678 << ArgIdx << FnName << PointeeTy
4679 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004680 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004681 continue;
John McCall31168b02011-06-15 23:02:42 +00004682
4683 DiagRuntimeBehavior(
4684 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004685 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004686 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4687 break;
4688 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004689 }
4690}
4691
Ted Kremenek6865f772011-08-18 20:55:45 +00004692// A little helper routine: ignore addition and subtraction of integer literals.
4693// This intentionally does not ignore all integer constant expressions because
4694// we don't want to remove sizeof().
4695static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4696 Ex = Ex->IgnoreParenCasts();
4697
4698 for (;;) {
4699 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4700 if (!BO || !BO->isAdditiveOp())
4701 break;
4702
4703 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4704 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4705
4706 if (isa<IntegerLiteral>(RHS))
4707 Ex = LHS;
4708 else if (isa<IntegerLiteral>(LHS))
4709 Ex = RHS;
4710 else
4711 break;
4712 }
4713
4714 return Ex;
4715}
4716
Anna Zaks13b08572012-08-08 21:42:23 +00004717static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4718 ASTContext &Context) {
4719 // Only handle constant-sized or VLAs, but not flexible members.
4720 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4721 // Only issue the FIXIT for arrays of size > 1.
4722 if (CAT->getSize().getSExtValue() <= 1)
4723 return false;
4724 } else if (!Ty->isVariableArrayType()) {
4725 return false;
4726 }
4727 return true;
4728}
4729
Ted Kremenek6865f772011-08-18 20:55:45 +00004730// Warn if the user has made the 'size' argument to strlcpy or strlcat
4731// be the size of the source, instead of the destination.
4732void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4733 IdentifierInfo *FnName) {
4734
4735 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00004736 unsigned NumArgs = Call->getNumArgs();
4737 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00004738 return;
4739
4740 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4741 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004742 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00004743
4744 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4745 Call->getLocStart(), Call->getRParenLoc()))
4746 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004747
4748 // Look for 'strlcpy(dst, x, sizeof(x))'
4749 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4750 CompareWithSrc = Ex;
4751 else {
4752 // Look for 'strlcpy(dst, x, strlen(x))'
4753 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004754 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4755 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004756 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4757 }
4758 }
4759
4760 if (!CompareWithSrc)
4761 return;
4762
4763 // Determine if the argument to sizeof/strlen is equal to the source
4764 // argument. In principle there's all kinds of things you could do
4765 // here, for instance creating an == expression and evaluating it with
4766 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4767 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4768 if (!SrcArgDRE)
4769 return;
4770
4771 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4772 if (!CompareWithSrcDRE ||
4773 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4774 return;
4775
4776 const Expr *OriginalSizeArg = Call->getArg(2);
4777 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4778 << OriginalSizeArg->getSourceRange() << FnName;
4779
4780 // Output a FIXIT hint if the destination is an array (rather than a
4781 // pointer to an array). This could be enhanced to handle some
4782 // pointers if we know the actual size, like if DstArg is 'array+2'
4783 // we could say 'sizeof(array)-2'.
4784 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004785 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004786 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004787
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004788 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004789 llvm::raw_svector_ostream OS(sizeString);
4790 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004791 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004792 OS << ")";
4793
4794 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4795 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4796 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004797}
4798
Anna Zaks314cd092012-02-01 19:08:57 +00004799/// Check if two expressions refer to the same declaration.
4800static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4801 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4802 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4803 return D1->getDecl() == D2->getDecl();
4804 return false;
4805}
4806
4807static const Expr *getStrlenExprArg(const Expr *E) {
4808 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4809 const FunctionDecl *FD = CE->getDirectCallee();
4810 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00004811 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004812 return CE->getArg(0)->IgnoreParenCasts();
4813 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004814 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004815}
4816
4817// Warn on anti-patterns as the 'size' argument to strncat.
4818// The correct size argument should look like following:
4819// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4820void Sema::CheckStrncatArguments(const CallExpr *CE,
4821 IdentifierInfo *FnName) {
4822 // Don't crash if the user has the wrong number of arguments.
4823 if (CE->getNumArgs() < 3)
4824 return;
4825 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4826 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4827 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4828
Nico Weber0e6daef2013-12-26 23:38:39 +00004829 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4830 CE->getRParenLoc()))
4831 return;
4832
Anna Zaks314cd092012-02-01 19:08:57 +00004833 // Identify common expressions, which are wrongly used as the size argument
4834 // to strncat and may lead to buffer overflows.
4835 unsigned PatternType = 0;
4836 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4837 // - sizeof(dst)
4838 if (referToTheSameDecl(SizeOfArg, DstArg))
4839 PatternType = 1;
4840 // - sizeof(src)
4841 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4842 PatternType = 2;
4843 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4844 if (BE->getOpcode() == BO_Sub) {
4845 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4846 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4847 // - sizeof(dst) - strlen(dst)
4848 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4849 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4850 PatternType = 1;
4851 // - sizeof(src) - (anything)
4852 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4853 PatternType = 2;
4854 }
4855 }
4856
4857 if (PatternType == 0)
4858 return;
4859
Anna Zaks5069aa32012-02-03 01:27:37 +00004860 // Generate the diagnostic.
4861 SourceLocation SL = LenArg->getLocStart();
4862 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004863 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00004864
4865 // If the function is defined as a builtin macro, do not show macro expansion.
4866 if (SM.isMacroArgExpansion(SL)) {
4867 SL = SM.getSpellingLoc(SL);
4868 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4869 SM.getSpellingLoc(SR.getEnd()));
4870 }
4871
Anna Zaks13b08572012-08-08 21:42:23 +00004872 // Check if the destination is an array (rather than a pointer to an array).
4873 QualType DstTy = DstArg->getType();
4874 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4875 Context);
4876 if (!isKnownSizeArray) {
4877 if (PatternType == 1)
4878 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4879 else
4880 Diag(SL, diag::warn_strncat_src_size) << SR;
4881 return;
4882 }
4883
Anna Zaks314cd092012-02-01 19:08:57 +00004884 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004885 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004886 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004887 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004888
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004889 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004890 llvm::raw_svector_ostream OS(sizeString);
4891 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004892 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004893 OS << ") - ";
4894 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004895 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004896 OS << ") - 1";
4897
Anna Zaks5069aa32012-02-03 01:27:37 +00004898 Diag(SL, diag::note_strncat_wrong_size)
4899 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004900}
4901
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004902//===--- CHECK: Return Address of Stack Variable --------------------------===//
4903
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004904static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4905 Decl *ParentDecl);
4906static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4907 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004908
4909/// CheckReturnStackAddr - Check if a return statement returns the address
4910/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004911static void
4912CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4913 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004914
Craig Topperc3ec1492014-05-26 06:22:03 +00004915 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004916 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004917
4918 // Perform checking for returned stack addresses, local blocks,
4919 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004920 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004921 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004922 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00004923 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004924 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004925 }
4926
Craig Topperc3ec1492014-05-26 06:22:03 +00004927 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004928 return; // Nothing suspicious was found.
4929
4930 SourceLocation diagLoc;
4931 SourceRange diagRange;
4932 if (refVars.empty()) {
4933 diagLoc = stackE->getLocStart();
4934 diagRange = stackE->getSourceRange();
4935 } else {
4936 // We followed through a reference variable. 'stackE' contains the
4937 // problematic expression but we will warn at the return statement pointing
4938 // at the reference variable. We will later display the "trail" of
4939 // reference variables using notes.
4940 diagLoc = refVars[0]->getLocStart();
4941 diagRange = refVars[0]->getSourceRange();
4942 }
4943
4944 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004945 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004946 : diag::warn_ret_stack_addr)
4947 << DR->getDecl()->getDeclName() << diagRange;
4948 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004949 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004950 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004951 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004952 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004953 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4954 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004955 << diagRange;
4956 }
4957
4958 // Display the "trail" of reference variables that we followed until we
4959 // found the problematic expression using notes.
4960 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4961 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4962 // If this var binds to another reference var, show the range of the next
4963 // var, otherwise the var binds to the problematic expression, in which case
4964 // show the range of the expression.
4965 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4966 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004967 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4968 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004969 }
4970}
4971
4972/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4973/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004974/// to a location on the stack, a local block, an address of a label, or a
4975/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004976/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004977/// encounter a subexpression that (1) clearly does not lead to one of the
4978/// above problematic expressions (2) is something we cannot determine leads to
4979/// a problematic expression based on such local checking.
4980///
4981/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4982/// the expression that they point to. Such variables are added to the
4983/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004984///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004985/// EvalAddr processes expressions that are pointers that are used as
4986/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004987/// At the base case of the recursion is a check for the above problematic
4988/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004989///
4990/// This implementation handles:
4991///
4992/// * pointer-to-pointer casts
4993/// * implicit conversions from array references to pointers
4994/// * taking the address of fields
4995/// * arbitrary interplay between "&" and "*" operators
4996/// * pointer arithmetic from an address of a stack variable
4997/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004998static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4999 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005000 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005001 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005002
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005003 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005004 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005005 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005006 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005007 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005008
Peter Collingbourne91147592011-04-15 00:35:48 +00005009 E = E->IgnoreParens();
5010
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005011 // Our "symbolic interpreter" is just a dispatch off the currently
5012 // viewed AST node. We then recursively traverse the AST by calling
5013 // EvalAddr and EvalVal appropriately.
5014 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005015 case Stmt::DeclRefExprClass: {
5016 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5017
Richard Smith40f08eb2014-01-30 22:05:38 +00005018 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005019 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005020 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005021
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005022 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5023 // If this is a reference variable, follow through to the expression that
5024 // it points to.
5025 if (V->hasLocalStorage() &&
5026 V->getType()->isReferenceType() && V->hasInit()) {
5027 // Add the reference variable to the "trail".
5028 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005029 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005030 }
5031
Craig Topperc3ec1492014-05-26 06:22:03 +00005032 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005033 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005034
Chris Lattner934edb22007-12-28 05:31:15 +00005035 case Stmt::UnaryOperatorClass: {
5036 // The only unary operator that make sense to handle here
5037 // is AddrOf. All others don't make sense as pointers.
5038 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005039
John McCalle3027922010-08-25 11:45:40 +00005040 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005041 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005042 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005043 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005044 }
Mike Stump11289f42009-09-09 15:08:12 +00005045
Chris Lattner934edb22007-12-28 05:31:15 +00005046 case Stmt::BinaryOperatorClass: {
5047 // Handle pointer arithmetic. All other binary operators are not valid
5048 // in this context.
5049 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005050 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005051
John McCalle3027922010-08-25 11:45:40 +00005052 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005053 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005054
Chris Lattner934edb22007-12-28 05:31:15 +00005055 Expr *Base = B->getLHS();
5056
5057 // Determine which argument is the real pointer base. It could be
5058 // the RHS argument instead of the LHS.
5059 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005060
Chris Lattner934edb22007-12-28 05:31:15 +00005061 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005062 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005063 }
Steve Naroff2752a172008-09-10 19:17:48 +00005064
Chris Lattner934edb22007-12-28 05:31:15 +00005065 // For conditional operators we need to see if either the LHS or RHS are
5066 // valid DeclRefExpr*s. If one of them is valid, we return it.
5067 case Stmt::ConditionalOperatorClass: {
5068 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005069
Chris Lattner934edb22007-12-28 05:31:15 +00005070 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005071 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5072 if (Expr *LHSExpr = C->getLHS()) {
5073 // In C++, we can have a throw-expression, which has 'void' type.
5074 if (!LHSExpr->getType()->isVoidType())
5075 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005076 return LHS;
5077 }
Chris Lattner934edb22007-12-28 05:31:15 +00005078
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005079 // In C++, we can have a throw-expression, which has 'void' type.
5080 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005081 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005082
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005083 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005084 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005085
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005086 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00005087 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005088 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00005089 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005090
5091 case Stmt::AddrLabelExprClass:
5092 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00005093
John McCall28fc7092011-11-10 05:35:25 +00005094 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005095 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5096 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005097
Ted Kremenekc3b4c522008-08-07 00:49:01 +00005098 // For casts, we need to handle conversions from arrays to
5099 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00005100 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00005101 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005102 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00005103 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00005104 case Stmt::CXXStaticCastExprClass:
5105 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00005106 case Stmt::CXXConstCastExprClass:
5107 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00005108 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5109 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00005110 case CK_LValueToRValue:
5111 case CK_NoOp:
5112 case CK_BaseToDerived:
5113 case CK_DerivedToBase:
5114 case CK_UncheckedDerivedToBase:
5115 case CK_Dynamic:
5116 case CK_CPointerToObjCPointerCast:
5117 case CK_BlockPointerToObjCPointerCast:
5118 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005119 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005120
5121 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005122 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005123
Richard Trieudadefde2014-07-02 04:39:38 +00005124 case CK_BitCast:
5125 if (SubExpr->getType()->isAnyPointerType() ||
5126 SubExpr->getType()->isBlockPointerType() ||
5127 SubExpr->getType()->isObjCQualifiedIdType())
5128 return EvalAddr(SubExpr, refVars, ParentDecl);
5129 else
5130 return nullptr;
5131
Eli Friedman8195ad72012-02-23 23:04:32 +00005132 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005133 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00005134 }
Chris Lattner934edb22007-12-28 05:31:15 +00005135 }
Mike Stump11289f42009-09-09 15:08:12 +00005136
Douglas Gregorfe314812011-06-21 17:03:29 +00005137 case Stmt::MaterializeTemporaryExprClass:
5138 if (Expr *Result = EvalAddr(
5139 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005140 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005141 return Result;
5142
5143 return E;
5144
Chris Lattner934edb22007-12-28 05:31:15 +00005145 // Everything else: we simply don't reason about them.
5146 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005147 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00005148 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005149}
Mike Stump11289f42009-09-09 15:08:12 +00005150
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005151
5152/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5153/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005154static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5155 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005156do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005157 // We should only be called for evaluating non-pointer expressions, or
5158 // expressions with a pointer type that are not used as references but instead
5159 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00005160
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005161 // Our "symbolic interpreter" is just a dispatch off the currently
5162 // viewed AST node. We then recursively traverse the AST by calling
5163 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00005164
5165 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005166 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005167 case Stmt::ImplicitCastExprClass: {
5168 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00005169 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005170 E = IE->getSubExpr();
5171 continue;
5172 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005173 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00005174 }
5175
John McCall28fc7092011-11-10 05:35:25 +00005176 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005177 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005178
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005179 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005180 // When we hit a DeclRefExpr we are looking at code that refers to a
5181 // variable's name. If it's not a reference variable we check if it has
5182 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005183 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005184
Richard Smith40f08eb2014-01-30 22:05:38 +00005185 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005186 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005187 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005188
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005189 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5190 // Check if it refers to itself, e.g. "int& i = i;".
5191 if (V == ParentDecl)
5192 return DR;
5193
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005194 if (V->hasLocalStorage()) {
5195 if (!V->getType()->isReferenceType())
5196 return DR;
5197
5198 // Reference variable, follow through to the expression that
5199 // it points to.
5200 if (V->hasInit()) {
5201 // Add the reference variable to the "trail".
5202 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005203 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005204 }
5205 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005206 }
Mike Stump11289f42009-09-09 15:08:12 +00005207
Craig Topperc3ec1492014-05-26 06:22:03 +00005208 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005209 }
Mike Stump11289f42009-09-09 15:08:12 +00005210
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005211 case Stmt::UnaryOperatorClass: {
5212 // The only unary operator that make sense to handle here
5213 // is Deref. All others don't resolve to a "name." This includes
5214 // handling all sorts of rvalues passed to a unary operator.
5215 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005216
John McCalle3027922010-08-25 11:45:40 +00005217 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005218 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005219
Craig Topperc3ec1492014-05-26 06:22:03 +00005220 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005221 }
Mike Stump11289f42009-09-09 15:08:12 +00005222
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005223 case Stmt::ArraySubscriptExprClass: {
5224 // Array subscripts are potential references to data on the stack. We
5225 // retrieve the DeclRefExpr* for the array variable if it indeed
5226 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005227 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005228 }
Mike Stump11289f42009-09-09 15:08:12 +00005229
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005230 case Stmt::ConditionalOperatorClass: {
5231 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005232 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005233 ConditionalOperator *C = cast<ConditionalOperator>(E);
5234
Anders Carlsson801c5c72007-11-30 19:04:31 +00005235 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005236 if (Expr *LHSExpr = C->getLHS()) {
5237 // In C++, we can have a throw-expression, which has 'void' type.
5238 if (!LHSExpr->getType()->isVoidType())
5239 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5240 return LHS;
5241 }
5242
5243 // In C++, we can have a throw-expression, which has 'void' type.
5244 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005245 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005246
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005247 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005248 }
Mike Stump11289f42009-09-09 15:08:12 +00005249
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005250 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005251 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005252 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005253
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005254 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005255 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005256 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005257
5258 // Check whether the member type is itself a reference, in which case
5259 // we're not going to refer to the member, but to what the member refers to.
5260 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005261 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005262
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005263 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005264 }
Mike Stump11289f42009-09-09 15:08:12 +00005265
Douglas Gregorfe314812011-06-21 17:03:29 +00005266 case Stmt::MaterializeTemporaryExprClass:
5267 if (Expr *Result = EvalVal(
5268 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005269 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005270 return Result;
5271
5272 return E;
5273
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005274 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005275 // Check that we don't return or take the address of a reference to a
5276 // temporary. This is only useful in C++.
5277 if (!E->isTypeDependent() && E->isRValue())
5278 return E;
5279
5280 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005281 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005282 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005283} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005284}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005285
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005286void
5287Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5288 SourceLocation ReturnLoc,
5289 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005290 const AttrVec *Attrs,
5291 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005292 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5293
5294 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00005295 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5296 CheckNonNullExpr(*this, RetValExp))
5297 Diag(ReturnLoc, diag::warn_null_ret)
5298 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00005299
5300 // C++11 [basic.stc.dynamic.allocation]p4:
5301 // If an allocation function declared with a non-throwing
5302 // exception-specification fails to allocate storage, it shall return
5303 // a null pointer. Any other allocation function that fails to allocate
5304 // storage shall indicate failure only by throwing an exception [...]
5305 if (FD) {
5306 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5307 if (Op == OO_New || Op == OO_Array_New) {
5308 const FunctionProtoType *Proto
5309 = FD->getType()->castAs<FunctionProtoType>();
5310 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5311 CheckNonNullExpr(*this, RetValExp))
5312 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5313 << FD << getLangOpts().CPlusPlus11;
5314 }
5315 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005316}
5317
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005318//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5319
5320/// Check for comparisons of floating point operands using != and ==.
5321/// Issue a warning if these are no self-comparisons, as they are not likely
5322/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00005323void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00005324 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5325 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005326
5327 // Special case: check for x == x (which is OK).
5328 // Do not emit warnings for such cases.
5329 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5330 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5331 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00005332 return;
Mike Stump11289f42009-09-09 15:08:12 +00005333
5334
Ted Kremenekeda40e22007-11-29 00:59:04 +00005335 // Special case: check for comparisons against literals that can be exactly
5336 // represented by APFloat. In such cases, do not emit a warning. This
5337 // is a heuristic: often comparison against such literals are used to
5338 // detect if a value in a variable has not changed. This clearly can
5339 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00005340 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5341 if (FLL->isExact())
5342 return;
5343 } else
5344 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5345 if (FLR->isExact())
5346 return;
Mike Stump11289f42009-09-09 15:08:12 +00005347
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005348 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00005349 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005350 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005351 return;
Mike Stump11289f42009-09-09 15:08:12 +00005352
David Blaikie1f4ff152012-07-16 20:47:22 +00005353 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005354 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005355 return;
Mike Stump11289f42009-09-09 15:08:12 +00005356
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005357 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00005358 Diag(Loc, diag::warn_floatingpoint_eq)
5359 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005360}
John McCallca01b222010-01-04 23:21:16 +00005361
John McCall70aa5392010-01-06 05:24:50 +00005362//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5363//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00005364
John McCall70aa5392010-01-06 05:24:50 +00005365namespace {
John McCallca01b222010-01-04 23:21:16 +00005366
John McCall70aa5392010-01-06 05:24:50 +00005367/// Structure recording the 'active' range of an integer-valued
5368/// expression.
5369struct IntRange {
5370 /// The number of bits active in the int.
5371 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00005372
John McCall70aa5392010-01-06 05:24:50 +00005373 /// True if the int is known not to have negative values.
5374 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00005375
John McCall70aa5392010-01-06 05:24:50 +00005376 IntRange(unsigned Width, bool NonNegative)
5377 : Width(Width), NonNegative(NonNegative)
5378 {}
John McCallca01b222010-01-04 23:21:16 +00005379
John McCall817d4af2010-11-10 23:38:19 +00005380 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00005381 static IntRange forBoolType() {
5382 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00005383 }
5384
John McCall817d4af2010-11-10 23:38:19 +00005385 /// Returns the range of an opaque value of the given integral type.
5386 static IntRange forValueOfType(ASTContext &C, QualType T) {
5387 return forValueOfCanonicalType(C,
5388 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00005389 }
5390
John McCall817d4af2010-11-10 23:38:19 +00005391 /// Returns the range of an opaque value of a canonical integral type.
5392 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00005393 assert(T->isCanonicalUnqualified());
5394
5395 if (const VectorType *VT = dyn_cast<VectorType>(T))
5396 T = VT->getElementType().getTypePtr();
5397 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5398 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005399 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5400 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00005401
David Majnemer6a426652013-06-07 22:07:20 +00005402 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00005403 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00005404 EnumDecl *Enum = ET->getDecl();
5405 if (!Enum->isCompleteDefinition())
5406 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00005407
David Majnemer6a426652013-06-07 22:07:20 +00005408 unsigned NumPositive = Enum->getNumPositiveBits();
5409 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00005410
David Majnemer6a426652013-06-07 22:07:20 +00005411 if (NumNegative == 0)
5412 return IntRange(NumPositive, true/*NonNegative*/);
5413 else
5414 return IntRange(std::max(NumPositive + 1, NumNegative),
5415 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00005416 }
John McCall70aa5392010-01-06 05:24:50 +00005417
5418 const BuiltinType *BT = cast<BuiltinType>(T);
5419 assert(BT->isInteger());
5420
5421 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5422 }
5423
John McCall817d4af2010-11-10 23:38:19 +00005424 /// Returns the "target" range of a canonical integral type, i.e.
5425 /// the range of values expressible in the type.
5426 ///
5427 /// This matches forValueOfCanonicalType except that enums have the
5428 /// full range of their type, not the range of their enumerators.
5429 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5430 assert(T->isCanonicalUnqualified());
5431
5432 if (const VectorType *VT = dyn_cast<VectorType>(T))
5433 T = VT->getElementType().getTypePtr();
5434 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5435 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005436 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5437 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005438 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00005439 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005440
5441 const BuiltinType *BT = cast<BuiltinType>(T);
5442 assert(BT->isInteger());
5443
5444 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5445 }
5446
5447 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00005448 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00005449 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00005450 L.NonNegative && R.NonNegative);
5451 }
5452
John McCall817d4af2010-11-10 23:38:19 +00005453 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00005454 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00005455 return IntRange(std::min(L.Width, R.Width),
5456 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00005457 }
5458};
5459
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005460static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5461 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005462 if (value.isSigned() && value.isNegative())
5463 return IntRange(value.getMinSignedBits(), false);
5464
5465 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005466 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005467
5468 // isNonNegative() just checks the sign bit without considering
5469 // signedness.
5470 return IntRange(value.getActiveBits(), true);
5471}
5472
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005473static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5474 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005475 if (result.isInt())
5476 return GetValueRange(C, result.getInt(), MaxWidth);
5477
5478 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00005479 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5480 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5481 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5482 R = IntRange::join(R, El);
5483 }
John McCall70aa5392010-01-06 05:24:50 +00005484 return R;
5485 }
5486
5487 if (result.isComplexInt()) {
5488 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5489 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5490 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00005491 }
5492
5493 // This can happen with lossless casts to intptr_t of "based" lvalues.
5494 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00005495 // FIXME: The only reason we need to pass the type in here is to get
5496 // the sign right on this one case. It would be nice if APValue
5497 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005498 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00005499 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005500}
John McCall70aa5392010-01-06 05:24:50 +00005501
Eli Friedmane6d33952013-07-08 20:20:06 +00005502static QualType GetExprType(Expr *E) {
5503 QualType Ty = E->getType();
5504 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5505 Ty = AtomicRHS->getValueType();
5506 return Ty;
5507}
5508
John McCall70aa5392010-01-06 05:24:50 +00005509/// Pseudo-evaluate the given integer expression, estimating the
5510/// range of values it might take.
5511///
5512/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005513static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005514 E = E->IgnoreParens();
5515
5516 // Try a full evaluation first.
5517 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005518 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005519 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005520
5521 // I think we only want to look through implicit casts here; if the
5522 // user has an explicit widening cast, we should treat the value as
5523 // being of the new, wider type.
5524 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005525 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005526 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5527
Eli Friedmane6d33952013-07-08 20:20:06 +00005528 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005529
John McCalle3027922010-08-25 11:45:40 +00005530 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005531
John McCall70aa5392010-01-06 05:24:50 +00005532 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005533 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005534 return OutputTypeRange;
5535
5536 IntRange SubRange
5537 = GetExprRange(C, CE->getSubExpr(),
5538 std::min(MaxWidth, OutputTypeRange.Width));
5539
5540 // Bail out if the subexpr's range is as wide as the cast type.
5541 if (SubRange.Width >= OutputTypeRange.Width)
5542 return OutputTypeRange;
5543
5544 // Otherwise, we take the smaller width, and we're non-negative if
5545 // either the output type or the subexpr is.
5546 return IntRange(SubRange.Width,
5547 SubRange.NonNegative || OutputTypeRange.NonNegative);
5548 }
5549
5550 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5551 // If we can fold the condition, just take that operand.
5552 bool CondResult;
5553 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5554 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5555 : CO->getFalseExpr(),
5556 MaxWidth);
5557
5558 // Otherwise, conservatively merge.
5559 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5560 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5561 return IntRange::join(L, R);
5562 }
5563
5564 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5565 switch (BO->getOpcode()) {
5566
5567 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005568 case BO_LAnd:
5569 case BO_LOr:
5570 case BO_LT:
5571 case BO_GT:
5572 case BO_LE:
5573 case BO_GE:
5574 case BO_EQ:
5575 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005576 return IntRange::forBoolType();
5577
John McCallc3688382011-07-13 06:35:24 +00005578 // The type of the assignments is the type of the LHS, so the RHS
5579 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005580 case BO_MulAssign:
5581 case BO_DivAssign:
5582 case BO_RemAssign:
5583 case BO_AddAssign:
5584 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005585 case BO_XorAssign:
5586 case BO_OrAssign:
5587 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005588 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005589
John McCallc3688382011-07-13 06:35:24 +00005590 // Simple assignments just pass through the RHS, which will have
5591 // been coerced to the LHS type.
5592 case BO_Assign:
5593 // TODO: bitfields?
5594 return GetExprRange(C, BO->getRHS(), MaxWidth);
5595
John McCall70aa5392010-01-06 05:24:50 +00005596 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005597 case BO_PtrMemD:
5598 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005599 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005600
John McCall2ce81ad2010-01-06 22:07:33 +00005601 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005602 case BO_And:
5603 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005604 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5605 GetExprRange(C, BO->getRHS(), MaxWidth));
5606
John McCall70aa5392010-01-06 05:24:50 +00005607 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005608 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005609 // ...except that we want to treat '1 << (blah)' as logically
5610 // positive. It's an important idiom.
5611 if (IntegerLiteral *I
5612 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5613 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005614 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005615 return IntRange(R.Width, /*NonNegative*/ true);
5616 }
5617 }
5618 // fallthrough
5619
John McCalle3027922010-08-25 11:45:40 +00005620 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005621 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005622
John McCall2ce81ad2010-01-06 22:07:33 +00005623 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005624 case BO_Shr:
5625 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005626 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5627
5628 // If the shift amount is a positive constant, drop the width by
5629 // that much.
5630 llvm::APSInt shift;
5631 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5632 shift.isNonNegative()) {
5633 unsigned zext = shift.getZExtValue();
5634 if (zext >= L.Width)
5635 L.Width = (L.NonNegative ? 0 : 1);
5636 else
5637 L.Width -= zext;
5638 }
5639
5640 return L;
5641 }
5642
5643 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005644 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005645 return GetExprRange(C, BO->getRHS(), MaxWidth);
5646
John McCall2ce81ad2010-01-06 22:07:33 +00005647 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005648 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005649 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005650 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005651 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005652
John McCall51431812011-07-14 22:39:48 +00005653 // The width of a division result is mostly determined by the size
5654 // of the LHS.
5655 case BO_Div: {
5656 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005657 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005658 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5659
5660 // If the divisor is constant, use that.
5661 llvm::APSInt divisor;
5662 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5663 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5664 if (log2 >= L.Width)
5665 L.Width = (L.NonNegative ? 0 : 1);
5666 else
5667 L.Width = std::min(L.Width - log2, MaxWidth);
5668 return L;
5669 }
5670
5671 // Otherwise, just use the LHS's width.
5672 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5673 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5674 }
5675
5676 // The result of a remainder can't be larger than the result of
5677 // either side.
5678 case BO_Rem: {
5679 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005680 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005681 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5682 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5683
5684 IntRange meet = IntRange::meet(L, R);
5685 meet.Width = std::min(meet.Width, MaxWidth);
5686 return meet;
5687 }
5688
5689 // The default behavior is okay for these.
5690 case BO_Mul:
5691 case BO_Add:
5692 case BO_Xor:
5693 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005694 break;
5695 }
5696
John McCall51431812011-07-14 22:39:48 +00005697 // The default case is to treat the operation as if it were closed
5698 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005699 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5700 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5701 return IntRange::join(L, R);
5702 }
5703
5704 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5705 switch (UO->getOpcode()) {
5706 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005707 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005708 return IntRange::forBoolType();
5709
5710 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005711 case UO_Deref:
5712 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005713 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005714
5715 default:
5716 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5717 }
5718 }
5719
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005720 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5721 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5722
John McCalld25db7e2013-05-06 21:39:12 +00005723 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005724 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005725 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005726
Eli Friedmane6d33952013-07-08 20:20:06 +00005727 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005728}
John McCall263a48b2010-01-04 23:31:57 +00005729
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005730static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005731 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005732}
5733
John McCall263a48b2010-01-04 23:31:57 +00005734/// Checks whether the given value, which currently has the given
5735/// source semantics, has the same value when coerced through the
5736/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005737static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5738 const llvm::fltSemantics &Src,
5739 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005740 llvm::APFloat truncated = value;
5741
5742 bool ignored;
5743 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5744 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5745
5746 return truncated.bitwiseIsEqual(value);
5747}
5748
5749/// Checks whether the given value, which currently has the given
5750/// source semantics, has the same value when coerced through the
5751/// target semantics.
5752///
5753/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005754static bool IsSameFloatAfterCast(const APValue &value,
5755 const llvm::fltSemantics &Src,
5756 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005757 if (value.isFloat())
5758 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5759
5760 if (value.isVector()) {
5761 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5762 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5763 return false;
5764 return true;
5765 }
5766
5767 assert(value.isComplexFloat());
5768 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5769 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5770}
5771
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005772static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005773
Ted Kremenek6274be42010-09-23 21:43:44 +00005774static bool IsZero(Sema &S, Expr *E) {
5775 // Suppress cases where we are comparing against an enum constant.
5776 if (const DeclRefExpr *DR =
5777 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5778 if (isa<EnumConstantDecl>(DR->getDecl()))
5779 return false;
5780
5781 // Suppress cases where the '0' value is expanded from a macro.
5782 if (E->getLocStart().isMacroID())
5783 return false;
5784
John McCallcc7e5bf2010-05-06 08:58:33 +00005785 llvm::APSInt Value;
5786 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5787}
5788
John McCall2551c1b2010-10-06 00:25:24 +00005789static bool HasEnumType(Expr *E) {
5790 // Strip off implicit integral promotions.
5791 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005792 if (ICE->getCastKind() != CK_IntegralCast &&
5793 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005794 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005795 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005796 }
5797
5798 return E->getType()->isEnumeralType();
5799}
5800
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005801static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005802 // Disable warning in template instantiations.
5803 if (!S.ActiveTemplateInstantiations.empty())
5804 return;
5805
John McCalle3027922010-08-25 11:45:40 +00005806 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005807 if (E->isValueDependent())
5808 return;
5809
John McCalle3027922010-08-25 11:45:40 +00005810 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005811 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005812 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005813 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005814 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005815 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005816 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005817 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005818 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005819 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005820 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005821 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005822 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005823 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005824 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005825 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5826 }
5827}
5828
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005829static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005830 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005831 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005832 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005833 // Disable warning in template instantiations.
5834 if (!S.ActiveTemplateInstantiations.empty())
5835 return;
5836
Richard Trieu0f097742014-04-04 04:13:47 +00005837 // TODO: Investigate using GetExprRange() to get tighter bounds
5838 // on the bit ranges.
5839 QualType OtherT = Other->getType();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005840 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5841 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00005842 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5843 unsigned OtherWidth = OtherRange.Width;
5844
5845 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5846
Richard Trieu560910c2012-11-14 22:50:24 +00005847 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00005848 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00005849 return;
5850
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005851 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00005852 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005853
Richard Trieu0f097742014-04-04 04:13:47 +00005854 // Used for diagnostic printout.
5855 enum {
5856 LiteralConstant = 0,
5857 CXXBoolLiteralTrue,
5858 CXXBoolLiteralFalse
5859 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005860
Richard Trieu0f097742014-04-04 04:13:47 +00005861 if (!OtherIsBooleanType) {
5862 QualType ConstantT = Constant->getType();
5863 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005864
Richard Trieu0f097742014-04-04 04:13:47 +00005865 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5866 return;
5867 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5868 "comparison with non-integer type");
5869
5870 bool ConstantSigned = ConstantT->isSignedIntegerType();
5871 bool CommonSigned = CommonT->isSignedIntegerType();
5872
5873 bool EqualityOnly = false;
5874
5875 if (CommonSigned) {
5876 // The common type is signed, therefore no signed to unsigned conversion.
5877 if (!OtherRange.NonNegative) {
5878 // Check that the constant is representable in type OtherT.
5879 if (ConstantSigned) {
5880 if (OtherWidth >= Value.getMinSignedBits())
5881 return;
5882 } else { // !ConstantSigned
5883 if (OtherWidth >= Value.getActiveBits() + 1)
5884 return;
5885 }
5886 } else { // !OtherSigned
5887 // Check that the constant is representable in type OtherT.
5888 // Negative values are out of range.
5889 if (ConstantSigned) {
5890 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5891 return;
5892 } else { // !ConstantSigned
5893 if (OtherWidth >= Value.getActiveBits())
5894 return;
5895 }
Richard Trieu560910c2012-11-14 22:50:24 +00005896 }
Richard Trieu0f097742014-04-04 04:13:47 +00005897 } else { // !CommonSigned
5898 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005899 if (OtherWidth >= Value.getActiveBits())
5900 return;
Craig Toppercf360162014-06-18 05:13:11 +00005901 } else { // OtherSigned
5902 assert(!ConstantSigned &&
5903 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00005904 // Check to see if the constant is representable in OtherT.
5905 if (OtherWidth > Value.getActiveBits())
5906 return;
5907 // Check to see if the constant is equivalent to a negative value
5908 // cast to CommonT.
5909 if (S.Context.getIntWidth(ConstantT) ==
5910 S.Context.getIntWidth(CommonT) &&
5911 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5912 return;
5913 // The constant value rests between values that OtherT can represent
5914 // after conversion. Relational comparison still works, but equality
5915 // comparisons will be tautological.
5916 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005917 }
5918 }
Richard Trieu0f097742014-04-04 04:13:47 +00005919
5920 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5921
5922 if (op == BO_EQ || op == BO_NE) {
5923 IsTrue = op == BO_NE;
5924 } else if (EqualityOnly) {
5925 return;
5926 } else if (RhsConstant) {
5927 if (op == BO_GT || op == BO_GE)
5928 IsTrue = !PositiveConstant;
5929 else // op == BO_LT || op == BO_LE
5930 IsTrue = PositiveConstant;
5931 } else {
5932 if (op == BO_LT || op == BO_LE)
5933 IsTrue = !PositiveConstant;
5934 else // op == BO_GT || op == BO_GE
5935 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005936 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005937 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00005938 // Other isKnownToHaveBooleanValue
5939 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
5940 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
5941 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
5942
5943 static const struct LinkedConditions {
5944 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
5945 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
5946 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
5947 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
5948 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
5949 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
5950
5951 } TruthTable = {
5952 // Constant on LHS. | Constant on RHS. |
5953 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
5954 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
5955 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
5956 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
5957 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
5958 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
5959 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
5960 };
5961
5962 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
5963
5964 enum ConstantValue ConstVal = Zero;
5965 if (Value.isUnsigned() || Value.isNonNegative()) {
5966 if (Value == 0) {
5967 LiteralOrBoolConstant =
5968 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
5969 ConstVal = Zero;
5970 } else if (Value == 1) {
5971 LiteralOrBoolConstant =
5972 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
5973 ConstVal = One;
5974 } else {
5975 LiteralOrBoolConstant = LiteralConstant;
5976 ConstVal = GT_One;
5977 }
5978 } else {
5979 ConstVal = LT_Zero;
5980 }
5981
5982 CompareBoolWithConstantResult CmpRes;
5983
5984 switch (op) {
5985 case BO_LT:
5986 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
5987 break;
5988 case BO_GT:
5989 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
5990 break;
5991 case BO_LE:
5992 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
5993 break;
5994 case BO_GE:
5995 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
5996 break;
5997 case BO_EQ:
5998 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
5999 break;
6000 case BO_NE:
6001 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6002 break;
6003 default:
6004 CmpRes = Unkwn;
6005 break;
6006 }
6007
6008 if (CmpRes == AFals) {
6009 IsTrue = false;
6010 } else if (CmpRes == ATrue) {
6011 IsTrue = true;
6012 } else {
6013 return;
6014 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006015 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006016
6017 // If this is a comparison to an enum constant, include that
6018 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006019 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006020 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6021 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6022
6023 SmallString<64> PrettySourceValue;
6024 llvm::raw_svector_ostream OS(PrettySourceValue);
6025 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00006026 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006027 else
6028 OS << Value;
6029
Richard Trieu0f097742014-04-04 04:13:47 +00006030 S.DiagRuntimeBehavior(
6031 E->getOperatorLoc(), E,
6032 S.PDiag(diag::warn_out_of_range_compare)
6033 << OS.str() << LiteralOrBoolConstant
6034 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6035 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006036}
6037
John McCallcc7e5bf2010-05-06 08:58:33 +00006038/// Analyze the operands of the given comparison. Implements the
6039/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006040static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00006041 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6042 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006043}
John McCall263a48b2010-01-04 23:31:57 +00006044
John McCallca01b222010-01-04 23:21:16 +00006045/// \brief Implements -Wsign-compare.
6046///
Richard Trieu82402a02011-09-15 21:56:47 +00006047/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006048static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006049 // The type the comparison is being performed in.
6050 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006051
6052 // Only analyze comparison operators where both sides have been converted to
6053 // the same type.
6054 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6055 return AnalyzeImpConvsInComparison(S, E);
6056
6057 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006058 if (E->isValueDependent())
6059 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006060
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006061 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6062 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006063
6064 bool IsComparisonConstant = false;
6065
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006066 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006067 // of 'true' or 'false'.
6068 if (T->isIntegralType(S.Context)) {
6069 llvm::APSInt RHSValue;
6070 bool IsRHSIntegralLiteral =
6071 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6072 llvm::APSInt LHSValue;
6073 bool IsLHSIntegralLiteral =
6074 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6075 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6076 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6077 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6078 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6079 else
6080 IsComparisonConstant =
6081 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006082 } else if (!T->hasUnsignedIntegerRepresentation())
6083 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006084
John McCallcc7e5bf2010-05-06 08:58:33 +00006085 // We don't do anything special if this isn't an unsigned integral
6086 // comparison: we're only interested in integral comparisons, and
6087 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00006088 //
6089 // We also don't care about value-dependent expressions or expressions
6090 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006091 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00006092 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006093
John McCallcc7e5bf2010-05-06 08:58:33 +00006094 // Check to see if one of the (unmodified) operands is of different
6095 // signedness.
6096 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00006097 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6098 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00006099 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00006100 signedOperand = LHS;
6101 unsignedOperand = RHS;
6102 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6103 signedOperand = RHS;
6104 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00006105 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00006106 CheckTrivialUnsignedComparison(S, E);
6107 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006108 }
6109
John McCallcc7e5bf2010-05-06 08:58:33 +00006110 // Otherwise, calculate the effective range of the signed operand.
6111 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00006112
John McCallcc7e5bf2010-05-06 08:58:33 +00006113 // Go ahead and analyze implicit conversions in the operands. Note
6114 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00006115 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6116 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00006117
John McCallcc7e5bf2010-05-06 08:58:33 +00006118 // If the signed range is non-negative, -Wsign-compare won't fire,
6119 // but we should still check for comparisons which are always true
6120 // or false.
6121 if (signedRange.NonNegative)
6122 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006123
6124 // For (in)equality comparisons, if the unsigned operand is a
6125 // constant which cannot collide with a overflowed signed operand,
6126 // then reinterpreting the signed operand as unsigned will not
6127 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00006128 if (E->isEqualityOp()) {
6129 unsigned comparisonWidth = S.Context.getIntWidth(T);
6130 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00006131
John McCallcc7e5bf2010-05-06 08:58:33 +00006132 // We should never be unable to prove that the unsigned operand is
6133 // non-negative.
6134 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6135
6136 if (unsignedRange.Width < comparisonWidth)
6137 return;
6138 }
6139
Douglas Gregorbfb4a212012-05-01 01:53:49 +00006140 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6141 S.PDiag(diag::warn_mixed_sign_comparison)
6142 << LHS->getType() << RHS->getType()
6143 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00006144}
6145
John McCall1f425642010-11-11 03:21:53 +00006146/// Analyzes an attempt to assign the given value to a bitfield.
6147///
6148/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006149static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6150 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00006151 assert(Bitfield->isBitField());
6152 if (Bitfield->isInvalidDecl())
6153 return false;
6154
John McCalldeebbcf2010-11-11 05:33:51 +00006155 // White-list bool bitfields.
6156 if (Bitfield->getType()->isBooleanType())
6157 return false;
6158
Douglas Gregor789adec2011-02-04 13:09:01 +00006159 // Ignore value- or type-dependent expressions.
6160 if (Bitfield->getBitWidth()->isValueDependent() ||
6161 Bitfield->getBitWidth()->isTypeDependent() ||
6162 Init->isValueDependent() ||
6163 Init->isTypeDependent())
6164 return false;
6165
John McCall1f425642010-11-11 03:21:53 +00006166 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6167
Richard Smith5fab0c92011-12-28 19:48:30 +00006168 llvm::APSInt Value;
6169 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00006170 return false;
6171
John McCall1f425642010-11-11 03:21:53 +00006172 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00006173 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00006174
6175 if (OriginalWidth <= FieldWidth)
6176 return false;
6177
Eli Friedmanc267a322012-01-26 23:11:39 +00006178 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006179 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00006180 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00006181
Eli Friedmanc267a322012-01-26 23:11:39 +00006182 // Check whether the stored value is equal to the original value.
6183 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00006184 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00006185 return false;
6186
Eli Friedmanc267a322012-01-26 23:11:39 +00006187 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00006188 // therefore don't strictly fit into a signed bitfield of width 1.
6189 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00006190 return false;
6191
John McCall1f425642010-11-11 03:21:53 +00006192 std::string PrettyValue = Value.toString(10);
6193 std::string PrettyTrunc = TruncatedValue.toString(10);
6194
6195 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6196 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6197 << Init->getSourceRange();
6198
6199 return true;
6200}
6201
John McCalld2a53122010-11-09 23:24:47 +00006202/// Analyze the given simple or compound assignment for warning-worthy
6203/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006204static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006205 // Just recurse on the LHS.
6206 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6207
6208 // We want to recurse on the RHS as normal unless we're assigning to
6209 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006210 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006211 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006212 E->getOperatorLoc())) {
6213 // Recurse, ignoring any implicit conversions on the RHS.
6214 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6215 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006216 }
6217 }
6218
6219 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6220}
6221
John McCall263a48b2010-01-04 23:31:57 +00006222/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006223static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006224 SourceLocation CContext, unsigned diag,
6225 bool pruneControlFlow = false) {
6226 if (pruneControlFlow) {
6227 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6228 S.PDiag(diag)
6229 << SourceType << T << E->getSourceRange()
6230 << SourceRange(CContext));
6231 return;
6232 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006233 S.Diag(E->getExprLoc(), diag)
6234 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6235}
6236
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006237/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006238static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006239 SourceLocation CContext, unsigned diag,
6240 bool pruneControlFlow = false) {
6241 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006242}
6243
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006244/// Diagnose an implicit cast from a literal expression. Does not warn when the
6245/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006246void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6247 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006248 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006249 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006250 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006251 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6252 T->hasUnsignedIntegerRepresentation());
6253 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006254 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006255 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006256 return;
6257
Eli Friedman07185912013-08-29 23:44:43 +00006258 // FIXME: Force the precision of the source value down so we don't print
6259 // digits which are usually useless (we don't really care here if we
6260 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6261 // would automatically print the shortest representation, but it's a bit
6262 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006263 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006264 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6265 precision = (precision * 59 + 195) / 196;
6266 Value.toString(PrettySourceValue, precision);
6267
David Blaikie9b88cc02012-05-15 17:18:27 +00006268 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006269 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6270 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6271 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006272 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006273
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006274 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006275 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6276 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006277}
6278
John McCall18a2c2c2010-11-09 22:22:12 +00006279std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6280 if (!Range.Width) return "0";
6281
6282 llvm::APSInt ValueInRange = Value;
6283 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006284 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006285 return ValueInRange.toString(10);
6286}
6287
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006288static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6289 if (!isa<ImplicitCastExpr>(Ex))
6290 return false;
6291
6292 Expr *InnerE = Ex->IgnoreParenImpCasts();
6293 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6294 const Type *Source =
6295 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6296 if (Target->isDependentType())
6297 return false;
6298
6299 const BuiltinType *FloatCandidateBT =
6300 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6301 const Type *BoolCandidateType = ToBool ? Target : Source;
6302
6303 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6304 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6305}
6306
6307void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6308 SourceLocation CC) {
6309 unsigned NumArgs = TheCall->getNumArgs();
6310 for (unsigned i = 0; i < NumArgs; ++i) {
6311 Expr *CurrA = TheCall->getArg(i);
6312 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6313 continue;
6314
6315 bool IsSwapped = ((i > 0) &&
6316 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6317 IsSwapped |= ((i < (NumArgs - 1)) &&
6318 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6319 if (IsSwapped) {
6320 // Warn on this floating-point to bool conversion.
6321 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6322 CurrA->getType(), CC,
6323 diag::warn_impcast_floating_point_to_bool);
6324 }
6325 }
6326}
6327
Richard Trieu5b993502014-10-15 03:42:06 +00006328static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6329 SourceLocation CC) {
6330 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6331 E->getExprLoc()))
6332 return;
6333
6334 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6335 const Expr::NullPointerConstantKind NullKind =
6336 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6337 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6338 return;
6339
6340 // Return if target type is a safe conversion.
6341 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6342 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6343 return;
6344
6345 SourceLocation Loc = E->getSourceRange().getBegin();
6346
6347 // __null is usually wrapped in a macro. Go up a macro if that is the case.
6348 if (NullKind == Expr::NPCK_GNUNull) {
6349 if (Loc.isMacroID())
6350 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6351 }
6352
6353 // Only warn if the null and context location are in the same macro expansion.
6354 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6355 return;
6356
6357 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6358 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6359 << FixItHint::CreateReplacement(Loc,
6360 S.getFixItZeroLiteralForType(T, Loc));
6361}
6362
John McCallcc7e5bf2010-05-06 08:58:33 +00006363void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00006364 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006365 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00006366
John McCallcc7e5bf2010-05-06 08:58:33 +00006367 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6368 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6369 if (Source == Target) return;
6370 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00006371
Chandler Carruthc22845a2011-07-26 05:40:03 +00006372 // If the conversion context location is invalid don't complain. We also
6373 // don't want to emit a warning if the issue occurs from the expansion of
6374 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6375 // delay this check as long as possible. Once we detect we are in that
6376 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006377 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00006378 return;
6379
Richard Trieu021baa32011-09-23 20:10:00 +00006380 // Diagnose implicit casts to bool.
6381 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6382 if (isa<StringLiteral>(E))
6383 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00006384 // and expressions, for instance, assert(0 && "error here"), are
6385 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00006386 return DiagnoseImpCast(S, E, T, CC,
6387 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00006388 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6389 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6390 // This covers the literal expressions that evaluate to Objective-C
6391 // objects.
6392 return DiagnoseImpCast(S, E, T, CC,
6393 diag::warn_impcast_objective_c_literal_to_bool);
6394 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006395 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6396 // Warn on pointer to bool conversion that is always true.
6397 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6398 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00006399 }
Richard Trieu021baa32011-09-23 20:10:00 +00006400 }
John McCall263a48b2010-01-04 23:31:57 +00006401
6402 // Strip vector types.
6403 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006404 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006405 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006406 return;
John McCallacf0ee52010-10-08 02:01:28 +00006407 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006408 }
Chris Lattneree7286f2011-06-14 04:51:15 +00006409
6410 // If the vector cast is cast between two vectors of the same size, it is
6411 // a bitcast, not a conversion.
6412 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6413 return;
John McCall263a48b2010-01-04 23:31:57 +00006414
6415 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6416 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6417 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00006418 if (auto VecTy = dyn_cast<VectorType>(Target))
6419 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00006420
6421 // Strip complex types.
6422 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006423 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006424 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006425 return;
6426
John McCallacf0ee52010-10-08 02:01:28 +00006427 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006428 }
John McCall263a48b2010-01-04 23:31:57 +00006429
6430 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6431 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6432 }
6433
6434 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6435 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6436
6437 // If the source is floating point...
6438 if (SourceBT && SourceBT->isFloatingPoint()) {
6439 // ...and the target is floating point...
6440 if (TargetBT && TargetBT->isFloatingPoint()) {
6441 // ...then warn if we're dropping FP rank.
6442
6443 // Builtin FP kinds are ordered by increasing FP rank.
6444 if (SourceBT->getKind() > TargetBT->getKind()) {
6445 // Don't warn about float constants that are precisely
6446 // representable in the target type.
6447 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006448 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00006449 // Value might be a float, a float vector, or a float complex.
6450 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00006451 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6452 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00006453 return;
6454 }
6455
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006456 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006457 return;
6458
John McCallacf0ee52010-10-08 02:01:28 +00006459 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00006460 }
6461 return;
6462 }
6463
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006464 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00006465 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006466 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006467 return;
6468
Chandler Carruth22c7a792011-02-17 11:05:49 +00006469 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00006470 // We also want to warn on, e.g., "int i = -1.234"
6471 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6472 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6473 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6474
Chandler Carruth016ef402011-04-10 08:36:24 +00006475 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6476 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00006477 } else {
6478 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6479 }
6480 }
John McCall263a48b2010-01-04 23:31:57 +00006481
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006482 // If the target is bool, warn if expr is a function or method call.
6483 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6484 isa<CallExpr>(E)) {
6485 // Check last argument of function call to see if it is an
6486 // implicit cast from a type matching the type the result
6487 // is being cast to.
6488 CallExpr *CEx = cast<CallExpr>(E);
6489 unsigned NumArgs = CEx->getNumArgs();
6490 if (NumArgs > 0) {
6491 Expr *LastA = CEx->getArg(NumArgs - 1);
6492 Expr *InnerE = LastA->IgnoreParenImpCasts();
6493 const Type *InnerType =
6494 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6495 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6496 // Warn on this floating-point to bool conversion
6497 DiagnoseImpCast(S, E, T, CC,
6498 diag::warn_impcast_floating_point_to_bool);
6499 }
6500 }
6501 }
John McCall263a48b2010-01-04 23:31:57 +00006502 return;
6503 }
6504
Richard Trieu5b993502014-10-15 03:42:06 +00006505 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00006506
David Blaikie9366d2b2012-06-19 21:19:06 +00006507 if (!Source->isIntegerType() || !Target->isIntegerType())
6508 return;
6509
David Blaikie7555b6a2012-05-15 16:56:36 +00006510 // TODO: remove this early return once the false positives for constant->bool
6511 // in templates, macros, etc, are reduced or removed.
6512 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6513 return;
6514
John McCallcc7e5bf2010-05-06 08:58:33 +00006515 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00006516 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00006517
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006518 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00006519 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006520 // TODO: this should happen for bitfield stores, too.
6521 llvm::APSInt Value(32);
6522 if (E->isIntegerConstantExpr(Value, S.Context)) {
6523 if (S.SourceMgr.isInSystemMacro(CC))
6524 return;
6525
John McCall18a2c2c2010-11-09 22:22:12 +00006526 std::string PrettySourceValue = Value.toString(10);
6527 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006528
Ted Kremenek33ba9952011-10-22 02:37:33 +00006529 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6530 S.PDiag(diag::warn_impcast_integer_precision_constant)
6531 << PrettySourceValue << PrettyTargetValue
6532 << E->getType() << T << E->getSourceRange()
6533 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006534 return;
6535 }
6536
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006537 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6538 if (S.SourceMgr.isInSystemMacro(CC))
6539 return;
6540
David Blaikie9455da02012-04-12 22:40:54 +00006541 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006542 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6543 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006544 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006545 }
6546
6547 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6548 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6549 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006550
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006551 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006552 return;
6553
John McCallcc7e5bf2010-05-06 08:58:33 +00006554 unsigned DiagID = diag::warn_impcast_integer_sign;
6555
6556 // Traditionally, gcc has warned about this under -Wsign-compare.
6557 // We also want to warn about it in -Wconversion.
6558 // So if -Wconversion is off, use a completely identical diagnostic
6559 // in the sign-compare group.
6560 // The conditional-checking code will
6561 if (ICContext) {
6562 DiagID = diag::warn_impcast_integer_sign_conditional;
6563 *ICContext = true;
6564 }
6565
John McCallacf0ee52010-10-08 02:01:28 +00006566 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006567 }
6568
Douglas Gregora78f1932011-02-22 02:45:07 +00006569 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006570 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6571 // type, to give us better diagnostics.
6572 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006573 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006574 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6575 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6576 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6577 SourceType = S.Context.getTypeDeclType(Enum);
6578 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6579 }
6580 }
6581
Douglas Gregora78f1932011-02-22 02:45:07 +00006582 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6583 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006584 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6585 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006586 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006587 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006588 return;
6589
Douglas Gregor364f7db2011-03-12 00:14:31 +00006590 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006591 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006592 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006593
John McCall263a48b2010-01-04 23:31:57 +00006594 return;
6595}
6596
David Blaikie18e9ac72012-05-15 21:57:38 +00006597void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6598 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006599
6600void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006601 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006602 E = E->IgnoreParenImpCasts();
6603
6604 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006605 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006606
John McCallacf0ee52010-10-08 02:01:28 +00006607 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006608 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006609 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006610 return;
6611}
6612
David Blaikie18e9ac72012-05-15 21:57:38 +00006613void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6614 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00006615 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006616
6617 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006618 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6619 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006620
6621 // If -Wconversion would have warned about either of the candidates
6622 // for a signedness conversion to the context type...
6623 if (!Suspicious) return;
6624
6625 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006626 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006627 return;
6628
John McCallcc7e5bf2010-05-06 08:58:33 +00006629 // ...then check whether it would have warned about either of the
6630 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006631 if (E->getType() == T) return;
6632
6633 Suspicious = false;
6634 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6635 E->getType(), CC, &Suspicious);
6636 if (!Suspicious)
6637 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006638 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006639}
6640
Richard Trieu65724892014-11-15 06:37:39 +00006641/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6642/// Input argument E is a logical expression.
6643static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
6644 if (S.getLangOpts().Bool)
6645 return;
6646 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
6647}
6648
John McCallcc7e5bf2010-05-06 08:58:33 +00006649/// AnalyzeImplicitConversions - Find and report any interesting
6650/// implicit conversions in the given expression. There are a couple
6651/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006652void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006653 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006654 Expr *E = OrigE->IgnoreParenImpCasts();
6655
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006656 if (E->isTypeDependent() || E->isValueDependent())
6657 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006658
John McCallcc7e5bf2010-05-06 08:58:33 +00006659 // For conditional operators, we analyze the arguments as if they
6660 // were being fed directly into the output.
6661 if (isa<ConditionalOperator>(E)) {
6662 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006663 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006664 return;
6665 }
6666
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006667 // Check implicit argument conversions for function calls.
6668 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6669 CheckImplicitArgumentConversions(S, Call, CC);
6670
John McCallcc7e5bf2010-05-06 08:58:33 +00006671 // Go ahead and check any implicit conversions we might have skipped.
6672 // The non-canonical typecheck is just an optimization;
6673 // CheckImplicitConversion will filter out dead implicit conversions.
6674 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006675 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006676
6677 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006678
6679 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006680 if (POE->getResultExpr())
6681 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006682 }
6683
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006684 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6685 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6686
John McCallcc7e5bf2010-05-06 08:58:33 +00006687 // Skip past explicit casts.
6688 if (isa<ExplicitCastExpr>(E)) {
6689 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006690 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006691 }
6692
John McCalld2a53122010-11-09 23:24:47 +00006693 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6694 // Do a somewhat different check with comparison operators.
6695 if (BO->isComparisonOp())
6696 return AnalyzeComparison(S, BO);
6697
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006698 // And with simple assignments.
6699 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006700 return AnalyzeAssignment(S, BO);
6701 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006702
6703 // These break the otherwise-useful invariant below. Fortunately,
6704 // we don't really need to recurse into them, because any internal
6705 // expressions should have been analyzed already when they were
6706 // built into statements.
6707 if (isa<StmtExpr>(E)) return;
6708
6709 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006710 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006711
6712 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006713 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006714 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006715 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006716 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006717 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006718 if (!ChildExpr)
6719 continue;
6720
Richard Trieu955231d2014-01-25 01:10:35 +00006721 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006722 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006723 // Ignore checking string literals that are in logical and operators.
6724 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006725 continue;
6726 AnalyzeImplicitConversions(S, ChildExpr, CC);
6727 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006728
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006729 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00006730 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
6731 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006732 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00006733
6734 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
6735 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006736 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006737 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006738
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006739 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
6740 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00006741 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006742}
6743
6744} // end anonymous namespace
6745
Richard Trieu3bb8b562014-02-26 02:36:06 +00006746enum {
6747 AddressOf,
6748 FunctionPointer,
6749 ArrayPointer
6750};
6751
Richard Trieuc1888e02014-06-28 23:25:37 +00006752// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6753// Returns true when emitting a warning about taking the address of a reference.
6754static bool CheckForReference(Sema &SemaRef, const Expr *E,
6755 PartialDiagnostic PD) {
6756 E = E->IgnoreParenImpCasts();
6757
6758 const FunctionDecl *FD = nullptr;
6759
6760 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6761 if (!DRE->getDecl()->getType()->isReferenceType())
6762 return false;
6763 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6764 if (!M->getMemberDecl()->getType()->isReferenceType())
6765 return false;
6766 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
6767 if (!Call->getCallReturnType()->isReferenceType())
6768 return false;
6769 FD = Call->getDirectCallee();
6770 } else {
6771 return false;
6772 }
6773
6774 SemaRef.Diag(E->getExprLoc(), PD);
6775
6776 // If possible, point to location of function.
6777 if (FD) {
6778 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6779 }
6780
6781 return true;
6782}
6783
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006784// Returns true if the SourceLocation is expanded from any macro body.
6785// Returns false if the SourceLocation is invalid, is from not in a macro
6786// expansion, or is from expanded from a top-level macro argument.
6787static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
6788 if (Loc.isInvalid())
6789 return false;
6790
6791 while (Loc.isMacroID()) {
6792 if (SM.isMacroBodyExpansion(Loc))
6793 return true;
6794 Loc = SM.getImmediateMacroCallerLoc(Loc);
6795 }
6796
6797 return false;
6798}
6799
Richard Trieu3bb8b562014-02-26 02:36:06 +00006800/// \brief Diagnose pointers that are always non-null.
6801/// \param E the expression containing the pointer
6802/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6803/// compared to a null pointer
6804/// \param IsEqual True when the comparison is equal to a null pointer
6805/// \param Range Extra SourceRange to highlight in the diagnostic
6806void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6807 Expr::NullPointerConstantKind NullKind,
6808 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00006809 if (!E)
6810 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006811
6812 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006813 if (E->getExprLoc().isMacroID()) {
6814 const SourceManager &SM = getSourceManager();
6815 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
6816 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00006817 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006818 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006819 E = E->IgnoreImpCasts();
6820
6821 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6822
Richard Trieuf7432752014-06-06 21:39:26 +00006823 if (isa<CXXThisExpr>(E)) {
6824 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6825 : diag::warn_this_bool_conversion;
6826 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6827 return;
6828 }
6829
Richard Trieu3bb8b562014-02-26 02:36:06 +00006830 bool IsAddressOf = false;
6831
6832 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6833 if (UO->getOpcode() != UO_AddrOf)
6834 return;
6835 IsAddressOf = true;
6836 E = UO->getSubExpr();
6837 }
6838
Richard Trieuc1888e02014-06-28 23:25:37 +00006839 if (IsAddressOf) {
6840 unsigned DiagID = IsCompare
6841 ? diag::warn_address_of_reference_null_compare
6842 : diag::warn_address_of_reference_bool_conversion;
6843 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6844 << IsEqual;
6845 if (CheckForReference(*this, E, PD)) {
6846 return;
6847 }
6848 }
6849
Richard Trieu3bb8b562014-02-26 02:36:06 +00006850 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00006851 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006852 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6853 D = R->getDecl();
6854 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6855 D = M->getMemberDecl();
6856 }
6857
6858 // Weak Decls can be null.
6859 if (!D || D->isWeak())
6860 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00006861
6862 // Check for parameter decl with nonnull attribute
6863 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
6864 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
6865 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
6866 unsigned NumArgs = FD->getNumParams();
6867 llvm::SmallBitVector AttrNonNull(NumArgs);
6868 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
6869 if (!NonNull->args_size()) {
6870 AttrNonNull.set(0, NumArgs);
6871 break;
6872 }
6873 for (unsigned Val : NonNull->args()) {
6874 if (Val >= NumArgs)
6875 continue;
6876 AttrNonNull.set(Val);
6877 }
6878 }
6879 if (!AttrNonNull.empty())
6880 for (unsigned i = 0; i < NumArgs; ++i)
Aaron Ballman2521f362014-12-11 19:35:42 +00006881 if (FD->getParamDecl(i) == PV &&
6882 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
Fariborz Jahanianef202d92014-11-18 21:57:54 +00006883 std::string Str;
6884 llvm::raw_string_ostream S(Str);
6885 E->printPretty(S, nullptr, getPrintingPolicy());
6886 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
6887 : diag::warn_cast_nonnull_to_bool;
6888 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
6889 << Range << IsEqual;
6890 return;
6891 }
6892 }
6893 }
6894
Richard Trieu3bb8b562014-02-26 02:36:06 +00006895 QualType T = D->getType();
6896 const bool IsArray = T->isArrayType();
6897 const bool IsFunction = T->isFunctionType();
6898
Richard Trieuc1888e02014-06-28 23:25:37 +00006899 // Address of function is used to silence the function warning.
6900 if (IsAddressOf && IsFunction) {
6901 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006902 }
6903
6904 // Found nothing.
6905 if (!IsAddressOf && !IsFunction && !IsArray)
6906 return;
6907
6908 // Pretty print the expression for the diagnostic.
6909 std::string Str;
6910 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00006911 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00006912
6913 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6914 : diag::warn_impcast_pointer_to_bool;
6915 unsigned DiagType;
6916 if (IsAddressOf)
6917 DiagType = AddressOf;
6918 else if (IsFunction)
6919 DiagType = FunctionPointer;
6920 else if (IsArray)
6921 DiagType = ArrayPointer;
6922 else
6923 llvm_unreachable("Could not determine diagnostic.");
6924 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6925 << Range << IsEqual;
6926
6927 if (!IsFunction)
6928 return;
6929
6930 // Suggest '&' to silence the function warning.
6931 Diag(E->getExprLoc(), diag::note_function_warning_silence)
6932 << FixItHint::CreateInsertion(E->getLocStart(), "&");
6933
6934 // Check to see if '()' fixit should be emitted.
6935 QualType ReturnType;
6936 UnresolvedSet<4> NonTemplateOverloads;
6937 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6938 if (ReturnType.isNull())
6939 return;
6940
6941 if (IsCompare) {
6942 // There are two cases here. If there is null constant, the only suggest
6943 // for a pointer return type. If the null is 0, then suggest if the return
6944 // type is a pointer or an integer type.
6945 if (!ReturnType->isPointerType()) {
6946 if (NullKind == Expr::NPCK_ZeroExpression ||
6947 NullKind == Expr::NPCK_ZeroLiteral) {
6948 if (!ReturnType->isIntegerType())
6949 return;
6950 } else {
6951 return;
6952 }
6953 }
6954 } else { // !IsCompare
6955 // For function to bool, only suggest if the function pointer has bool
6956 // return type.
6957 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6958 return;
6959 }
6960 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006961 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00006962}
6963
6964
John McCallcc7e5bf2010-05-06 08:58:33 +00006965/// Diagnoses "dangerous" implicit conversions within the given
6966/// expression (which is a full expression). Implements -Wconversion
6967/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006968///
6969/// \param CC the "context" location of the implicit conversion, i.e.
6970/// the most location of the syntactic entity requiring the implicit
6971/// conversion
6972void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006973 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00006974 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00006975 return;
6976
6977 // Don't diagnose for value- or type-dependent expressions.
6978 if (E->isTypeDependent() || E->isValueDependent())
6979 return;
6980
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006981 // Check for array bounds violations in cases where the check isn't triggered
6982 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6983 // ArraySubscriptExpr is on the RHS of a variable initialization.
6984 CheckArrayAccess(E);
6985
John McCallacf0ee52010-10-08 02:01:28 +00006986 // This is not the right CC for (e.g.) a variable initialization.
6987 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006988}
6989
Richard Trieu65724892014-11-15 06:37:39 +00006990/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6991/// Input argument E is a logical expression.
6992void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
6993 ::CheckBoolLikeConversion(*this, E, CC);
6994}
6995
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006996/// Diagnose when expression is an integer constant expression and its evaluation
6997/// results in integer overflow
6998void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00006999 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7000 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007001}
7002
Richard Smithc406cb72013-01-17 01:17:56 +00007003namespace {
7004/// \brief Visitor for expressions which looks for unsequenced operations on the
7005/// same object.
7006class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007007 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7008
Richard Smithc406cb72013-01-17 01:17:56 +00007009 /// \brief A tree of sequenced regions within an expression. Two regions are
7010 /// unsequenced if one is an ancestor or a descendent of the other. When we
7011 /// finish processing an expression with sequencing, such as a comma
7012 /// expression, we fold its tree nodes into its parent, since they are
7013 /// unsequenced with respect to nodes we will visit later.
7014 class SequenceTree {
7015 struct Value {
7016 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7017 unsigned Parent : 31;
7018 bool Merged : 1;
7019 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007020 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00007021
7022 public:
7023 /// \brief A region within an expression which may be sequenced with respect
7024 /// to some other region.
7025 class Seq {
7026 explicit Seq(unsigned N) : Index(N) {}
7027 unsigned Index;
7028 friend class SequenceTree;
7029 public:
7030 Seq() : Index(0) {}
7031 };
7032
7033 SequenceTree() { Values.push_back(Value(0)); }
7034 Seq root() const { return Seq(0); }
7035
7036 /// \brief Create a new sequence of operations, which is an unsequenced
7037 /// subset of \p Parent. This sequence of operations is sequenced with
7038 /// respect to other children of \p Parent.
7039 Seq allocate(Seq Parent) {
7040 Values.push_back(Value(Parent.Index));
7041 return Seq(Values.size() - 1);
7042 }
7043
7044 /// \brief Merge a sequence of operations into its parent.
7045 void merge(Seq S) {
7046 Values[S.Index].Merged = true;
7047 }
7048
7049 /// \brief Determine whether two operations are unsequenced. This operation
7050 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7051 /// should have been merged into its parent as appropriate.
7052 bool isUnsequenced(Seq Cur, Seq Old) {
7053 unsigned C = representative(Cur.Index);
7054 unsigned Target = representative(Old.Index);
7055 while (C >= Target) {
7056 if (C == Target)
7057 return true;
7058 C = Values[C].Parent;
7059 }
7060 return false;
7061 }
7062
7063 private:
7064 /// \brief Pick a representative for a sequence.
7065 unsigned representative(unsigned K) {
7066 if (Values[K].Merged)
7067 // Perform path compression as we go.
7068 return Values[K].Parent = representative(Values[K].Parent);
7069 return K;
7070 }
7071 };
7072
7073 /// An object for which we can track unsequenced uses.
7074 typedef NamedDecl *Object;
7075
7076 /// Different flavors of object usage which we track. We only track the
7077 /// least-sequenced usage of each kind.
7078 enum UsageKind {
7079 /// A read of an object. Multiple unsequenced reads are OK.
7080 UK_Use,
7081 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00007082 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00007083 UK_ModAsValue,
7084 /// A modification of an object which is not sequenced before the value
7085 /// computation of the expression, such as n++.
7086 UK_ModAsSideEffect,
7087
7088 UK_Count = UK_ModAsSideEffect + 1
7089 };
7090
7091 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00007092 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00007093 Expr *Use;
7094 SequenceTree::Seq Seq;
7095 };
7096
7097 struct UsageInfo {
7098 UsageInfo() : Diagnosed(false) {}
7099 Usage Uses[UK_Count];
7100 /// Have we issued a diagnostic for this variable already?
7101 bool Diagnosed;
7102 };
7103 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7104
7105 Sema &SemaRef;
7106 /// Sequenced regions within the expression.
7107 SequenceTree Tree;
7108 /// Declaration modifications and references which we have seen.
7109 UsageInfoMap UsageMap;
7110 /// The region we are currently within.
7111 SequenceTree::Seq Region;
7112 /// Filled in with declarations which were modified as a side-effect
7113 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007114 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00007115 /// Expressions to check later. We defer checking these to reduce
7116 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007117 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00007118
7119 /// RAII object wrapping the visitation of a sequenced subexpression of an
7120 /// expression. At the end of this process, the side-effects of the evaluation
7121 /// become sequenced with respect to the value computation of the result, so
7122 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7123 /// UK_ModAsValue.
7124 struct SequencedSubexpression {
7125 SequencedSubexpression(SequenceChecker &Self)
7126 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7127 Self.ModAsSideEffect = &ModAsSideEffect;
7128 }
7129 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00007130 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7131 MI != ME; ++MI) {
7132 UsageInfo &U = Self.UsageMap[MI->first];
7133 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7134 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7135 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00007136 }
7137 Self.ModAsSideEffect = OldModAsSideEffect;
7138 }
7139
7140 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007141 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7142 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00007143 };
7144
Richard Smith40238f02013-06-20 22:21:56 +00007145 /// RAII object wrapping the visitation of a subexpression which we might
7146 /// choose to evaluate as a constant. If any subexpression is evaluated and
7147 /// found to be non-constant, this allows us to suppress the evaluation of
7148 /// the outer expression.
7149 class EvaluationTracker {
7150 public:
7151 EvaluationTracker(SequenceChecker &Self)
7152 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7153 Self.EvalTracker = this;
7154 }
7155 ~EvaluationTracker() {
7156 Self.EvalTracker = Prev;
7157 if (Prev)
7158 Prev->EvalOK &= EvalOK;
7159 }
7160
7161 bool evaluate(const Expr *E, bool &Result) {
7162 if (!EvalOK || E->isValueDependent())
7163 return false;
7164 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7165 return EvalOK;
7166 }
7167
7168 private:
7169 SequenceChecker &Self;
7170 EvaluationTracker *Prev;
7171 bool EvalOK;
7172 } *EvalTracker;
7173
Richard Smithc406cb72013-01-17 01:17:56 +00007174 /// \brief Find the object which is produced by the specified expression,
7175 /// if any.
7176 Object getObject(Expr *E, bool Mod) const {
7177 E = E->IgnoreParenCasts();
7178 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7179 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7180 return getObject(UO->getSubExpr(), Mod);
7181 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7182 if (BO->getOpcode() == BO_Comma)
7183 return getObject(BO->getRHS(), Mod);
7184 if (Mod && BO->isAssignmentOp())
7185 return getObject(BO->getLHS(), Mod);
7186 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7187 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7188 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7189 return ME->getMemberDecl();
7190 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7191 // FIXME: If this is a reference, map through to its value.
7192 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00007193 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00007194 }
7195
7196 /// \brief Note that an object was modified or used by an expression.
7197 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7198 Usage &U = UI.Uses[UK];
7199 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7200 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7201 ModAsSideEffect->push_back(std::make_pair(O, U));
7202 U.Use = Ref;
7203 U.Seq = Region;
7204 }
7205 }
7206 /// \brief Check whether a modification or use conflicts with a prior usage.
7207 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7208 bool IsModMod) {
7209 if (UI.Diagnosed)
7210 return;
7211
7212 const Usage &U = UI.Uses[OtherKind];
7213 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7214 return;
7215
7216 Expr *Mod = U.Use;
7217 Expr *ModOrUse = Ref;
7218 if (OtherKind == UK_Use)
7219 std::swap(Mod, ModOrUse);
7220
7221 SemaRef.Diag(Mod->getExprLoc(),
7222 IsModMod ? diag::warn_unsequenced_mod_mod
7223 : diag::warn_unsequenced_mod_use)
7224 << O << SourceRange(ModOrUse->getExprLoc());
7225 UI.Diagnosed = true;
7226 }
7227
7228 void notePreUse(Object O, Expr *Use) {
7229 UsageInfo &U = UsageMap[O];
7230 // Uses conflict with other modifications.
7231 checkUsage(O, U, Use, UK_ModAsValue, false);
7232 }
7233 void notePostUse(Object O, Expr *Use) {
7234 UsageInfo &U = UsageMap[O];
7235 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7236 addUsage(U, O, Use, UK_Use);
7237 }
7238
7239 void notePreMod(Object O, Expr *Mod) {
7240 UsageInfo &U = UsageMap[O];
7241 // Modifications conflict with other modifications and with uses.
7242 checkUsage(O, U, Mod, UK_ModAsValue, true);
7243 checkUsage(O, U, Mod, UK_Use, false);
7244 }
7245 void notePostMod(Object O, Expr *Use, UsageKind UK) {
7246 UsageInfo &U = UsageMap[O];
7247 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7248 addUsage(U, O, Use, UK);
7249 }
7250
7251public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007252 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00007253 : Base(S.Context), SemaRef(S), Region(Tree.root()),
7254 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007255 Visit(E);
7256 }
7257
7258 void VisitStmt(Stmt *S) {
7259 // Skip all statements which aren't expressions for now.
7260 }
7261
7262 void VisitExpr(Expr *E) {
7263 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00007264 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007265 }
7266
7267 void VisitCastExpr(CastExpr *E) {
7268 Object O = Object();
7269 if (E->getCastKind() == CK_LValueToRValue)
7270 O = getObject(E->getSubExpr(), false);
7271
7272 if (O)
7273 notePreUse(O, E);
7274 VisitExpr(E);
7275 if (O)
7276 notePostUse(O, E);
7277 }
7278
7279 void VisitBinComma(BinaryOperator *BO) {
7280 // C++11 [expr.comma]p1:
7281 // Every value computation and side effect associated with the left
7282 // expression is sequenced before every value computation and side
7283 // effect associated with the right expression.
7284 SequenceTree::Seq LHS = Tree.allocate(Region);
7285 SequenceTree::Seq RHS = Tree.allocate(Region);
7286 SequenceTree::Seq OldRegion = Region;
7287
7288 {
7289 SequencedSubexpression SeqLHS(*this);
7290 Region = LHS;
7291 Visit(BO->getLHS());
7292 }
7293
7294 Region = RHS;
7295 Visit(BO->getRHS());
7296
7297 Region = OldRegion;
7298
7299 // Forget that LHS and RHS are sequenced. They are both unsequenced
7300 // with respect to other stuff.
7301 Tree.merge(LHS);
7302 Tree.merge(RHS);
7303 }
7304
7305 void VisitBinAssign(BinaryOperator *BO) {
7306 // The modification is sequenced after the value computation of the LHS
7307 // and RHS, so check it before inspecting the operands and update the
7308 // map afterwards.
7309 Object O = getObject(BO->getLHS(), true);
7310 if (!O)
7311 return VisitExpr(BO);
7312
7313 notePreMod(O, BO);
7314
7315 // C++11 [expr.ass]p7:
7316 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7317 // only once.
7318 //
7319 // Therefore, for a compound assignment operator, O is considered used
7320 // everywhere except within the evaluation of E1 itself.
7321 if (isa<CompoundAssignOperator>(BO))
7322 notePreUse(O, BO);
7323
7324 Visit(BO->getLHS());
7325
7326 if (isa<CompoundAssignOperator>(BO))
7327 notePostUse(O, BO);
7328
7329 Visit(BO->getRHS());
7330
Richard Smith83e37bee2013-06-26 23:16:51 +00007331 // C++11 [expr.ass]p1:
7332 // the assignment is sequenced [...] before the value computation of the
7333 // assignment expression.
7334 // C11 6.5.16/3 has no such rule.
7335 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7336 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007337 }
7338 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7339 VisitBinAssign(CAO);
7340 }
7341
7342 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7343 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7344 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7345 Object O = getObject(UO->getSubExpr(), true);
7346 if (!O)
7347 return VisitExpr(UO);
7348
7349 notePreMod(O, UO);
7350 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00007351 // C++11 [expr.pre.incr]p1:
7352 // the expression ++x is equivalent to x+=1
7353 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7354 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007355 }
7356
7357 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7358 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7359 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7360 Object O = getObject(UO->getSubExpr(), true);
7361 if (!O)
7362 return VisitExpr(UO);
7363
7364 notePreMod(O, UO);
7365 Visit(UO->getSubExpr());
7366 notePostMod(O, UO, UK_ModAsSideEffect);
7367 }
7368
7369 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7370 void VisitBinLOr(BinaryOperator *BO) {
7371 // The side-effects of the LHS of an '&&' are sequenced before the
7372 // value computation of the RHS, and hence before the value computation
7373 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7374 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00007375 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007376 {
7377 SequencedSubexpression Sequenced(*this);
7378 Visit(BO->getLHS());
7379 }
7380
7381 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007382 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007383 if (!Result)
7384 Visit(BO->getRHS());
7385 } else {
7386 // Check for unsequenced operations in the RHS, treating it as an
7387 // entirely separate evaluation.
7388 //
7389 // FIXME: If there are operations in the RHS which are unsequenced
7390 // with respect to operations outside the RHS, and those operations
7391 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00007392 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007393 }
Richard Smithc406cb72013-01-17 01:17:56 +00007394 }
7395 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00007396 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007397 {
7398 SequencedSubexpression Sequenced(*this);
7399 Visit(BO->getLHS());
7400 }
7401
7402 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007403 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007404 if (Result)
7405 Visit(BO->getRHS());
7406 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00007407 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007408 }
Richard Smithc406cb72013-01-17 01:17:56 +00007409 }
7410
7411 // Only visit the condition, unless we can be sure which subexpression will
7412 // be chosen.
7413 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00007414 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00007415 {
7416 SequencedSubexpression Sequenced(*this);
7417 Visit(CO->getCond());
7418 }
Richard Smithc406cb72013-01-17 01:17:56 +00007419
7420 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007421 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00007422 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007423 else {
Richard Smithd33f5202013-01-17 23:18:09 +00007424 WorkList.push_back(CO->getTrueExpr());
7425 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007426 }
Richard Smithc406cb72013-01-17 01:17:56 +00007427 }
7428
Richard Smithe3dbfe02013-06-30 10:40:20 +00007429 void VisitCallExpr(CallExpr *CE) {
7430 // C++11 [intro.execution]p15:
7431 // When calling a function [...], every value computation and side effect
7432 // associated with any argument expression, or with the postfix expression
7433 // designating the called function, is sequenced before execution of every
7434 // expression or statement in the body of the function [and thus before
7435 // the value computation of its result].
7436 SequencedSubexpression Sequenced(*this);
7437 Base::VisitCallExpr(CE);
7438
7439 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7440 }
7441
Richard Smithc406cb72013-01-17 01:17:56 +00007442 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007443 // This is a call, so all subexpressions are sequenced before the result.
7444 SequencedSubexpression Sequenced(*this);
7445
Richard Smithc406cb72013-01-17 01:17:56 +00007446 if (!CCE->isListInitialization())
7447 return VisitExpr(CCE);
7448
7449 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007450 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007451 SequenceTree::Seq Parent = Region;
7452 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7453 E = CCE->arg_end();
7454 I != E; ++I) {
7455 Region = Tree.allocate(Parent);
7456 Elts.push_back(Region);
7457 Visit(*I);
7458 }
7459
7460 // Forget that the initializers are sequenced.
7461 Region = Parent;
7462 for (unsigned I = 0; I < Elts.size(); ++I)
7463 Tree.merge(Elts[I]);
7464 }
7465
7466 void VisitInitListExpr(InitListExpr *ILE) {
7467 if (!SemaRef.getLangOpts().CPlusPlus11)
7468 return VisitExpr(ILE);
7469
7470 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007471 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007472 SequenceTree::Seq Parent = Region;
7473 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7474 Expr *E = ILE->getInit(I);
7475 if (!E) continue;
7476 Region = Tree.allocate(Parent);
7477 Elts.push_back(Region);
7478 Visit(E);
7479 }
7480
7481 // Forget that the initializers are sequenced.
7482 Region = Parent;
7483 for (unsigned I = 0; I < Elts.size(); ++I)
7484 Tree.merge(Elts[I]);
7485 }
7486};
7487}
7488
7489void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007490 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00007491 WorkList.push_back(E);
7492 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00007493 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00007494 SequenceChecker(*this, Item, WorkList);
7495 }
Richard Smithc406cb72013-01-17 01:17:56 +00007496}
7497
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007498void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7499 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007500 CheckImplicitConversions(E, CheckLoc);
7501 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007502 if (!IsConstexpr && !E->isValueDependent())
7503 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007504}
7505
John McCall1f425642010-11-11 03:21:53 +00007506void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7507 FieldDecl *BitField,
7508 Expr *Init) {
7509 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7510}
7511
Mike Stump0c2ec772010-01-21 03:59:47 +00007512/// CheckParmsForFunctionDef - Check that the parameters of the given
7513/// function are appropriate for the definition of a function. This
7514/// takes care of any checks that cannot be performed on the
7515/// declaration itself, e.g., that the types of each of the function
7516/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00007517bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7518 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00007519 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007520 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00007521 for (; P != PEnd; ++P) {
7522 ParmVarDecl *Param = *P;
7523
Mike Stump0c2ec772010-01-21 03:59:47 +00007524 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7525 // function declarator that is part of a function definition of
7526 // that function shall not have incomplete type.
7527 //
7528 // This is also C++ [dcl.fct]p6.
7529 if (!Param->isInvalidDecl() &&
7530 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007531 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007532 Param->setInvalidDecl();
7533 HasInvalidParm = true;
7534 }
7535
7536 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7537 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00007538 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00007539 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00007540 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007541 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00007542 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00007543
7544 // C99 6.7.5.3p12:
7545 // If the function declarator is not part of a definition of that
7546 // function, parameters may have incomplete type and may use the [*]
7547 // notation in their sequences of declarator specifiers to specify
7548 // variable length array types.
7549 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007550 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00007551 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00007552 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00007553 // information is added for it.
7554 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007555 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00007556 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007557 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00007558 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007559
7560 // MSVC destroys objects passed by value in the callee. Therefore a
7561 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007562 // object's destructor. However, we don't perform any direct access check
7563 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00007564 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7565 .getCXXABI()
7566 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00007567 if (!Param->isInvalidDecl()) {
7568 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7569 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7570 if (!ClassDecl->isInvalidDecl() &&
7571 !ClassDecl->hasIrrelevantDestructor() &&
7572 !ClassDecl->isDependentContext()) {
7573 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7574 MarkFunctionReferenced(Param->getLocation(), Destructor);
7575 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7576 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007577 }
7578 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007579 }
Mike Stump0c2ec772010-01-21 03:59:47 +00007580 }
7581
7582 return HasInvalidParm;
7583}
John McCall2b5c1b22010-08-12 21:44:57 +00007584
7585/// CheckCastAlign - Implements -Wcast-align, which warns when a
7586/// pointer cast increases the alignment requirements.
7587void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7588 // This is actually a lot of work to potentially be doing on every
7589 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007590 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00007591 return;
7592
7593 // Ignore dependent types.
7594 if (T->isDependentType() || Op->getType()->isDependentType())
7595 return;
7596
7597 // Require that the destination be a pointer type.
7598 const PointerType *DestPtr = T->getAs<PointerType>();
7599 if (!DestPtr) return;
7600
7601 // If the destination has alignment 1, we're done.
7602 QualType DestPointee = DestPtr->getPointeeType();
7603 if (DestPointee->isIncompleteType()) return;
7604 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7605 if (DestAlign.isOne()) return;
7606
7607 // Require that the source be a pointer type.
7608 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7609 if (!SrcPtr) return;
7610 QualType SrcPointee = SrcPtr->getPointeeType();
7611
7612 // Whitelist casts from cv void*. We already implicitly
7613 // whitelisted casts to cv void*, since they have alignment 1.
7614 // Also whitelist casts involving incomplete types, which implicitly
7615 // includes 'void'.
7616 if (SrcPointee->isIncompleteType()) return;
7617
7618 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7619 if (SrcAlign >= DestAlign) return;
7620
7621 Diag(TRange.getBegin(), diag::warn_cast_align)
7622 << Op->getType() << T
7623 << static_cast<unsigned>(SrcAlign.getQuantity())
7624 << static_cast<unsigned>(DestAlign.getQuantity())
7625 << TRange << Op->getSourceRange();
7626}
7627
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007628static const Type* getElementType(const Expr *BaseExpr) {
7629 const Type* EltType = BaseExpr->getType().getTypePtr();
7630 if (EltType->isAnyPointerType())
7631 return EltType->getPointeeType().getTypePtr();
7632 else if (EltType->isArrayType())
7633 return EltType->getBaseElementTypeUnsafe();
7634 return EltType;
7635}
7636
Chandler Carruth28389f02011-08-05 09:10:50 +00007637/// \brief Check whether this array fits the idiom of a size-one tail padded
7638/// array member of a struct.
7639///
7640/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7641/// commonly used to emulate flexible arrays in C89 code.
7642static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7643 const NamedDecl *ND) {
7644 if (Size != 1 || !ND) return false;
7645
7646 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7647 if (!FD) return false;
7648
7649 // Don't consider sizes resulting from macro expansions or template argument
7650 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00007651
7652 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007653 while (TInfo) {
7654 TypeLoc TL = TInfo->getTypeLoc();
7655 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007656 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7657 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007658 TInfo = TDL->getTypeSourceInfo();
7659 continue;
7660 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007661 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7662 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007663 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7664 return false;
7665 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007666 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007667 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007668
7669 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007670 if (!RD) return false;
7671 if (RD->isUnion()) return false;
7672 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7673 if (!CRD->isStandardLayout()) return false;
7674 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007675
Benjamin Kramer8c543672011-08-06 03:04:42 +00007676 // See if this is the last field decl in the record.
7677 const Decl *D = FD;
7678 while ((D = D->getNextDeclInContext()))
7679 if (isa<FieldDecl>(D))
7680 return false;
7681 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007682}
7683
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007684void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007685 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007686 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007687 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007688 if (IndexExpr->isValueDependent())
7689 return;
7690
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007691 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007692 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007693 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007694 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007695 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007696 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007697
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007698 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007699 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007700 return;
Richard Smith13f67182011-12-16 19:31:14 +00007701 if (IndexNegated)
7702 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007703
Craig Topperc3ec1492014-05-26 06:22:03 +00007704 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007705 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7706 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007707 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007708 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007709
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007710 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007711 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007712 if (!size.isStrictlyPositive())
7713 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007714
7715 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007716 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007717 // Make sure we're comparing apples to apples when comparing index to size
7718 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7719 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007720 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007721 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007722 if (ptrarith_typesize != array_typesize) {
7723 // There's a cast to a different size type involved
7724 uint64_t ratio = array_typesize / ptrarith_typesize;
7725 // TODO: Be smarter about handling cases where array_typesize is not a
7726 // multiple of ptrarith_typesize
7727 if (ptrarith_typesize * ratio == array_typesize)
7728 size *= llvm::APInt(size.getBitWidth(), ratio);
7729 }
7730 }
7731
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007732 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007733 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007734 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007735 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007736
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007737 // For array subscripting the index must be less than size, but for pointer
7738 // arithmetic also allow the index (offset) to be equal to size since
7739 // computing the next address after the end of the array is legal and
7740 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007741 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007742 return;
7743
7744 // Also don't warn for arrays of size 1 which are members of some
7745 // structure. These are often used to approximate flexible arrays in C89
7746 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007747 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007748 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007749
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007750 // Suppress the warning if the subscript expression (as identified by the
7751 // ']' location) and the index expression are both from macro expansions
7752 // within a system header.
7753 if (ASE) {
7754 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7755 ASE->getRBracketLoc());
7756 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7757 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7758 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007759 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007760 return;
7761 }
7762 }
7763
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007764 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007765 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007766 DiagID = diag::warn_array_index_exceeds_bounds;
7767
7768 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7769 PDiag(DiagID) << index.toString(10, true)
7770 << size.toString(10, true)
7771 << (unsigned)size.getLimitedValue(~0U)
7772 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007773 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007774 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007775 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007776 DiagID = diag::warn_ptr_arith_precedes_bounds;
7777 if (index.isNegative()) index = -index;
7778 }
7779
7780 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7781 PDiag(DiagID) << index.toString(10, true)
7782 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007783 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007784
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007785 if (!ND) {
7786 // Try harder to find a NamedDecl to point at in the note.
7787 while (const ArraySubscriptExpr *ASE =
7788 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7789 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7790 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7791 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7792 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7793 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7794 }
7795
Chandler Carruth1af88f12011-02-17 21:10:52 +00007796 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007797 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7798 PDiag(diag::note_array_index_out_of_bounds)
7799 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007800}
7801
Ted Kremenekdf26df72011-03-01 18:41:00 +00007802void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007803 int AllowOnePastEnd = 0;
7804 while (expr) {
7805 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007806 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007807 case Stmt::ArraySubscriptExprClass: {
7808 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007809 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007810 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007811 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007812 }
7813 case Stmt::UnaryOperatorClass: {
7814 // Only unwrap the * and & unary operators
7815 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7816 expr = UO->getSubExpr();
7817 switch (UO->getOpcode()) {
7818 case UO_AddrOf:
7819 AllowOnePastEnd++;
7820 break;
7821 case UO_Deref:
7822 AllowOnePastEnd--;
7823 break;
7824 default:
7825 return;
7826 }
7827 break;
7828 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007829 case Stmt::ConditionalOperatorClass: {
7830 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7831 if (const Expr *lhs = cond->getLHS())
7832 CheckArrayAccess(lhs);
7833 if (const Expr *rhs = cond->getRHS())
7834 CheckArrayAccess(rhs);
7835 return;
7836 }
7837 default:
7838 return;
7839 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007840 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007841}
John McCall31168b02011-06-15 23:02:42 +00007842
7843//===--- CHECK: Objective-C retain cycles ----------------------------------//
7844
7845namespace {
7846 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00007847 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00007848 VarDecl *Variable;
7849 SourceRange Range;
7850 SourceLocation Loc;
7851 bool Indirect;
7852
7853 void setLocsFrom(Expr *e) {
7854 Loc = e->getExprLoc();
7855 Range = e->getSourceRange();
7856 }
7857 };
7858}
7859
7860/// Consider whether capturing the given variable can possibly lead to
7861/// a retain cycle.
7862static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007863 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007864 // lifetime. In MRR, it's captured strongly if the variable is
7865 // __block and has an appropriate type.
7866 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7867 return false;
7868
7869 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007870 if (ref)
7871 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007872 return true;
7873}
7874
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007875static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007876 while (true) {
7877 e = e->IgnoreParens();
7878 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7879 switch (cast->getCastKind()) {
7880 case CK_BitCast:
7881 case CK_LValueBitCast:
7882 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007883 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007884 e = cast->getSubExpr();
7885 continue;
7886
John McCall31168b02011-06-15 23:02:42 +00007887 default:
7888 return false;
7889 }
7890 }
7891
7892 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7893 ObjCIvarDecl *ivar = ref->getDecl();
7894 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7895 return false;
7896
7897 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007898 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00007899 return false;
7900
7901 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7902 owner.Indirect = true;
7903 return true;
7904 }
7905
7906 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7907 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7908 if (!var) return false;
7909 return considerVariable(var, ref, owner);
7910 }
7911
John McCall31168b02011-06-15 23:02:42 +00007912 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7913 if (member->isArrow()) return false;
7914
7915 // Don't count this as an indirect ownership.
7916 e = member->getBase();
7917 continue;
7918 }
7919
John McCallfe96e0b2011-11-06 09:01:30 +00007920 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7921 // Only pay attention to pseudo-objects on property references.
7922 ObjCPropertyRefExpr *pre
7923 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7924 ->IgnoreParens());
7925 if (!pre) return false;
7926 if (pre->isImplicitProperty()) return false;
7927 ObjCPropertyDecl *property = pre->getExplicitProperty();
7928 if (!property->isRetaining() &&
7929 !(property->getPropertyIvarDecl() &&
7930 property->getPropertyIvarDecl()->getType()
7931 .getObjCLifetime() == Qualifiers::OCL_Strong))
7932 return false;
7933
7934 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007935 if (pre->isSuperReceiver()) {
7936 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7937 if (!owner.Variable)
7938 return false;
7939 owner.Loc = pre->getLocation();
7940 owner.Range = pre->getSourceRange();
7941 return true;
7942 }
John McCallfe96e0b2011-11-06 09:01:30 +00007943 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7944 ->getSourceExpr());
7945 continue;
7946 }
7947
John McCall31168b02011-06-15 23:02:42 +00007948 // Array ivars?
7949
7950 return false;
7951 }
7952}
7953
7954namespace {
7955 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7956 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7957 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007958 Context(Context), Variable(variable), Capturer(nullptr),
7959 VarWillBeReased(false) {}
7960 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00007961 VarDecl *Variable;
7962 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007963 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00007964
7965 void VisitDeclRefExpr(DeclRefExpr *ref) {
7966 if (ref->getDecl() == Variable && !Capturer)
7967 Capturer = ref;
7968 }
7969
John McCall31168b02011-06-15 23:02:42 +00007970 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7971 if (Capturer) return;
7972 Visit(ref->getBase());
7973 if (Capturer && ref->isFreeIvar())
7974 Capturer = ref;
7975 }
7976
7977 void VisitBlockExpr(BlockExpr *block) {
7978 // Look inside nested blocks
7979 if (block->getBlockDecl()->capturesVariable(Variable))
7980 Visit(block->getBlockDecl()->getBody());
7981 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00007982
7983 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7984 if (Capturer) return;
7985 if (OVE->getSourceExpr())
7986 Visit(OVE->getSourceExpr());
7987 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007988 void VisitBinaryOperator(BinaryOperator *BinOp) {
7989 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
7990 return;
7991 Expr *LHS = BinOp->getLHS();
7992 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
7993 if (DRE->getDecl() != Variable)
7994 return;
7995 if (Expr *RHS = BinOp->getRHS()) {
7996 RHS = RHS->IgnoreParenCasts();
7997 llvm::APSInt Value;
7998 VarWillBeReased =
7999 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8000 }
8001 }
8002 }
John McCall31168b02011-06-15 23:02:42 +00008003 };
8004}
8005
8006/// Check whether the given argument is a block which captures a
8007/// variable.
8008static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8009 assert(owner.Variable && owner.Loc.isValid());
8010
8011 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00008012
8013 // Look through [^{...} copy] and Block_copy(^{...}).
8014 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8015 Selector Cmd = ME->getSelector();
8016 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8017 e = ME->getInstanceReceiver();
8018 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00008019 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00008020 e = e->IgnoreParenCasts();
8021 }
8022 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8023 if (CE->getNumArgs() == 1) {
8024 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00008025 if (Fn) {
8026 const IdentifierInfo *FnI = Fn->getIdentifier();
8027 if (FnI && FnI->isStr("_Block_copy")) {
8028 e = CE->getArg(0)->IgnoreParenCasts();
8029 }
8030 }
Jordan Rose67e887c2012-09-17 17:54:30 +00008031 }
8032 }
8033
John McCall31168b02011-06-15 23:02:42 +00008034 BlockExpr *block = dyn_cast<BlockExpr>(e);
8035 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00008036 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00008037
8038 FindCaptureVisitor visitor(S.Context, owner.Variable);
8039 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008040 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00008041}
8042
8043static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8044 RetainCycleOwner &owner) {
8045 assert(capturer);
8046 assert(owner.Variable && owner.Loc.isValid());
8047
8048 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8049 << owner.Variable << capturer->getSourceRange();
8050 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8051 << owner.Indirect << owner.Range;
8052}
8053
8054/// Check for a keyword selector that starts with the word 'add' or
8055/// 'set'.
8056static bool isSetterLikeSelector(Selector sel) {
8057 if (sel.isUnarySelector()) return false;
8058
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008059 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00008060 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008061 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00008062 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008063 else if (str.startswith("add")) {
8064 // Specially whitelist 'addOperationWithBlock:'.
8065 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8066 return false;
8067 str = str.substr(3);
8068 }
John McCall31168b02011-06-15 23:02:42 +00008069 else
8070 return false;
8071
8072 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00008073 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00008074}
8075
8076/// Check a message send to see if it's likely to cause a retain cycle.
8077void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8078 // Only check instance methods whose selector looks like a setter.
8079 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8080 return;
8081
8082 // Try to find a variable that the receiver is strongly owned by.
8083 RetainCycleOwner owner;
8084 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008085 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00008086 return;
8087 } else {
8088 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8089 owner.Variable = getCurMethodDecl()->getSelfDecl();
8090 owner.Loc = msg->getSuperLoc();
8091 owner.Range = msg->getSuperLoc();
8092 }
8093
8094 // Check whether the receiver is captured by any of the arguments.
8095 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
8096 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
8097 return diagnoseRetainCycle(*this, capturer, owner);
8098}
8099
8100/// Check a property assign to see if it's likely to cause a retain cycle.
8101void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
8102 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008103 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00008104 return;
8105
8106 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
8107 diagnoseRetainCycle(*this, capturer, owner);
8108}
8109
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008110void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
8111 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00008112 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008113 return;
8114
8115 // Because we don't have an expression for the variable, we have to set the
8116 // location explicitly here.
8117 Owner.Loc = Var->getLocation();
8118 Owner.Range = Var->getSourceRange();
8119
8120 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8121 diagnoseRetainCycle(*this, Capturer, Owner);
8122}
8123
Ted Kremenek9304da92012-12-21 08:04:28 +00008124static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8125 Expr *RHS, bool isProperty) {
8126 // Check if RHS is an Objective-C object literal, which also can get
8127 // immediately zapped in a weak reference. Note that we explicitly
8128 // allow ObjCStringLiterals, since those are designed to never really die.
8129 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008130
Ted Kremenek64873352012-12-21 22:46:35 +00008131 // This enum needs to match with the 'select' in
8132 // warn_objc_arc_literal_assign (off-by-1).
8133 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8134 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8135 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008136
8137 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00008138 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00008139 << (isProperty ? 0 : 1)
8140 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008141
8142 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00008143}
8144
Ted Kremenekc1f014a2012-12-21 19:45:30 +00008145static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8146 Qualifiers::ObjCLifetime LT,
8147 Expr *RHS, bool isProperty) {
8148 // Strip off any implicit cast added to get to the one ARC-specific.
8149 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8150 if (cast->getCastKind() == CK_ARCConsumeObject) {
8151 S.Diag(Loc, diag::warn_arc_retained_assign)
8152 << (LT == Qualifiers::OCL_ExplicitNone)
8153 << (isProperty ? 0 : 1)
8154 << RHS->getSourceRange();
8155 return true;
8156 }
8157 RHS = cast->getSubExpr();
8158 }
8159
8160 if (LT == Qualifiers::OCL_Weak &&
8161 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8162 return true;
8163
8164 return false;
8165}
8166
Ted Kremenekb36234d2012-12-21 08:04:20 +00008167bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8168 QualType LHS, Expr *RHS) {
8169 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8170
8171 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8172 return false;
8173
8174 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8175 return true;
8176
8177 return false;
8178}
8179
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008180void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8181 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008182 QualType LHSType;
8183 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00008184 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008185 ObjCPropertyRefExpr *PRE
8186 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8187 if (PRE && !PRE->isImplicitProperty()) {
8188 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8189 if (PD)
8190 LHSType = PD->getType();
8191 }
8192
8193 if (LHSType.isNull())
8194 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00008195
8196 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8197
8198 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008199 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00008200 getCurFunction()->markSafeWeakUse(LHS);
8201 }
8202
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008203 if (checkUnsafeAssigns(Loc, LHSType, RHS))
8204 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00008205
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008206 // FIXME. Check for other life times.
8207 if (LT != Qualifiers::OCL_None)
8208 return;
8209
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008210 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008211 if (PRE->isImplicitProperty())
8212 return;
8213 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8214 if (!PD)
8215 return;
8216
Bill Wendling44426052012-12-20 19:22:21 +00008217 unsigned Attributes = PD->getPropertyAttributes();
8218 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008219 // when 'assign' attribute was not explicitly specified
8220 // by user, ignore it and rely on property type itself
8221 // for lifetime info.
8222 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
8223 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
8224 LHSType->isObjCRetainableType())
8225 return;
8226
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008227 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00008228 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008229 Diag(Loc, diag::warn_arc_retained_property_assign)
8230 << RHS->getSourceRange();
8231 return;
8232 }
8233 RHS = cast->getSubExpr();
8234 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008235 }
Bill Wendling44426052012-12-20 19:22:21 +00008236 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00008237 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
8238 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00008239 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008240 }
8241}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008242
8243//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8244
8245namespace {
8246bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8247 SourceLocation StmtLoc,
8248 const NullStmt *Body) {
8249 // Do not warn if the body is a macro that expands to nothing, e.g:
8250 //
8251 // #define CALL(x)
8252 // if (condition)
8253 // CALL(0);
8254 //
8255 if (Body->hasLeadingEmptyMacro())
8256 return false;
8257
8258 // Get line numbers of statement and body.
8259 bool StmtLineInvalid;
8260 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
8261 &StmtLineInvalid);
8262 if (StmtLineInvalid)
8263 return false;
8264
8265 bool BodyLineInvalid;
8266 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8267 &BodyLineInvalid);
8268 if (BodyLineInvalid)
8269 return false;
8270
8271 // Warn if null statement and body are on the same line.
8272 if (StmtLine != BodyLine)
8273 return false;
8274
8275 return true;
8276}
8277} // Unnamed namespace
8278
8279void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8280 const Stmt *Body,
8281 unsigned DiagID) {
8282 // Since this is a syntactic check, don't emit diagnostic for template
8283 // instantiations, this just adds noise.
8284 if (CurrentInstantiationScope)
8285 return;
8286
8287 // The body should be a null statement.
8288 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8289 if (!NBody)
8290 return;
8291
8292 // Do the usual checks.
8293 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8294 return;
8295
8296 Diag(NBody->getSemiLoc(), DiagID);
8297 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8298}
8299
8300void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8301 const Stmt *PossibleBody) {
8302 assert(!CurrentInstantiationScope); // Ensured by caller
8303
8304 SourceLocation StmtLoc;
8305 const Stmt *Body;
8306 unsigned DiagID;
8307 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8308 StmtLoc = FS->getRParenLoc();
8309 Body = FS->getBody();
8310 DiagID = diag::warn_empty_for_body;
8311 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8312 StmtLoc = WS->getCond()->getSourceRange().getEnd();
8313 Body = WS->getBody();
8314 DiagID = diag::warn_empty_while_body;
8315 } else
8316 return; // Neither `for' nor `while'.
8317
8318 // The body should be a null statement.
8319 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8320 if (!NBody)
8321 return;
8322
8323 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008324 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008325 return;
8326
8327 // Do the usual checks.
8328 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8329 return;
8330
8331 // `for(...);' and `while(...);' are popular idioms, so in order to keep
8332 // noise level low, emit diagnostics only if for/while is followed by a
8333 // CompoundStmt, e.g.:
8334 // for (int i = 0; i < n; i++);
8335 // {
8336 // a(i);
8337 // }
8338 // or if for/while is followed by a statement with more indentation
8339 // than for/while itself:
8340 // for (int i = 0; i < n; i++);
8341 // a(i);
8342 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8343 if (!ProbableTypo) {
8344 bool BodyColInvalid;
8345 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8346 PossibleBody->getLocStart(),
8347 &BodyColInvalid);
8348 if (BodyColInvalid)
8349 return;
8350
8351 bool StmtColInvalid;
8352 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8353 S->getLocStart(),
8354 &StmtColInvalid);
8355 if (StmtColInvalid)
8356 return;
8357
8358 if (BodyCol > StmtCol)
8359 ProbableTypo = true;
8360 }
8361
8362 if (ProbableTypo) {
8363 Diag(NBody->getSemiLoc(), DiagID);
8364 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8365 }
8366}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008367
Richard Trieu36d0b2b2015-01-13 02:32:02 +00008368//===--- CHECK: Warn on self move with std::move. -------------------------===//
8369
8370/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
8371void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
8372 SourceLocation OpLoc) {
8373
8374 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
8375 return;
8376
8377 if (!ActiveTemplateInstantiations.empty())
8378 return;
8379
8380 // Strip parens and casts away.
8381 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8382 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8383
8384 // Check for a call expression
8385 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
8386 if (!CE || CE->getNumArgs() != 1)
8387 return;
8388
8389 // Check for a call to std::move
8390 const FunctionDecl *FD = CE->getDirectCallee();
8391 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
8392 !FD->getIdentifier()->isStr("move"))
8393 return;
8394
8395 // Get argument from std::move
8396 RHSExpr = CE->getArg(0);
8397
8398 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8399 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8400
8401 // Two DeclRefExpr's, check that the decls are the same.
8402 if (LHSDeclRef && RHSDeclRef) {
8403 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8404 return;
8405 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8406 RHSDeclRef->getDecl()->getCanonicalDecl())
8407 return;
8408
8409 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8410 << LHSExpr->getSourceRange()
8411 << RHSExpr->getSourceRange();
8412 return;
8413 }
8414
8415 // Member variables require a different approach to check for self moves.
8416 // MemberExpr's are the same if every nested MemberExpr refers to the same
8417 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
8418 // the base Expr's are CXXThisExpr's.
8419 const Expr *LHSBase = LHSExpr;
8420 const Expr *RHSBase = RHSExpr;
8421 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
8422 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
8423 if (!LHSME || !RHSME)
8424 return;
8425
8426 while (LHSME && RHSME) {
8427 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
8428 RHSME->getMemberDecl()->getCanonicalDecl())
8429 return;
8430
8431 LHSBase = LHSME->getBase();
8432 RHSBase = RHSME->getBase();
8433 LHSME = dyn_cast<MemberExpr>(LHSBase);
8434 RHSME = dyn_cast<MemberExpr>(RHSBase);
8435 }
8436
8437 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
8438 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
8439 if (LHSDeclRef && RHSDeclRef) {
8440 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8441 return;
8442 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8443 RHSDeclRef->getDecl()->getCanonicalDecl())
8444 return;
8445
8446 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8447 << LHSExpr->getSourceRange()
8448 << RHSExpr->getSourceRange();
8449 return;
8450 }
8451
8452 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
8453 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8454 << LHSExpr->getSourceRange()
8455 << RHSExpr->getSourceRange();
8456}
8457
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008458//===--- Layout compatibility ----------------------------------------------//
8459
8460namespace {
8461
8462bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8463
8464/// \brief Check if two enumeration types are layout-compatible.
8465bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8466 // C++11 [dcl.enum] p8:
8467 // Two enumeration types are layout-compatible if they have the same
8468 // underlying type.
8469 return ED1->isComplete() && ED2->isComplete() &&
8470 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8471}
8472
8473/// \brief Check if two fields are layout-compatible.
8474bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8475 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8476 return false;
8477
8478 if (Field1->isBitField() != Field2->isBitField())
8479 return false;
8480
8481 if (Field1->isBitField()) {
8482 // Make sure that the bit-fields are the same length.
8483 unsigned Bits1 = Field1->getBitWidthValue(C);
8484 unsigned Bits2 = Field2->getBitWidthValue(C);
8485
8486 if (Bits1 != Bits2)
8487 return false;
8488 }
8489
8490 return true;
8491}
8492
8493/// \brief Check if two standard-layout structs are layout-compatible.
8494/// (C++11 [class.mem] p17)
8495bool isLayoutCompatibleStruct(ASTContext &C,
8496 RecordDecl *RD1,
8497 RecordDecl *RD2) {
8498 // If both records are C++ classes, check that base classes match.
8499 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
8500 // If one of records is a CXXRecordDecl we are in C++ mode,
8501 // thus the other one is a CXXRecordDecl, too.
8502 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
8503 // Check number of base classes.
8504 if (D1CXX->getNumBases() != D2CXX->getNumBases())
8505 return false;
8506
8507 // Check the base classes.
8508 for (CXXRecordDecl::base_class_const_iterator
8509 Base1 = D1CXX->bases_begin(),
8510 BaseEnd1 = D1CXX->bases_end(),
8511 Base2 = D2CXX->bases_begin();
8512 Base1 != BaseEnd1;
8513 ++Base1, ++Base2) {
8514 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
8515 return false;
8516 }
8517 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
8518 // If only RD2 is a C++ class, it should have zero base classes.
8519 if (D2CXX->getNumBases() > 0)
8520 return false;
8521 }
8522
8523 // Check the fields.
8524 RecordDecl::field_iterator Field2 = RD2->field_begin(),
8525 Field2End = RD2->field_end(),
8526 Field1 = RD1->field_begin(),
8527 Field1End = RD1->field_end();
8528 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
8529 if (!isLayoutCompatible(C, *Field1, *Field2))
8530 return false;
8531 }
8532 if (Field1 != Field1End || Field2 != Field2End)
8533 return false;
8534
8535 return true;
8536}
8537
8538/// \brief Check if two standard-layout unions are layout-compatible.
8539/// (C++11 [class.mem] p18)
8540bool isLayoutCompatibleUnion(ASTContext &C,
8541 RecordDecl *RD1,
8542 RecordDecl *RD2) {
8543 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008544 for (auto *Field2 : RD2->fields())
8545 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008546
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008547 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008548 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
8549 I = UnmatchedFields.begin(),
8550 E = UnmatchedFields.end();
8551
8552 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008553 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008554 bool Result = UnmatchedFields.erase(*I);
8555 (void) Result;
8556 assert(Result);
8557 break;
8558 }
8559 }
8560 if (I == E)
8561 return false;
8562 }
8563
8564 return UnmatchedFields.empty();
8565}
8566
8567bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
8568 if (RD1->isUnion() != RD2->isUnion())
8569 return false;
8570
8571 if (RD1->isUnion())
8572 return isLayoutCompatibleUnion(C, RD1, RD2);
8573 else
8574 return isLayoutCompatibleStruct(C, RD1, RD2);
8575}
8576
8577/// \brief Check if two types are layout-compatible in C++11 sense.
8578bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
8579 if (T1.isNull() || T2.isNull())
8580 return false;
8581
8582 // C++11 [basic.types] p11:
8583 // If two types T1 and T2 are the same type, then T1 and T2 are
8584 // layout-compatible types.
8585 if (C.hasSameType(T1, T2))
8586 return true;
8587
8588 T1 = T1.getCanonicalType().getUnqualifiedType();
8589 T2 = T2.getCanonicalType().getUnqualifiedType();
8590
8591 const Type::TypeClass TC1 = T1->getTypeClass();
8592 const Type::TypeClass TC2 = T2->getTypeClass();
8593
8594 if (TC1 != TC2)
8595 return false;
8596
8597 if (TC1 == Type::Enum) {
8598 return isLayoutCompatible(C,
8599 cast<EnumType>(T1)->getDecl(),
8600 cast<EnumType>(T2)->getDecl());
8601 } else if (TC1 == Type::Record) {
8602 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
8603 return false;
8604
8605 return isLayoutCompatible(C,
8606 cast<RecordType>(T1)->getDecl(),
8607 cast<RecordType>(T2)->getDecl());
8608 }
8609
8610 return false;
8611}
8612}
8613
8614//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
8615
8616namespace {
8617/// \brief Given a type tag expression find the type tag itself.
8618///
8619/// \param TypeExpr Type tag expression, as it appears in user's code.
8620///
8621/// \param VD Declaration of an identifier that appears in a type tag.
8622///
8623/// \param MagicValue Type tag magic value.
8624bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
8625 const ValueDecl **VD, uint64_t *MagicValue) {
8626 while(true) {
8627 if (!TypeExpr)
8628 return false;
8629
8630 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
8631
8632 switch (TypeExpr->getStmtClass()) {
8633 case Stmt::UnaryOperatorClass: {
8634 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
8635 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
8636 TypeExpr = UO->getSubExpr();
8637 continue;
8638 }
8639 return false;
8640 }
8641
8642 case Stmt::DeclRefExprClass: {
8643 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
8644 *VD = DRE->getDecl();
8645 return true;
8646 }
8647
8648 case Stmt::IntegerLiteralClass: {
8649 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
8650 llvm::APInt MagicValueAPInt = IL->getValue();
8651 if (MagicValueAPInt.getActiveBits() <= 64) {
8652 *MagicValue = MagicValueAPInt.getZExtValue();
8653 return true;
8654 } else
8655 return false;
8656 }
8657
8658 case Stmt::BinaryConditionalOperatorClass:
8659 case Stmt::ConditionalOperatorClass: {
8660 const AbstractConditionalOperator *ACO =
8661 cast<AbstractConditionalOperator>(TypeExpr);
8662 bool Result;
8663 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
8664 if (Result)
8665 TypeExpr = ACO->getTrueExpr();
8666 else
8667 TypeExpr = ACO->getFalseExpr();
8668 continue;
8669 }
8670 return false;
8671 }
8672
8673 case Stmt::BinaryOperatorClass: {
8674 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
8675 if (BO->getOpcode() == BO_Comma) {
8676 TypeExpr = BO->getRHS();
8677 continue;
8678 }
8679 return false;
8680 }
8681
8682 default:
8683 return false;
8684 }
8685 }
8686}
8687
8688/// \brief Retrieve the C type corresponding to type tag TypeExpr.
8689///
8690/// \param TypeExpr Expression that specifies a type tag.
8691///
8692/// \param MagicValues Registered magic values.
8693///
8694/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
8695/// kind.
8696///
8697/// \param TypeInfo Information about the corresponding C type.
8698///
8699/// \returns true if the corresponding C type was found.
8700bool GetMatchingCType(
8701 const IdentifierInfo *ArgumentKind,
8702 const Expr *TypeExpr, const ASTContext &Ctx,
8703 const llvm::DenseMap<Sema::TypeTagMagicValue,
8704 Sema::TypeTagData> *MagicValues,
8705 bool &FoundWrongKind,
8706 Sema::TypeTagData &TypeInfo) {
8707 FoundWrongKind = false;
8708
8709 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00008710 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008711
8712 uint64_t MagicValue;
8713
8714 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
8715 return false;
8716
8717 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00008718 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008719 if (I->getArgumentKind() != ArgumentKind) {
8720 FoundWrongKind = true;
8721 return false;
8722 }
8723 TypeInfo.Type = I->getMatchingCType();
8724 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
8725 TypeInfo.MustBeNull = I->getMustBeNull();
8726 return true;
8727 }
8728 return false;
8729 }
8730
8731 if (!MagicValues)
8732 return false;
8733
8734 llvm::DenseMap<Sema::TypeTagMagicValue,
8735 Sema::TypeTagData>::const_iterator I =
8736 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
8737 if (I == MagicValues->end())
8738 return false;
8739
8740 TypeInfo = I->second;
8741 return true;
8742}
8743} // unnamed namespace
8744
8745void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8746 uint64_t MagicValue, QualType Type,
8747 bool LayoutCompatible,
8748 bool MustBeNull) {
8749 if (!TypeTagForDatatypeMagicValues)
8750 TypeTagForDatatypeMagicValues.reset(
8751 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
8752
8753 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
8754 (*TypeTagForDatatypeMagicValues)[Magic] =
8755 TypeTagData(Type, LayoutCompatible, MustBeNull);
8756}
8757
8758namespace {
8759bool IsSameCharType(QualType T1, QualType T2) {
8760 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
8761 if (!BT1)
8762 return false;
8763
8764 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8765 if (!BT2)
8766 return false;
8767
8768 BuiltinType::Kind T1Kind = BT1->getKind();
8769 BuiltinType::Kind T2Kind = BT2->getKind();
8770
8771 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
8772 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
8773 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8774 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8775}
8776} // unnamed namespace
8777
8778void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8779 const Expr * const *ExprArgs) {
8780 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8781 bool IsPointerAttr = Attr->getIsPointer();
8782
8783 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8784 bool FoundWrongKind;
8785 TypeTagData TypeInfo;
8786 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8787 TypeTagForDatatypeMagicValues.get(),
8788 FoundWrongKind, TypeInfo)) {
8789 if (FoundWrongKind)
8790 Diag(TypeTagExpr->getExprLoc(),
8791 diag::warn_type_tag_for_datatype_wrong_kind)
8792 << TypeTagExpr->getSourceRange();
8793 return;
8794 }
8795
8796 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8797 if (IsPointerAttr) {
8798 // Skip implicit cast of pointer to `void *' (as a function argument).
8799 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00008800 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00008801 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008802 ArgumentExpr = ICE->getSubExpr();
8803 }
8804 QualType ArgumentType = ArgumentExpr->getType();
8805
8806 // Passing a `void*' pointer shouldn't trigger a warning.
8807 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8808 return;
8809
8810 if (TypeInfo.MustBeNull) {
8811 // Type tag with matching void type requires a null pointer.
8812 if (!ArgumentExpr->isNullPointerConstant(Context,
8813 Expr::NPC_ValueDependentIsNotNull)) {
8814 Diag(ArgumentExpr->getExprLoc(),
8815 diag::warn_type_safety_null_pointer_required)
8816 << ArgumentKind->getName()
8817 << ArgumentExpr->getSourceRange()
8818 << TypeTagExpr->getSourceRange();
8819 }
8820 return;
8821 }
8822
8823 QualType RequiredType = TypeInfo.Type;
8824 if (IsPointerAttr)
8825 RequiredType = Context.getPointerType(RequiredType);
8826
8827 bool mismatch = false;
8828 if (!TypeInfo.LayoutCompatible) {
8829 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8830
8831 // C++11 [basic.fundamental] p1:
8832 // Plain char, signed char, and unsigned char are three distinct types.
8833 //
8834 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8835 // char' depending on the current char signedness mode.
8836 if (mismatch)
8837 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8838 RequiredType->getPointeeType())) ||
8839 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8840 mismatch = false;
8841 } else
8842 if (IsPointerAttr)
8843 mismatch = !isLayoutCompatible(Context,
8844 ArgumentType->getPointeeType(),
8845 RequiredType->getPointeeType());
8846 else
8847 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8848
8849 if (mismatch)
8850 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00008851 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008852 << TypeInfo.LayoutCompatible << RequiredType
8853 << ArgumentExpr->getSourceRange()
8854 << TypeTagExpr->getSourceRange();
8855}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008856