blob: fb11adb45180cf0c87c572770ee4a63b4c513a4b [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000024#include "clang/AST/ExprOpenMP.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000025#include "clang/AST/StmtCXX.h"
26#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000028#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000029#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000030#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000031#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "clang/Sema/Lookup.h"
34#include "clang/Sema/ScopeInfo.h"
35#include "clang/Sema/Sema.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000036#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000037#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "llvm/ADT/SmallString.h"
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +000039#include "llvm/Support/Format.h"
40#include "llvm/Support/Locale.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000041#include "llvm/Support/ConvertUTF.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000042#include "llvm/Support/raw_ostream.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000043#include <limits>
Eugene Zelenko1ced5092016-02-12 22:53:10 +000044
Chris Lattnerb87b1b32007-08-10 20:18:51 +000045using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000046using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000047
Chris Lattnera26fb342009-02-18 17:49:48 +000048SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
49 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000050 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
51 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000052}
53
John McCallbebede42011-02-26 05:39:39 +000054/// Checks that a call expression's argument count is the desired number.
55/// This is useful when doing custom type-checking. Returns true on error.
56static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
57 unsigned argCount = call->getNumArgs();
58 if (argCount == desiredArgCount) return false;
59
60 if (argCount < desiredArgCount)
61 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
62 << 0 /*function call*/ << desiredArgCount << argCount
63 << call->getSourceRange();
64
65 // Highlight all the excess arguments.
66 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
67 call->getArg(argCount - 1)->getLocEnd());
68
69 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
70 << 0 /*function call*/ << desiredArgCount << argCount
71 << call->getArg(1)->getSourceRange();
72}
73
Julien Lerouge4a5b4442012-04-28 17:39:16 +000074/// Check that the first argument to __builtin_annotation is an integer
75/// and the second argument is a non-wide string literal.
76static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
77 if (checkArgCount(S, TheCall, 2))
78 return true;
79
80 // First argument should be an integer.
81 Expr *ValArg = TheCall->getArg(0);
82 QualType Ty = ValArg->getType();
83 if (!Ty->isIntegerType()) {
84 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
85 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000086 return true;
87 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000088
89 // Second argument should be a constant string.
90 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
91 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
92 if (!Literal || !Literal->isAscii()) {
93 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
94 << StrArg->getSourceRange();
95 return true;
96 }
97
98 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000099 return false;
100}
101
Richard Smith6cbd65d2013-07-11 02:27:57 +0000102/// Check that the argument to __builtin_addressof is a glvalue, and set the
103/// result type to the corresponding pointer type.
104static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
105 if (checkArgCount(S, TheCall, 1))
106 return true;
107
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000108 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000109 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
110 if (ResultType.isNull())
111 return true;
112
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000113 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000114 TheCall->setType(ResultType);
115 return false;
116}
117
John McCall03107a42015-10-29 20:48:01 +0000118static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
119 if (checkArgCount(S, TheCall, 3))
120 return true;
121
122 // First two arguments should be integers.
123 for (unsigned I = 0; I < 2; ++I) {
124 Expr *Arg = TheCall->getArg(I);
125 QualType Ty = Arg->getType();
126 if (!Ty->isIntegerType()) {
127 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
128 << Ty << Arg->getSourceRange();
129 return true;
130 }
131 }
132
133 // Third argument should be a pointer to a non-const integer.
134 // IRGen correctly handles volatile, restrict, and address spaces, and
135 // the other qualifiers aren't possible.
136 {
137 Expr *Arg = TheCall->getArg(2);
138 QualType Ty = Arg->getType();
139 const auto *PtrTy = Ty->getAs<PointerType>();
140 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
141 !PtrTy->getPointeeType().isConstQualified())) {
142 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
143 << Ty << Arg->getSourceRange();
144 return true;
145 }
146 }
147
148 return false;
149}
150
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000151static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
152 CallExpr *TheCall, unsigned SizeIdx,
153 unsigned DstSizeIdx) {
154 if (TheCall->getNumArgs() <= SizeIdx ||
155 TheCall->getNumArgs() <= DstSizeIdx)
156 return;
157
158 const Expr *SizeArg = TheCall->getArg(SizeIdx);
159 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
160
161 llvm::APSInt Size, DstSize;
162
163 // find out if both sizes are known at compile time
164 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
165 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
166 return;
167
168 if (Size.ule(DstSize))
169 return;
170
171 // confirmed overflow so generate the diagnostic.
172 IdentifierInfo *FnName = FDecl->getIdentifier();
173 SourceLocation SL = TheCall->getLocStart();
174 SourceRange SR = TheCall->getSourceRange();
175
176 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
177}
178
Peter Collingbournef7706832014-12-12 23:41:25 +0000179static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
180 if (checkArgCount(S, BuiltinCall, 2))
181 return true;
182
183 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
184 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
185 Expr *Call = BuiltinCall->getArg(0);
186 Expr *Chain = BuiltinCall->getArg(1);
187
188 if (Call->getStmtClass() != Stmt::CallExprClass) {
189 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
190 << Call->getSourceRange();
191 return true;
192 }
193
194 auto CE = cast<CallExpr>(Call);
195 if (CE->getCallee()->getType()->isBlockPointerType()) {
196 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
197 << Call->getSourceRange();
198 return true;
199 }
200
201 const Decl *TargetDecl = CE->getCalleeDecl();
202 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
203 if (FD->getBuiltinID()) {
204 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
205 << Call->getSourceRange();
206 return true;
207 }
208
209 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
210 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
211 << Call->getSourceRange();
212 return true;
213 }
214
215 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
216 if (ChainResult.isInvalid())
217 return true;
218 if (!ChainResult.get()->getType()->isPointerType()) {
219 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
220 << Chain->getSourceRange();
221 return true;
222 }
223
David Majnemerced8bdf2015-02-25 17:36:15 +0000224 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000225 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
226 QualType BuiltinTy = S.Context.getFunctionType(
227 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
228 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
229
230 Builtin =
231 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
232
233 BuiltinCall->setType(CE->getType());
234 BuiltinCall->setValueKind(CE->getValueKind());
235 BuiltinCall->setObjectKind(CE->getObjectKind());
236 BuiltinCall->setCallee(Builtin);
237 BuiltinCall->setArg(1, ChainResult.get());
238
239 return false;
240}
241
Reid Kleckner1d59f992015-01-22 01:36:17 +0000242static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
243 Scope::ScopeFlags NeededScopeFlags,
244 unsigned DiagID) {
245 // Scopes aren't available during instantiation. Fortunately, builtin
246 // functions cannot be template args so they cannot be formed through template
247 // instantiation. Therefore checking once during the parse is sufficient.
248 if (!SemaRef.ActiveTemplateInstantiations.empty())
249 return false;
250
251 Scope *S = SemaRef.getCurScope();
252 while (S && !S->isSEHExceptScope())
253 S = S->getParent();
254 if (!S || !(S->getFlags() & NeededScopeFlags)) {
255 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
256 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
257 << DRE->getDecl()->getIdentifier();
258 return true;
259 }
260
261 return false;
262}
263
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000264/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000265static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000266 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000267}
268
269/// Returns true if pipe element type is different from the pointer.
270static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
271 const Expr *Arg0 = Call->getArg(0);
272 // First argument type should always be pipe.
273 if (!Arg0->getType()->isPipeType()) {
274 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000275 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000276 return true;
277 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000278 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000279 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
280 // Validates the access qualifier is compatible with the call.
281 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
282 // read_only and write_only, and assumed to be read_only if no qualifier is
283 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000284 switch (Call->getDirectCallee()->getBuiltinID()) {
285 case Builtin::BIread_pipe:
286 case Builtin::BIreserve_read_pipe:
287 case Builtin::BIcommit_read_pipe:
288 case Builtin::BIwork_group_reserve_read_pipe:
289 case Builtin::BIsub_group_reserve_read_pipe:
290 case Builtin::BIwork_group_commit_read_pipe:
291 case Builtin::BIsub_group_commit_read_pipe:
292 if (!(!AccessQual || AccessQual->isReadOnly())) {
293 S.Diag(Arg0->getLocStart(),
294 diag::err_opencl_builtin_pipe_invalid_access_modifier)
295 << "read_only" << Arg0->getSourceRange();
296 return true;
297 }
298 break;
299 case Builtin::BIwrite_pipe:
300 case Builtin::BIreserve_write_pipe:
301 case Builtin::BIcommit_write_pipe:
302 case Builtin::BIwork_group_reserve_write_pipe:
303 case Builtin::BIsub_group_reserve_write_pipe:
304 case Builtin::BIwork_group_commit_write_pipe:
305 case Builtin::BIsub_group_commit_write_pipe:
306 if (!(AccessQual && AccessQual->isWriteOnly())) {
307 S.Diag(Arg0->getLocStart(),
308 diag::err_opencl_builtin_pipe_invalid_access_modifier)
309 << "write_only" << Arg0->getSourceRange();
310 return true;
311 }
312 break;
313 default:
314 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000315 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000316 return false;
317}
318
319/// Returns true if pipe element type is different from the pointer.
320static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
321 const Expr *Arg0 = Call->getArg(0);
322 const Expr *ArgIdx = Call->getArg(Idx);
323 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000324 const QualType EltTy = PipeTy->getElementType();
325 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000326 // The Idx argument should be a pointer and the type of the pointer and
327 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000328 if (!ArgTy ||
329 !S.Context.hasSameType(
330 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000331 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000332 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000333 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000334 return true;
335 }
336 return false;
337}
338
339// \brief Performs semantic analysis for the read/write_pipe call.
340// \param S Reference to the semantic analyzer.
341// \param Call A pointer to the builtin call.
342// \return True if a semantic error has been found, false otherwise.
343static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000344 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
345 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000346 switch (Call->getNumArgs()) {
347 case 2: {
348 if (checkOpenCLPipeArg(S, Call))
349 return true;
350 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000351 // read/write_pipe(pipe T, T*).
352 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000353 if (checkOpenCLPipePacketType(S, Call, 1))
354 return true;
355 } break;
356
357 case 4: {
358 if (checkOpenCLPipeArg(S, Call))
359 return true;
360 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000361 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
362 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000363 if (!Call->getArg(1)->getType()->isReserveIDT()) {
364 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000365 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000366 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000367 return true;
368 }
369
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000370 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000371 const Expr *Arg2 = Call->getArg(2);
372 if (!Arg2->getType()->isIntegerType() &&
373 !Arg2->getType()->isUnsignedIntegerType()) {
374 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000375 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000376 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000377 return true;
378 }
379
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000380 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000381 if (checkOpenCLPipePacketType(S, Call, 3))
382 return true;
383 } break;
384 default:
385 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000386 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000387 return true;
388 }
389
390 return false;
391}
392
393// \brief Performs a semantic analysis on the {work_group_/sub_group_
394// /_}reserve_{read/write}_pipe
395// \param S Reference to the semantic analyzer.
396// \param Call The call to the builtin function to be analyzed.
397// \return True if a semantic error was found, false otherwise.
398static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
399 if (checkArgCount(S, Call, 2))
400 return true;
401
402 if (checkOpenCLPipeArg(S, Call))
403 return true;
404
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000405 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000406 if (!Call->getArg(1)->getType()->isIntegerType() &&
407 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
408 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000409 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000410 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000411 return true;
412 }
413
414 return false;
415}
416
417// \brief Performs a semantic analysis on {work_group_/sub_group_
418// /_}commit_{read/write}_pipe
419// \param S Reference to the semantic analyzer.
420// \param Call The call to the builtin function to be analyzed.
421// \return True if a semantic error was found, false otherwise.
422static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
423 if (checkArgCount(S, Call, 2))
424 return true;
425
426 if (checkOpenCLPipeArg(S, Call))
427 return true;
428
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000429 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000430 if (!Call->getArg(1)->getType()->isReserveIDT()) {
431 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000432 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000433 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000434 return true;
435 }
436
437 return false;
438}
439
440// \brief Performs a semantic analysis on the call to built-in Pipe
441// Query Functions.
442// \param S Reference to the semantic analyzer.
443// \param Call The call to the builtin function to be analyzed.
444// \return True if a semantic error was found, false otherwise.
445static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
446 if (checkArgCount(S, Call, 1))
447 return true;
448
449 if (!Call->getArg(0)->getType()->isPipeType()) {
450 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000451 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000452 return true;
453 }
454
455 return false;
456}
457
John McCalldadc5752010-08-24 06:29:42 +0000458ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000459Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
460 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000461 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000462
Chris Lattner3be167f2010-10-01 23:23:24 +0000463 // Find out if any arguments are required to be integer constant expressions.
464 unsigned ICEArguments = 0;
465 ASTContext::GetBuiltinTypeError Error;
466 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
467 if (Error != ASTContext::GE_None)
468 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
469
470 // If any arguments are required to be ICE's, check and diagnose.
471 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
472 // Skip arguments not required to be ICE's.
473 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
474
475 llvm::APSInt Result;
476 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
477 return true;
478 ICEArguments &= ~(1 << ArgNo);
479 }
480
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000481 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000482 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000483 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000484 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000485 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000486 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000487 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000488 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000489 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000490 if (SemaBuiltinVAStart(TheCall))
491 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000492 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000493 case Builtin::BI__va_start: {
494 switch (Context.getTargetInfo().getTriple().getArch()) {
495 case llvm::Triple::arm:
496 case llvm::Triple::thumb:
497 if (SemaBuiltinVAStartARM(TheCall))
498 return ExprError();
499 break;
500 default:
501 if (SemaBuiltinVAStart(TheCall))
502 return ExprError();
503 break;
504 }
505 break;
506 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000507 case Builtin::BI__builtin_isgreater:
508 case Builtin::BI__builtin_isgreaterequal:
509 case Builtin::BI__builtin_isless:
510 case Builtin::BI__builtin_islessequal:
511 case Builtin::BI__builtin_islessgreater:
512 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000513 if (SemaBuiltinUnorderedCompare(TheCall))
514 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000515 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000516 case Builtin::BI__builtin_fpclassify:
517 if (SemaBuiltinFPClassification(TheCall, 6))
518 return ExprError();
519 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000520 case Builtin::BI__builtin_isfinite:
521 case Builtin::BI__builtin_isinf:
522 case Builtin::BI__builtin_isinf_sign:
523 case Builtin::BI__builtin_isnan:
524 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000525 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000526 return ExprError();
527 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000528 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000529 return SemaBuiltinShuffleVector(TheCall);
530 // TheCall will be freed by the smart pointer here, but that's fine, since
531 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000532 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000533 if (SemaBuiltinPrefetch(TheCall))
534 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000535 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000536 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000537 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000538 if (SemaBuiltinAssume(TheCall))
539 return ExprError();
540 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000541 case Builtin::BI__builtin_assume_aligned:
542 if (SemaBuiltinAssumeAligned(TheCall))
543 return ExprError();
544 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000545 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000546 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000547 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000548 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000549 case Builtin::BI__builtin_longjmp:
550 if (SemaBuiltinLongjmp(TheCall))
551 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000552 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000553 case Builtin::BI__builtin_setjmp:
554 if (SemaBuiltinSetjmp(TheCall))
555 return ExprError();
556 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000557 case Builtin::BI_setjmp:
558 case Builtin::BI_setjmpex:
559 if (checkArgCount(*this, TheCall, 1))
560 return true;
561 break;
John McCallbebede42011-02-26 05:39:39 +0000562
563 case Builtin::BI__builtin_classify_type:
564 if (checkArgCount(*this, TheCall, 1)) return true;
565 TheCall->setType(Context.IntTy);
566 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000567 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000568 if (checkArgCount(*this, TheCall, 1)) return true;
569 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000570 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000571 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000572 case Builtin::BI__sync_fetch_and_add_1:
573 case Builtin::BI__sync_fetch_and_add_2:
574 case Builtin::BI__sync_fetch_and_add_4:
575 case Builtin::BI__sync_fetch_and_add_8:
576 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000577 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000578 case Builtin::BI__sync_fetch_and_sub_1:
579 case Builtin::BI__sync_fetch_and_sub_2:
580 case Builtin::BI__sync_fetch_and_sub_4:
581 case Builtin::BI__sync_fetch_and_sub_8:
582 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000583 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000584 case Builtin::BI__sync_fetch_and_or_1:
585 case Builtin::BI__sync_fetch_and_or_2:
586 case Builtin::BI__sync_fetch_and_or_4:
587 case Builtin::BI__sync_fetch_and_or_8:
588 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000589 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000590 case Builtin::BI__sync_fetch_and_and_1:
591 case Builtin::BI__sync_fetch_and_and_2:
592 case Builtin::BI__sync_fetch_and_and_4:
593 case Builtin::BI__sync_fetch_and_and_8:
594 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000595 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000596 case Builtin::BI__sync_fetch_and_xor_1:
597 case Builtin::BI__sync_fetch_and_xor_2:
598 case Builtin::BI__sync_fetch_and_xor_4:
599 case Builtin::BI__sync_fetch_and_xor_8:
600 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000601 case Builtin::BI__sync_fetch_and_nand:
602 case Builtin::BI__sync_fetch_and_nand_1:
603 case Builtin::BI__sync_fetch_and_nand_2:
604 case Builtin::BI__sync_fetch_and_nand_4:
605 case Builtin::BI__sync_fetch_and_nand_8:
606 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000607 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000608 case Builtin::BI__sync_add_and_fetch_1:
609 case Builtin::BI__sync_add_and_fetch_2:
610 case Builtin::BI__sync_add_and_fetch_4:
611 case Builtin::BI__sync_add_and_fetch_8:
612 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000613 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000614 case Builtin::BI__sync_sub_and_fetch_1:
615 case Builtin::BI__sync_sub_and_fetch_2:
616 case Builtin::BI__sync_sub_and_fetch_4:
617 case Builtin::BI__sync_sub_and_fetch_8:
618 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000619 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000620 case Builtin::BI__sync_and_and_fetch_1:
621 case Builtin::BI__sync_and_and_fetch_2:
622 case Builtin::BI__sync_and_and_fetch_4:
623 case Builtin::BI__sync_and_and_fetch_8:
624 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000625 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000626 case Builtin::BI__sync_or_and_fetch_1:
627 case Builtin::BI__sync_or_and_fetch_2:
628 case Builtin::BI__sync_or_and_fetch_4:
629 case Builtin::BI__sync_or_and_fetch_8:
630 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000631 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000632 case Builtin::BI__sync_xor_and_fetch_1:
633 case Builtin::BI__sync_xor_and_fetch_2:
634 case Builtin::BI__sync_xor_and_fetch_4:
635 case Builtin::BI__sync_xor_and_fetch_8:
636 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000637 case Builtin::BI__sync_nand_and_fetch:
638 case Builtin::BI__sync_nand_and_fetch_1:
639 case Builtin::BI__sync_nand_and_fetch_2:
640 case Builtin::BI__sync_nand_and_fetch_4:
641 case Builtin::BI__sync_nand_and_fetch_8:
642 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000643 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000644 case Builtin::BI__sync_val_compare_and_swap_1:
645 case Builtin::BI__sync_val_compare_and_swap_2:
646 case Builtin::BI__sync_val_compare_and_swap_4:
647 case Builtin::BI__sync_val_compare_and_swap_8:
648 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000649 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000650 case Builtin::BI__sync_bool_compare_and_swap_1:
651 case Builtin::BI__sync_bool_compare_and_swap_2:
652 case Builtin::BI__sync_bool_compare_and_swap_4:
653 case Builtin::BI__sync_bool_compare_and_swap_8:
654 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000655 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000656 case Builtin::BI__sync_lock_test_and_set_1:
657 case Builtin::BI__sync_lock_test_and_set_2:
658 case Builtin::BI__sync_lock_test_and_set_4:
659 case Builtin::BI__sync_lock_test_and_set_8:
660 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000661 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000662 case Builtin::BI__sync_lock_release_1:
663 case Builtin::BI__sync_lock_release_2:
664 case Builtin::BI__sync_lock_release_4:
665 case Builtin::BI__sync_lock_release_8:
666 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000667 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000668 case Builtin::BI__sync_swap_1:
669 case Builtin::BI__sync_swap_2:
670 case Builtin::BI__sync_swap_4:
671 case Builtin::BI__sync_swap_8:
672 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000673 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000674 case Builtin::BI__builtin_nontemporal_load:
675 case Builtin::BI__builtin_nontemporal_store:
676 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000677#define BUILTIN(ID, TYPE, ATTRS)
678#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
679 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000680 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000681#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000682 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000683 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000684 return ExprError();
685 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000686 case Builtin::BI__builtin_addressof:
687 if (SemaBuiltinAddressof(*this, TheCall))
688 return ExprError();
689 break;
John McCall03107a42015-10-29 20:48:01 +0000690 case Builtin::BI__builtin_add_overflow:
691 case Builtin::BI__builtin_sub_overflow:
692 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000693 if (SemaBuiltinOverflow(*this, TheCall))
694 return ExprError();
695 break;
Richard Smith760520b2014-06-03 23:27:44 +0000696 case Builtin::BI__builtin_operator_new:
697 case Builtin::BI__builtin_operator_delete:
698 if (!getLangOpts().CPlusPlus) {
699 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
700 << (BuiltinID == Builtin::BI__builtin_operator_new
701 ? "__builtin_operator_new"
702 : "__builtin_operator_delete")
703 << "C++";
704 return ExprError();
705 }
706 // CodeGen assumes it can find the global new and delete to call,
707 // so ensure that they are declared.
708 DeclareGlobalNewDelete();
709 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000710
711 // check secure string manipulation functions where overflows
712 // are detectable at compile time
713 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000714 case Builtin::BI__builtin___memmove_chk:
715 case Builtin::BI__builtin___memset_chk:
716 case Builtin::BI__builtin___strlcat_chk:
717 case Builtin::BI__builtin___strlcpy_chk:
718 case Builtin::BI__builtin___strncat_chk:
719 case Builtin::BI__builtin___strncpy_chk:
720 case Builtin::BI__builtin___stpncpy_chk:
721 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
722 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000723 case Builtin::BI__builtin___memccpy_chk:
724 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
725 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000726 case Builtin::BI__builtin___snprintf_chk:
727 case Builtin::BI__builtin___vsnprintf_chk:
728 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
729 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000730 case Builtin::BI__builtin_call_with_static_chain:
731 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
732 return ExprError();
733 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000734 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000735 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000736 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
737 diag::err_seh___except_block))
738 return ExprError();
739 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000740 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000741 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000742 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
743 diag::err_seh___except_filter))
744 return ExprError();
745 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +0000746 case Builtin::BI__GetExceptionInfo:
747 if (checkArgCount(*this, TheCall, 1))
748 return ExprError();
749
750 if (CheckCXXThrowOperand(
751 TheCall->getLocStart(),
752 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
753 TheCall))
754 return ExprError();
755
756 TheCall->setType(Context.VoidPtrTy);
757 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000758 case Builtin::BIread_pipe:
759 case Builtin::BIwrite_pipe:
760 // Since those two functions are declared with var args, we need a semantic
761 // check for the argument.
762 if (SemaBuiltinRWPipe(*this, TheCall))
763 return ExprError();
764 break;
765 case Builtin::BIreserve_read_pipe:
766 case Builtin::BIreserve_write_pipe:
767 case Builtin::BIwork_group_reserve_read_pipe:
768 case Builtin::BIwork_group_reserve_write_pipe:
769 case Builtin::BIsub_group_reserve_read_pipe:
770 case Builtin::BIsub_group_reserve_write_pipe:
771 if (SemaBuiltinReserveRWPipe(*this, TheCall))
772 return ExprError();
773 // Since return type of reserve_read/write_pipe built-in function is
774 // reserve_id_t, which is not defined in the builtin def file , we used int
775 // as return type and need to override the return type of these functions.
776 TheCall->setType(Context.OCLReserveIDTy);
777 break;
778 case Builtin::BIcommit_read_pipe:
779 case Builtin::BIcommit_write_pipe:
780 case Builtin::BIwork_group_commit_read_pipe:
781 case Builtin::BIwork_group_commit_write_pipe:
782 case Builtin::BIsub_group_commit_read_pipe:
783 case Builtin::BIsub_group_commit_write_pipe:
784 if (SemaBuiltinCommitRWPipe(*this, TheCall))
785 return ExprError();
786 break;
787 case Builtin::BIget_pipe_num_packets:
788 case Builtin::BIget_pipe_max_packets:
789 if (SemaBuiltinPipePackets(*this, TheCall))
790 return ExprError();
791 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000792 }
Richard Smith760520b2014-06-03 23:27:44 +0000793
Nate Begeman4904e322010-06-08 02:47:44 +0000794 // Since the target specific builtins for each arch overlap, only check those
795 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +0000796 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000797 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000798 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000799 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000800 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000801 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000802 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
803 return ExprError();
804 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000805 case llvm::Triple::aarch64:
806 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000807 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000808 return ExprError();
809 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000810 case llvm::Triple::mips:
811 case llvm::Triple::mipsel:
812 case llvm::Triple::mips64:
813 case llvm::Triple::mips64el:
814 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
815 return ExprError();
816 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +0000817 case llvm::Triple::systemz:
818 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
819 return ExprError();
820 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000821 case llvm::Triple::x86:
822 case llvm::Triple::x86_64:
823 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
824 return ExprError();
825 break;
Kit Bartone50adcb2015-03-30 19:40:59 +0000826 case llvm::Triple::ppc:
827 case llvm::Triple::ppc64:
828 case llvm::Triple::ppc64le:
829 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
830 return ExprError();
831 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000832 default:
833 break;
834 }
835 }
836
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000837 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000838}
839
Nate Begeman91e1fea2010-06-14 05:21:25 +0000840// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000841static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000842 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000843 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000844 switch (Type.getEltType()) {
845 case NeonTypeFlags::Int8:
846 case NeonTypeFlags::Poly8:
847 return shift ? 7 : (8 << IsQuad) - 1;
848 case NeonTypeFlags::Int16:
849 case NeonTypeFlags::Poly16:
850 return shift ? 15 : (4 << IsQuad) - 1;
851 case NeonTypeFlags::Int32:
852 return shift ? 31 : (2 << IsQuad) - 1;
853 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000854 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000855 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000856 case NeonTypeFlags::Poly128:
857 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000858 case NeonTypeFlags::Float16:
859 assert(!shift && "cannot shift float types!");
860 return (4 << IsQuad) - 1;
861 case NeonTypeFlags::Float32:
862 assert(!shift && "cannot shift float types!");
863 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000864 case NeonTypeFlags::Float64:
865 assert(!shift && "cannot shift float types!");
866 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000867 }
David Blaikie8a40f702012-01-17 06:56:22 +0000868 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000869}
870
Bob Wilsone4d77232011-11-08 05:04:11 +0000871/// getNeonEltType - Return the QualType corresponding to the elements of
872/// the vector type specified by the NeonTypeFlags. This is used to check
873/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000874static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000875 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000876 switch (Flags.getEltType()) {
877 case NeonTypeFlags::Int8:
878 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
879 case NeonTypeFlags::Int16:
880 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
881 case NeonTypeFlags::Int32:
882 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
883 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000884 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000885 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
886 else
887 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
888 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000889 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000890 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000891 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000892 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000893 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +0000894 if (IsInt64Long)
895 return Context.UnsignedLongTy;
896 else
897 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000898 case NeonTypeFlags::Poly128:
899 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000900 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000901 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000902 case NeonTypeFlags::Float32:
903 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000904 case NeonTypeFlags::Float64:
905 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000906 }
David Blaikie8a40f702012-01-17 06:56:22 +0000907 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000908}
909
Tim Northover12670412014-02-19 10:37:05 +0000910bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000911 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000912 uint64_t mask = 0;
913 unsigned TV = 0;
914 int PtrArgNum = -1;
915 bool HasConstPtr = false;
916 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000917#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000918#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000919#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000920 }
921
922 // For NEON intrinsics which are overloaded on vector element type, validate
923 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000924 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000925 if (mask) {
926 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
927 return true;
928
929 TV = Result.getLimitedValue(64);
930 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
931 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000932 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000933 }
934
935 if (PtrArgNum >= 0) {
936 // Check that pointer arguments have the specified type.
937 Expr *Arg = TheCall->getArg(PtrArgNum);
938 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
939 Arg = ICE->getSubExpr();
940 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
941 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000942
Tim Northovera2ee4332014-03-29 15:09:45 +0000943 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000944 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000945 bool IsInt64Long =
946 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
947 QualType EltTy =
948 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000949 if (HasConstPtr)
950 EltTy = EltTy.withConst();
951 QualType LHSTy = Context.getPointerType(EltTy);
952 AssignConvertType ConvTy;
953 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
954 if (RHS.isInvalid())
955 return true;
956 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
957 RHS.get(), AA_Assigning))
958 return true;
959 }
960
961 // For NEON intrinsics which take an immediate value as part of the
962 // instruction, range check them here.
963 unsigned i = 0, l = 0, u = 0;
964 switch (BuiltinID) {
965 default:
966 return false;
Tim Northover12670412014-02-19 10:37:05 +0000967#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000968#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000969#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000970 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000971
Richard Sandiford28940af2014-04-16 08:47:51 +0000972 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000973}
974
Tim Northovera2ee4332014-03-29 15:09:45 +0000975bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
976 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000977 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000978 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000979 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000980 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000981 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000982 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
983 BuiltinID == AArch64::BI__builtin_arm_strex ||
984 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000985 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000986 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000987 BuiltinID == ARM::BI__builtin_arm_ldaex ||
988 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
989 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000990
991 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
992
993 // Ensure that we have the proper number of arguments.
994 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
995 return true;
996
997 // Inspect the pointer argument of the atomic builtin. This should always be
998 // a pointer type, whose element is an integral scalar or pointer type.
999 // Because it is a pointer type, we don't have to worry about any implicit
1000 // casts here.
1001 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1002 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1003 if (PointerArgRes.isInvalid())
1004 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001005 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001006
1007 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1008 if (!pointerType) {
1009 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1010 << PointerArg->getType() << PointerArg->getSourceRange();
1011 return true;
1012 }
1013
1014 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1015 // task is to insert the appropriate casts into the AST. First work out just
1016 // what the appropriate type is.
1017 QualType ValType = pointerType->getPointeeType();
1018 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1019 if (IsLdrex)
1020 AddrType.addConst();
1021
1022 // Issue a warning if the cast is dodgy.
1023 CastKind CastNeeded = CK_NoOp;
1024 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1025 CastNeeded = CK_BitCast;
1026 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1027 << PointerArg->getType()
1028 << Context.getPointerType(AddrType)
1029 << AA_Passing << PointerArg->getSourceRange();
1030 }
1031
1032 // Finally, do the cast and replace the argument with the corrected version.
1033 AddrType = Context.getPointerType(AddrType);
1034 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1035 if (PointerArgRes.isInvalid())
1036 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001037 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001038
1039 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1040
1041 // In general, we allow ints, floats and pointers to be loaded and stored.
1042 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1043 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1044 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1045 << PointerArg->getType() << PointerArg->getSourceRange();
1046 return true;
1047 }
1048
1049 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001050 if (Context.getTypeSize(ValType) > MaxWidth) {
1051 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001052 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1053 << PointerArg->getType() << PointerArg->getSourceRange();
1054 return true;
1055 }
1056
1057 switch (ValType.getObjCLifetime()) {
1058 case Qualifiers::OCL_None:
1059 case Qualifiers::OCL_ExplicitNone:
1060 // okay
1061 break;
1062
1063 case Qualifiers::OCL_Weak:
1064 case Qualifiers::OCL_Strong:
1065 case Qualifiers::OCL_Autoreleasing:
1066 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1067 << ValType << PointerArg->getSourceRange();
1068 return true;
1069 }
1070
Tim Northover6aacd492013-07-16 09:47:53 +00001071 if (IsLdrex) {
1072 TheCall->setType(ValType);
1073 return false;
1074 }
1075
1076 // Initialize the argument to be stored.
1077 ExprResult ValArg = TheCall->getArg(0);
1078 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1079 Context, ValType, /*consume*/ false);
1080 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1081 if (ValArg.isInvalid())
1082 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001083 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001084
1085 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1086 // but the custom checker bypasses all default analysis.
1087 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001088 return false;
1089}
1090
Nate Begeman4904e322010-06-08 02:47:44 +00001091bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +00001092 llvm::APSInt Result;
1093
Tim Northover6aacd492013-07-16 09:47:53 +00001094 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001095 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1096 BuiltinID == ARM::BI__builtin_arm_strex ||
1097 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001098 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001099 }
1100
Yi Kong26d104a2014-08-13 19:18:14 +00001101 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1102 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1103 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1104 }
1105
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001106 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1107 BuiltinID == ARM::BI__builtin_arm_wsr64)
1108 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1109
1110 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1111 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1112 BuiltinID == ARM::BI__builtin_arm_wsr ||
1113 BuiltinID == ARM::BI__builtin_arm_wsrp)
1114 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1115
Tim Northover12670412014-02-19 10:37:05 +00001116 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1117 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001118
Yi Kong4efadfb2014-07-03 16:01:25 +00001119 // For intrinsics which take an immediate value as part of the instruction,
1120 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001121 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001122 switch (BuiltinID) {
1123 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001124 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1125 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001126 case ARM::BI__builtin_arm_vcvtr_f:
1127 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001128 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001129 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001130 case ARM::BI__builtin_arm_isb:
1131 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001132 }
Nate Begemand773fe62010-06-13 04:47:52 +00001133
Nate Begemanf568b072010-08-03 21:32:34 +00001134 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001135 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001136}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001137
Tim Northover573cbee2014-05-24 12:52:07 +00001138bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001139 CallExpr *TheCall) {
1140 llvm::APSInt Result;
1141
Tim Northover573cbee2014-05-24 12:52:07 +00001142 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001143 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1144 BuiltinID == AArch64::BI__builtin_arm_strex ||
1145 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001146 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1147 }
1148
Yi Konga5548432014-08-13 19:18:20 +00001149 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1150 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1151 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1152 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1153 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1154 }
1155
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001156 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1157 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001158 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001159
1160 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1161 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1162 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1163 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1164 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1165
Tim Northovera2ee4332014-03-29 15:09:45 +00001166 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1167 return true;
1168
Yi Kong19a29ac2014-07-17 10:52:06 +00001169 // For intrinsics which take an immediate value as part of the instruction,
1170 // range check them here.
1171 unsigned i = 0, l = 0, u = 0;
1172 switch (BuiltinID) {
1173 default: return false;
1174 case AArch64::BI__builtin_arm_dmb:
1175 case AArch64::BI__builtin_arm_dsb:
1176 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1177 }
1178
Yi Kong19a29ac2014-07-17 10:52:06 +00001179 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001180}
1181
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001182bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1183 unsigned i = 0, l = 0, u = 0;
1184 switch (BuiltinID) {
1185 default: return false;
1186 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1187 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001188 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1189 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1190 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1191 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1192 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001193 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001194
Richard Sandiford28940af2014-04-16 08:47:51 +00001195 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001196}
1197
Kit Bartone50adcb2015-03-30 19:40:59 +00001198bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1199 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001200 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1201 BuiltinID == PPC::BI__builtin_divdeu ||
1202 BuiltinID == PPC::BI__builtin_bpermd;
1203 bool IsTarget64Bit = Context.getTargetInfo()
1204 .getTypeWidth(Context
1205 .getTargetInfo()
1206 .getIntPtrType()) == 64;
1207 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1208 BuiltinID == PPC::BI__builtin_divweu ||
1209 BuiltinID == PPC::BI__builtin_divde ||
1210 BuiltinID == PPC::BI__builtin_divdeu;
1211
1212 if (Is64BitBltin && !IsTarget64Bit)
1213 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1214 << TheCall->getSourceRange();
1215
1216 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1217 (BuiltinID == PPC::BI__builtin_bpermd &&
1218 !Context.getTargetInfo().hasFeature("bpermd")))
1219 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1220 << TheCall->getSourceRange();
1221
Kit Bartone50adcb2015-03-30 19:40:59 +00001222 switch (BuiltinID) {
1223 default: return false;
1224 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1225 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1226 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1227 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1228 case PPC::BI__builtin_tbegin:
1229 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1230 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1231 case PPC::BI__builtin_tabortwc:
1232 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1233 case PPC::BI__builtin_tabortwci:
1234 case PPC::BI__builtin_tabortdci:
1235 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1236 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1237 }
1238 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1239}
1240
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001241bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1242 CallExpr *TheCall) {
1243 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1244 Expr *Arg = TheCall->getArg(0);
1245 llvm::APSInt AbortCode(32);
1246 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1247 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1248 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1249 << Arg->getSourceRange();
1250 }
1251
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001252 // For intrinsics which take an immediate value as part of the instruction,
1253 // range check them here.
1254 unsigned i = 0, l = 0, u = 0;
1255 switch (BuiltinID) {
1256 default: return false;
1257 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1258 case SystemZ::BI__builtin_s390_verimb:
1259 case SystemZ::BI__builtin_s390_verimh:
1260 case SystemZ::BI__builtin_s390_verimf:
1261 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1262 case SystemZ::BI__builtin_s390_vfaeb:
1263 case SystemZ::BI__builtin_s390_vfaeh:
1264 case SystemZ::BI__builtin_s390_vfaef:
1265 case SystemZ::BI__builtin_s390_vfaebs:
1266 case SystemZ::BI__builtin_s390_vfaehs:
1267 case SystemZ::BI__builtin_s390_vfaefs:
1268 case SystemZ::BI__builtin_s390_vfaezb:
1269 case SystemZ::BI__builtin_s390_vfaezh:
1270 case SystemZ::BI__builtin_s390_vfaezf:
1271 case SystemZ::BI__builtin_s390_vfaezbs:
1272 case SystemZ::BI__builtin_s390_vfaezhs:
1273 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1274 case SystemZ::BI__builtin_s390_vfidb:
1275 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1276 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1277 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1278 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1279 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1280 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1281 case SystemZ::BI__builtin_s390_vstrcb:
1282 case SystemZ::BI__builtin_s390_vstrch:
1283 case SystemZ::BI__builtin_s390_vstrcf:
1284 case SystemZ::BI__builtin_s390_vstrczb:
1285 case SystemZ::BI__builtin_s390_vstrczh:
1286 case SystemZ::BI__builtin_s390_vstrczf:
1287 case SystemZ::BI__builtin_s390_vstrcbs:
1288 case SystemZ::BI__builtin_s390_vstrchs:
1289 case SystemZ::BI__builtin_s390_vstrcfs:
1290 case SystemZ::BI__builtin_s390_vstrczbs:
1291 case SystemZ::BI__builtin_s390_vstrczhs:
1292 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1293 }
1294 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001295}
1296
Craig Topper5ba2c502015-11-07 08:08:31 +00001297/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1298/// This checks that the target supports __builtin_cpu_supports and
1299/// that the string argument is constant and valid.
1300static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1301 Expr *Arg = TheCall->getArg(0);
1302
1303 // Check if the argument is a string literal.
1304 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1305 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1306 << Arg->getSourceRange();
1307
1308 // Check the contents of the string.
1309 StringRef Feature =
1310 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1311 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1312 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1313 << Arg->getSourceRange();
1314 return false;
1315}
1316
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001317bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001318 unsigned i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001319 switch (BuiltinID) {
Richard Trieucc3949d2016-02-18 22:34:54 +00001320 default:
1321 return false;
Eric Christopherd9832702015-06-29 21:00:05 +00001322 case X86::BI__builtin_cpu_supports:
Craig Topper5ba2c502015-11-07 08:08:31 +00001323 return SemaBuiltinCpuSupports(*this, TheCall);
Charles Davisc7d5c942015-09-17 20:55:33 +00001324 case X86::BI__builtin_ms_va_start:
1325 return SemaBuiltinMSVAStart(TheCall);
Richard Trieucc3949d2016-02-18 22:34:54 +00001326 case X86::BI_mm_prefetch:
1327 i = 1;
1328 l = 0;
1329 u = 3;
1330 break;
1331 case X86::BI__builtin_ia32_sha1rnds4:
1332 i = 2;
1333 l = 0;
1334 u = 3;
1335 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001336 case X86::BI__builtin_ia32_vpermil2pd:
1337 case X86::BI__builtin_ia32_vpermil2pd256:
1338 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00001339 case X86::BI__builtin_ia32_vpermil2ps256:
1340 i = 3;
1341 l = 0;
1342 u = 3;
1343 break;
Craig Topper95b0d732015-01-25 23:30:05 +00001344 case X86::BI__builtin_ia32_cmpb128_mask:
1345 case X86::BI__builtin_ia32_cmpw128_mask:
1346 case X86::BI__builtin_ia32_cmpd128_mask:
1347 case X86::BI__builtin_ia32_cmpq128_mask:
1348 case X86::BI__builtin_ia32_cmpb256_mask:
1349 case X86::BI__builtin_ia32_cmpw256_mask:
1350 case X86::BI__builtin_ia32_cmpd256_mask:
1351 case X86::BI__builtin_ia32_cmpq256_mask:
1352 case X86::BI__builtin_ia32_cmpb512_mask:
1353 case X86::BI__builtin_ia32_cmpw512_mask:
1354 case X86::BI__builtin_ia32_cmpd512_mask:
1355 case X86::BI__builtin_ia32_cmpq512_mask:
1356 case X86::BI__builtin_ia32_ucmpb128_mask:
1357 case X86::BI__builtin_ia32_ucmpw128_mask:
1358 case X86::BI__builtin_ia32_ucmpd128_mask:
1359 case X86::BI__builtin_ia32_ucmpq128_mask:
1360 case X86::BI__builtin_ia32_ucmpb256_mask:
1361 case X86::BI__builtin_ia32_ucmpw256_mask:
1362 case X86::BI__builtin_ia32_ucmpd256_mask:
1363 case X86::BI__builtin_ia32_ucmpq256_mask:
1364 case X86::BI__builtin_ia32_ucmpb512_mask:
1365 case X86::BI__builtin_ia32_ucmpw512_mask:
1366 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00001367 case X86::BI__builtin_ia32_ucmpq512_mask:
1368 i = 2;
1369 l = 0;
1370 u = 7;
1371 break;
Craig Topper16015252015-01-31 06:31:23 +00001372 case X86::BI__builtin_ia32_roundps:
1373 case X86::BI__builtin_ia32_roundpd:
1374 case X86::BI__builtin_ia32_roundps256:
Richard Trieucc3949d2016-02-18 22:34:54 +00001375 case X86::BI__builtin_ia32_roundpd256:
1376 i = 1;
1377 l = 0;
1378 u = 15;
1379 break;
Craig Topper16015252015-01-31 06:31:23 +00001380 case X86::BI__builtin_ia32_roundss:
Richard Trieucc3949d2016-02-18 22:34:54 +00001381 case X86::BI__builtin_ia32_roundsd:
1382 i = 2;
1383 l = 0;
1384 u = 15;
1385 break;
Craig Topper16015252015-01-31 06:31:23 +00001386 case X86::BI__builtin_ia32_cmpps:
1387 case X86::BI__builtin_ia32_cmpss:
1388 case X86::BI__builtin_ia32_cmppd:
1389 case X86::BI__builtin_ia32_cmpsd:
1390 case X86::BI__builtin_ia32_cmpps256:
1391 case X86::BI__builtin_ia32_cmppd256:
1392 case X86::BI__builtin_ia32_cmpps512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00001393 case X86::BI__builtin_ia32_cmppd512_mask:
1394 i = 2;
1395 l = 0;
1396 u = 31;
1397 break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001398 case X86::BI__builtin_ia32_vpcomub:
1399 case X86::BI__builtin_ia32_vpcomuw:
1400 case X86::BI__builtin_ia32_vpcomud:
1401 case X86::BI__builtin_ia32_vpcomuq:
1402 case X86::BI__builtin_ia32_vpcomb:
1403 case X86::BI__builtin_ia32_vpcomw:
1404 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00001405 case X86::BI__builtin_ia32_vpcomq:
1406 i = 2;
1407 l = 0;
1408 u = 7;
1409 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001410 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001411 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001412}
1413
Richard Smith55ce3522012-06-25 20:30:08 +00001414/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1415/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1416/// Returns true when the format fits the function and the FormatStringInfo has
1417/// been populated.
1418bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1419 FormatStringInfo *FSI) {
1420 FSI->HasVAListArg = Format->getFirstArg() == 0;
1421 FSI->FormatIdx = Format->getFormatIdx() - 1;
1422 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001423
Richard Smith55ce3522012-06-25 20:30:08 +00001424 // The way the format attribute works in GCC, the implicit this argument
1425 // of member functions is counted. However, it doesn't appear in our own
1426 // lists, so decrement format_idx in that case.
1427 if (IsCXXMember) {
1428 if(FSI->FormatIdx == 0)
1429 return false;
1430 --FSI->FormatIdx;
1431 if (FSI->FirstDataArg != 0)
1432 --FSI->FirstDataArg;
1433 }
1434 return true;
1435}
Mike Stump11289f42009-09-09 15:08:12 +00001436
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001437/// Checks if a the given expression evaluates to null.
1438///
1439/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00001440static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001441 // If the expression has non-null type, it doesn't evaluate to null.
1442 if (auto nullability
1443 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1444 if (*nullability == NullabilityKind::NonNull)
1445 return false;
1446 }
1447
Ted Kremeneka146db32014-01-17 06:24:47 +00001448 // As a special case, transparent unions initialized with zero are
1449 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001450 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001451 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1452 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001453 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001454 if (const InitListExpr *ILE =
1455 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001456 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001457 }
1458
1459 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001460 return (!Expr->isValueDependent() &&
1461 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1462 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001463}
1464
1465static void CheckNonNullArgument(Sema &S,
1466 const Expr *ArgExpr,
1467 SourceLocation CallSiteLoc) {
1468 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00001469 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1470 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00001471}
1472
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001473bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1474 FormatStringInfo FSI;
1475 if ((GetFormatStringType(Format) == FST_NSString) &&
1476 getFormatStringInfo(Format, false, &FSI)) {
1477 Idx = FSI.FormatIdx;
1478 return true;
1479 }
1480 return false;
1481}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001482/// \brief Diagnose use of %s directive in an NSString which is being passed
1483/// as formatting string to formatting method.
1484static void
1485DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1486 const NamedDecl *FDecl,
1487 Expr **Args,
1488 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001489 unsigned Idx = 0;
1490 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001491 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1492 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001493 Idx = 2;
1494 Format = true;
1495 }
1496 else
1497 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1498 if (S.GetFormatNSStringIdx(I, Idx)) {
1499 Format = true;
1500 break;
1501 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001502 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001503 if (!Format || NumArgs <= Idx)
1504 return;
1505 const Expr *FormatExpr = Args[Idx];
1506 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1507 FormatExpr = CSCE->getSubExpr();
1508 const StringLiteral *FormatString;
1509 if (const ObjCStringLiteral *OSL =
1510 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1511 FormatString = OSL->getString();
1512 else
1513 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1514 if (!FormatString)
1515 return;
1516 if (S.FormatStringHasSArg(FormatString)) {
1517 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1518 << "%s" << 1 << 1;
1519 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1520 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001521 }
1522}
1523
Douglas Gregorb4866e82015-06-19 18:13:19 +00001524/// Determine whether the given type has a non-null nullability annotation.
1525static bool isNonNullType(ASTContext &ctx, QualType type) {
1526 if (auto nullability = type->getNullability(ctx))
1527 return *nullability == NullabilityKind::NonNull;
1528
1529 return false;
1530}
1531
Ted Kremenek2bc73332014-01-17 06:24:43 +00001532static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001533 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00001534 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00001535 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001536 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001537 assert((FDecl || Proto) && "Need a function declaration or prototype");
1538
Ted Kremenek9aedc152014-01-17 06:24:56 +00001539 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001540 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001541 if (FDecl) {
1542 // Handle the nonnull attribute on the function/method declaration itself.
1543 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1544 if (!NonNull->args_size()) {
1545 // Easy case: all pointer arguments are nonnull.
1546 for (const auto *Arg : Args)
1547 if (S.isValidPointerAttrType(Arg->getType()))
1548 CheckNonNullArgument(S, Arg, CallSiteLoc);
1549 return;
1550 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001551
Douglas Gregorb4866e82015-06-19 18:13:19 +00001552 for (unsigned Val : NonNull->args()) {
1553 if (Val >= Args.size())
1554 continue;
1555 if (NonNullArgs.empty())
1556 NonNullArgs.resize(Args.size());
1557 NonNullArgs.set(Val);
1558 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001559 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001560 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001561
Douglas Gregorb4866e82015-06-19 18:13:19 +00001562 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1563 // Handle the nonnull attribute on the parameters of the
1564 // function/method.
1565 ArrayRef<ParmVarDecl*> parms;
1566 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1567 parms = FD->parameters();
1568 else
1569 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1570
1571 unsigned ParamIndex = 0;
1572 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1573 I != E; ++I, ++ParamIndex) {
1574 const ParmVarDecl *PVD = *I;
1575 if (PVD->hasAttr<NonNullAttr>() ||
1576 isNonNullType(S.Context, PVD->getType())) {
1577 if (NonNullArgs.empty())
1578 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00001579
Douglas Gregorb4866e82015-06-19 18:13:19 +00001580 NonNullArgs.set(ParamIndex);
1581 }
1582 }
1583 } else {
1584 // If we have a non-function, non-method declaration but no
1585 // function prototype, try to dig out the function prototype.
1586 if (!Proto) {
1587 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1588 QualType type = VD->getType().getNonReferenceType();
1589 if (auto pointerType = type->getAs<PointerType>())
1590 type = pointerType->getPointeeType();
1591 else if (auto blockType = type->getAs<BlockPointerType>())
1592 type = blockType->getPointeeType();
1593 // FIXME: data member pointers?
1594
1595 // Dig out the function prototype, if there is one.
1596 Proto = type->getAs<FunctionProtoType>();
1597 }
1598 }
1599
1600 // Fill in non-null argument information from the nullability
1601 // information on the parameter types (if we have them).
1602 if (Proto) {
1603 unsigned Index = 0;
1604 for (auto paramType : Proto->getParamTypes()) {
1605 if (isNonNullType(S.Context, paramType)) {
1606 if (NonNullArgs.empty())
1607 NonNullArgs.resize(Args.size());
1608
1609 NonNullArgs.set(Index);
1610 }
1611
1612 ++Index;
1613 }
1614 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001615 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001616
Douglas Gregorb4866e82015-06-19 18:13:19 +00001617 // Check for non-null arguments.
1618 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1619 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001620 if (NonNullArgs[ArgIndex])
1621 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00001622 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001623}
1624
Richard Smith55ce3522012-06-25 20:30:08 +00001625/// Handles the checks for format strings, non-POD arguments to vararg
1626/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001627void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1628 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00001629 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001630 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001631 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001632 if (CurContext->isDependentContext())
1633 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001634
Ted Kremenekb8176da2010-09-09 04:33:05 +00001635 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001636 llvm::SmallBitVector CheckedVarArgs;
1637 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001638 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001639 // Only create vector if there are format attributes.
1640 CheckedVarArgs.resize(Args.size());
1641
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001642 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001643 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001644 }
Richard Smithd7293d72013-08-05 18:49:43 +00001645 }
Richard Smith55ce3522012-06-25 20:30:08 +00001646
1647 // Refuse POD arguments that weren't caught by the format string
1648 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001649 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001650 unsigned NumParams = Proto ? Proto->getNumParams()
1651 : FDecl && isa<FunctionDecl>(FDecl)
1652 ? cast<FunctionDecl>(FDecl)->getNumParams()
1653 : FDecl && isa<ObjCMethodDecl>(FDecl)
1654 ? cast<ObjCMethodDecl>(FDecl)->param_size()
1655 : 0;
1656
Alp Toker9cacbab2014-01-20 20:26:09 +00001657 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001658 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001659 if (const Expr *Arg = Args[ArgIdx]) {
1660 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1661 checkVariadicArgument(Arg, CallType);
1662 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001663 }
Richard Smithd7293d72013-08-05 18:49:43 +00001664 }
Mike Stump11289f42009-09-09 15:08:12 +00001665
Douglas Gregorb4866e82015-06-19 18:13:19 +00001666 if (FDecl || Proto) {
1667 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001668
Richard Trieu41bc0992013-06-22 00:20:41 +00001669 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001670 if (FDecl) {
1671 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1672 CheckArgumentWithTypeTag(I, Args.data());
1673 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001674 }
Richard Smith55ce3522012-06-25 20:30:08 +00001675}
1676
1677/// CheckConstructorCall - Check a constructor call for correctness and safety
1678/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001679void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1680 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001681 const FunctionProtoType *Proto,
1682 SourceLocation Loc) {
1683 VariadicCallType CallType =
1684 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001685 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1686 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00001687}
1688
1689/// CheckFunctionCall - Check a direct function call for various correctness
1690/// and safety properties not strictly enforced by the C type system.
1691bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1692 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001693 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1694 isa<CXXMethodDecl>(FDecl);
1695 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1696 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001697 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1698 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00001699 Expr** Args = TheCall->getArgs();
1700 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001701 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001702 // If this is a call to a member operator, hide the first argument
1703 // from checkCall.
1704 // FIXME: Our choice of AST representation here is less than ideal.
1705 ++Args;
1706 --NumArgs;
1707 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00001708 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00001709 IsMemberFunction, TheCall->getRParenLoc(),
1710 TheCall->getCallee()->getSourceRange(), CallType);
1711
1712 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1713 // None of the checks below are needed for functions that don't have
1714 // simple names (e.g., C++ conversion functions).
1715 if (!FnInfo)
1716 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001717
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001718 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001719 if (getLangOpts().ObjC1)
1720 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001721
Anna Zaks22122702012-01-17 00:37:07 +00001722 unsigned CMId = FDecl->getMemoryFunctionKind();
1723 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001724 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001725
Anna Zaks201d4892012-01-13 21:52:01 +00001726 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001727 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001728 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001729 else if (CMId == Builtin::BIstrncat)
1730 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001731 else
Anna Zaks22122702012-01-17 00:37:07 +00001732 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001733
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001734 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001735}
1736
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001737bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001738 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001739 VariadicCallType CallType =
1740 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001741
Douglas Gregorb4866e82015-06-19 18:13:19 +00001742 checkCall(Method, nullptr, Args,
1743 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1744 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001745
1746 return false;
1747}
1748
Richard Trieu664c4c62013-06-20 21:03:13 +00001749bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1750 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00001751 QualType Ty;
1752 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001753 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001754 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001755 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001756 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001757 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001758
Douglas Gregorb4866e82015-06-19 18:13:19 +00001759 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
1760 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001761 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001762
Richard Trieu664c4c62013-06-20 21:03:13 +00001763 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001764 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001765 CallType = VariadicDoesNotApply;
1766 } else if (Ty->isBlockPointerType()) {
1767 CallType = VariadicBlock;
1768 } else { // Ty->isFunctionPointerType()
1769 CallType = VariadicFunction;
1770 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001771
Douglas Gregorb4866e82015-06-19 18:13:19 +00001772 checkCall(NDecl, Proto,
1773 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1774 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001775 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001776
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001777 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001778}
1779
Richard Trieu41bc0992013-06-22 00:20:41 +00001780/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1781/// such as function pointers returned from functions.
1782bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001783 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001784 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00001785 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001786 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00001787 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001788 TheCall->getCallee()->getSourceRange(), CallType);
1789
1790 return false;
1791}
1792
Tim Northovere94a34c2014-03-11 10:49:14 +00001793static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00001794 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00001795 return false;
1796
JF Bastiendda2cb12016-04-18 18:01:49 +00001797 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00001798 switch (Op) {
1799 case AtomicExpr::AO__c11_atomic_init:
1800 llvm_unreachable("There is no ordering argument for an init");
1801
1802 case AtomicExpr::AO__c11_atomic_load:
1803 case AtomicExpr::AO__atomic_load_n:
1804 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00001805 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
1806 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00001807
1808 case AtomicExpr::AO__c11_atomic_store:
1809 case AtomicExpr::AO__atomic_store:
1810 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00001811 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
1812 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
1813 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00001814
1815 default:
1816 return true;
1817 }
1818}
1819
Richard Smithfeea8832012-04-12 05:08:17 +00001820ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1821 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001822 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1823 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001824
Richard Smithfeea8832012-04-12 05:08:17 +00001825 // All these operations take one of the following forms:
1826 enum {
1827 // C __c11_atomic_init(A *, C)
1828 Init,
1829 // C __c11_atomic_load(A *, int)
1830 Load,
1831 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00001832 LoadCopy,
1833 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00001834 Copy,
1835 // C __c11_atomic_add(A *, M, int)
1836 Arithmetic,
1837 // C __atomic_exchange_n(A *, CP, int)
1838 Xchg,
1839 // void __atomic_exchange(A *, C *, CP, int)
1840 GNUXchg,
1841 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1842 C11CmpXchg,
1843 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1844 GNUCmpXchg
1845 } Form = Init;
Eric Fiselier8d662442016-03-30 23:39:56 +00001846 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
1847 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00001848 // where:
1849 // C is an appropriate type,
1850 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1851 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1852 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1853 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001854
Gabor Horvath98bd0982015-03-16 09:59:54 +00001855 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1856 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1857 AtomicExpr::AO__atomic_load,
1858 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00001859 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1860 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1861 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1862 Op == AtomicExpr::AO__atomic_store_n ||
1863 Op == AtomicExpr::AO__atomic_exchange_n ||
1864 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1865 bool IsAddSub = false;
1866
1867 switch (Op) {
1868 case AtomicExpr::AO__c11_atomic_init:
1869 Form = Init;
1870 break;
1871
1872 case AtomicExpr::AO__c11_atomic_load:
1873 case AtomicExpr::AO__atomic_load_n:
1874 Form = Load;
1875 break;
1876
Richard Smithfeea8832012-04-12 05:08:17 +00001877 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00001878 Form = LoadCopy;
1879 break;
1880
1881 case AtomicExpr::AO__c11_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00001882 case AtomicExpr::AO__atomic_store:
1883 case AtomicExpr::AO__atomic_store_n:
1884 Form = Copy;
1885 break;
1886
1887 case AtomicExpr::AO__c11_atomic_fetch_add:
1888 case AtomicExpr::AO__c11_atomic_fetch_sub:
1889 case AtomicExpr::AO__atomic_fetch_add:
1890 case AtomicExpr::AO__atomic_fetch_sub:
1891 case AtomicExpr::AO__atomic_add_fetch:
1892 case AtomicExpr::AO__atomic_sub_fetch:
1893 IsAddSub = true;
1894 // Fall through.
1895 case AtomicExpr::AO__c11_atomic_fetch_and:
1896 case AtomicExpr::AO__c11_atomic_fetch_or:
1897 case AtomicExpr::AO__c11_atomic_fetch_xor:
1898 case AtomicExpr::AO__atomic_fetch_and:
1899 case AtomicExpr::AO__atomic_fetch_or:
1900 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001901 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001902 case AtomicExpr::AO__atomic_and_fetch:
1903 case AtomicExpr::AO__atomic_or_fetch:
1904 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001905 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001906 Form = Arithmetic;
1907 break;
1908
1909 case AtomicExpr::AO__c11_atomic_exchange:
1910 case AtomicExpr::AO__atomic_exchange_n:
1911 Form = Xchg;
1912 break;
1913
1914 case AtomicExpr::AO__atomic_exchange:
1915 Form = GNUXchg;
1916 break;
1917
1918 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1919 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1920 Form = C11CmpXchg;
1921 break;
1922
1923 case AtomicExpr::AO__atomic_compare_exchange:
1924 case AtomicExpr::AO__atomic_compare_exchange_n:
1925 Form = GNUCmpXchg;
1926 break;
1927 }
1928
1929 // Check we have the right number of arguments.
1930 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001931 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001932 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001933 << TheCall->getCallee()->getSourceRange();
1934 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001935 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1936 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001937 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001938 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001939 << TheCall->getCallee()->getSourceRange();
1940 return ExprError();
1941 }
1942
Richard Smithfeea8832012-04-12 05:08:17 +00001943 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001944 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001945 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1946 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1947 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001948 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001949 << Ptr->getType() << Ptr->getSourceRange();
1950 return ExprError();
1951 }
1952
Richard Smithfeea8832012-04-12 05:08:17 +00001953 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1954 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1955 QualType ValType = AtomTy; // 'C'
1956 if (IsC11) {
1957 if (!AtomTy->isAtomicType()) {
1958 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1959 << Ptr->getType() << Ptr->getSourceRange();
1960 return ExprError();
1961 }
Richard Smithe00921a2012-09-15 06:09:58 +00001962 if (AtomTy.isConstQualified()) {
1963 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1964 << Ptr->getType() << Ptr->getSourceRange();
1965 return ExprError();
1966 }
Richard Smithfeea8832012-04-12 05:08:17 +00001967 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00001968 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00001969 if (ValType.isConstQualified()) {
1970 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
1971 << Ptr->getType() << Ptr->getSourceRange();
1972 return ExprError();
1973 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001974 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001975
Richard Smithfeea8832012-04-12 05:08:17 +00001976 // For an arithmetic operation, the implied arithmetic must be well-formed.
1977 if (Form == Arithmetic) {
1978 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1979 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1980 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1981 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1982 return ExprError();
1983 }
1984 if (!IsAddSub && !ValType->isIntegerType()) {
1985 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1986 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1987 return ExprError();
1988 }
David Majnemere85cff82015-01-28 05:48:06 +00001989 if (IsC11 && ValType->isPointerType() &&
1990 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1991 diag::err_incomplete_type)) {
1992 return ExprError();
1993 }
Richard Smithfeea8832012-04-12 05:08:17 +00001994 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1995 // For __atomic_*_n operations, the value type must be a scalar integral or
1996 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001997 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001998 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1999 return ExprError();
2000 }
2001
Eli Friedmanaa769812013-09-11 03:49:34 +00002002 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2003 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00002004 // For GNU atomics, require a trivially-copyable type. This is not part of
2005 // the GNU atomics specification, but we enforce it for sanity.
2006 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002007 << Ptr->getType() << Ptr->getSourceRange();
2008 return ExprError();
2009 }
2010
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002011 switch (ValType.getObjCLifetime()) {
2012 case Qualifiers::OCL_None:
2013 case Qualifiers::OCL_ExplicitNone:
2014 // okay
2015 break;
2016
2017 case Qualifiers::OCL_Weak:
2018 case Qualifiers::OCL_Strong:
2019 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002020 // FIXME: Can this happen? By this point, ValType should be known
2021 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002022 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2023 << ValType << Ptr->getSourceRange();
2024 return ExprError();
2025 }
2026
David Majnemerc6eb6502015-06-03 00:26:35 +00002027 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2028 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00002029 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00002030 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00002031 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002032 QualType ResultType = ValType;
Eric Fiselier8d662442016-03-30 23:39:56 +00002033 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002034 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002035 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002036 ResultType = Context.BoolTy;
2037
Richard Smithfeea8832012-04-12 05:08:17 +00002038 // The type of a parameter passed 'by value'. In the GNU atomics, such
2039 // arguments are actually passed as pointers.
2040 QualType ByValType = ValType; // 'CP'
2041 if (!IsC11 && !IsN)
2042 ByValType = Ptr->getType();
2043
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002044 // The first argument --- the pointer --- has a fixed type; we
2045 // deduce the types of the rest of the arguments accordingly. Walk
2046 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002047 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002048 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002049 if (i < NumVals[Form] + 1) {
2050 switch (i) {
2051 case 1:
2052 // The second argument is the non-atomic operand. For arithmetic, this
2053 // is always passed by value, and for a compare_exchange it is always
2054 // passed by address. For the rest, GNU uses by-address and C11 uses
2055 // by-value.
2056 assert(Form != Load);
2057 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2058 Ty = ValType;
2059 else if (Form == Copy || Form == Xchg)
2060 Ty = ByValType;
2061 else if (Form == Arithmetic)
2062 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002063 else {
2064 Expr *ValArg = TheCall->getArg(i);
2065 unsigned AS = 0;
2066 // Keep address space of non-atomic pointer type.
2067 if (const PointerType *PtrTy =
2068 ValArg->getType()->getAs<PointerType>()) {
2069 AS = PtrTy->getPointeeType().getAddressSpace();
2070 }
2071 Ty = Context.getPointerType(
2072 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2073 }
Richard Smithfeea8832012-04-12 05:08:17 +00002074 break;
2075 case 2:
2076 // The third argument to compare_exchange / GNU exchange is a
2077 // (pointer to a) desired value.
2078 Ty = ByValType;
2079 break;
2080 case 3:
2081 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2082 Ty = Context.BoolTy;
2083 break;
2084 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002085 } else {
2086 // The order(s) are always converted to int.
2087 Ty = Context.IntTy;
2088 }
Richard Smithfeea8832012-04-12 05:08:17 +00002089
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002090 InitializedEntity Entity =
2091 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002092 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002093 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2094 if (Arg.isInvalid())
2095 return true;
2096 TheCall->setArg(i, Arg.get());
2097 }
2098
Richard Smithfeea8832012-04-12 05:08:17 +00002099 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002100 SmallVector<Expr*, 5> SubExprs;
2101 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002102 switch (Form) {
2103 case Init:
2104 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002105 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002106 break;
2107 case Load:
2108 SubExprs.push_back(TheCall->getArg(1)); // Order
2109 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00002110 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00002111 case Copy:
2112 case Arithmetic:
2113 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002114 SubExprs.push_back(TheCall->getArg(2)); // Order
2115 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002116 break;
2117 case GNUXchg:
2118 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2119 SubExprs.push_back(TheCall->getArg(3)); // Order
2120 SubExprs.push_back(TheCall->getArg(1)); // Val1
2121 SubExprs.push_back(TheCall->getArg(2)); // Val2
2122 break;
2123 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002124 SubExprs.push_back(TheCall->getArg(3)); // Order
2125 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002126 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002127 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002128 break;
2129 case GNUCmpXchg:
2130 SubExprs.push_back(TheCall->getArg(4)); // Order
2131 SubExprs.push_back(TheCall->getArg(1)); // Val1
2132 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2133 SubExprs.push_back(TheCall->getArg(2)); // Val2
2134 SubExprs.push_back(TheCall->getArg(3)); // Weak
2135 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002136 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002137
2138 if (SubExprs.size() >= 2 && Form != Init) {
2139 llvm::APSInt Result(32);
2140 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2141 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002142 Diag(SubExprs[1]->getLocStart(),
2143 diag::warn_atomic_op_has_invalid_memory_order)
2144 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002145 }
2146
Fariborz Jahanian615de762013-05-28 17:37:39 +00002147 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2148 SubExprs, ResultType, Op,
2149 TheCall->getRParenLoc());
2150
2151 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2152 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2153 Context.AtomicUsesUnsupportedLibcall(AE))
2154 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2155 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002156
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002157 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002158}
2159
John McCall29ad95b2011-08-27 01:09:30 +00002160/// checkBuiltinArgument - Given a call to a builtin function, perform
2161/// normal type-checking on the given argument, updating the call in
2162/// place. This is useful when a builtin function requires custom
2163/// type-checking for some of its arguments but not necessarily all of
2164/// them.
2165///
2166/// Returns true on error.
2167static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2168 FunctionDecl *Fn = E->getDirectCallee();
2169 assert(Fn && "builtin call without direct callee!");
2170
2171 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2172 InitializedEntity Entity =
2173 InitializedEntity::InitializeParameter(S.Context, Param);
2174
2175 ExprResult Arg = E->getArg(0);
2176 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2177 if (Arg.isInvalid())
2178 return true;
2179
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002180 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00002181 return false;
2182}
2183
Chris Lattnerdc046542009-05-08 06:58:22 +00002184/// SemaBuiltinAtomicOverloaded - We have a call to a function like
2185/// __sync_fetch_and_add, which is an overloaded function based on the pointer
2186/// type of its first argument. The main ActOnCallExpr routines have already
2187/// promoted the types of arguments because all of these calls are prototyped as
2188/// void(...).
2189///
2190/// This function goes through and does final semantic checking for these
2191/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00002192ExprResult
2193Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002194 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00002195 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2196 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2197
2198 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002199 if (TheCall->getNumArgs() < 1) {
2200 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2201 << 0 << 1 << TheCall->getNumArgs()
2202 << TheCall->getCallee()->getSourceRange();
2203 return ExprError();
2204 }
Mike Stump11289f42009-09-09 15:08:12 +00002205
Chris Lattnerdc046542009-05-08 06:58:22 +00002206 // Inspect the first argument of the atomic builtin. This should always be
2207 // a pointer type, whose element is an integral scalar or pointer type.
2208 // Because it is a pointer type, we don't have to worry about any implicit
2209 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002210 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00002211 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00002212 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
2213 if (FirstArgResult.isInvalid())
2214 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002215 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00002216 TheCall->setArg(0, FirstArg);
2217
John McCall31168b02011-06-15 23:02:42 +00002218 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
2219 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002220 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2221 << FirstArg->getType() << FirstArg->getSourceRange();
2222 return ExprError();
2223 }
Mike Stump11289f42009-09-09 15:08:12 +00002224
John McCall31168b02011-06-15 23:02:42 +00002225 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00002226 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002227 !ValType->isBlockPointerType()) {
2228 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
2229 << FirstArg->getType() << FirstArg->getSourceRange();
2230 return ExprError();
2231 }
Chris Lattnerdc046542009-05-08 06:58:22 +00002232
John McCall31168b02011-06-15 23:02:42 +00002233 switch (ValType.getObjCLifetime()) {
2234 case Qualifiers::OCL_None:
2235 case Qualifiers::OCL_ExplicitNone:
2236 // okay
2237 break;
2238
2239 case Qualifiers::OCL_Weak:
2240 case Qualifiers::OCL_Strong:
2241 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002242 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00002243 << ValType << FirstArg->getSourceRange();
2244 return ExprError();
2245 }
2246
John McCallb50451a2011-10-05 07:41:44 +00002247 // Strip any qualifiers off ValType.
2248 ValType = ValType.getUnqualifiedType();
2249
Chandler Carruth3973af72010-07-18 20:54:12 +00002250 // The majority of builtins return a value, but a few have special return
2251 // types, so allow them to override appropriately below.
2252 QualType ResultType = ValType;
2253
Chris Lattnerdc046542009-05-08 06:58:22 +00002254 // We need to figure out which concrete builtin this maps onto. For example,
2255 // __sync_fetch_and_add with a 2 byte object turns into
2256 // __sync_fetch_and_add_2.
2257#define BUILTIN_ROW(x) \
2258 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2259 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00002260
Chris Lattnerdc046542009-05-08 06:58:22 +00002261 static const unsigned BuiltinIndices[][5] = {
2262 BUILTIN_ROW(__sync_fetch_and_add),
2263 BUILTIN_ROW(__sync_fetch_and_sub),
2264 BUILTIN_ROW(__sync_fetch_and_or),
2265 BUILTIN_ROW(__sync_fetch_and_and),
2266 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00002267 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00002268
Chris Lattnerdc046542009-05-08 06:58:22 +00002269 BUILTIN_ROW(__sync_add_and_fetch),
2270 BUILTIN_ROW(__sync_sub_and_fetch),
2271 BUILTIN_ROW(__sync_and_and_fetch),
2272 BUILTIN_ROW(__sync_or_and_fetch),
2273 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00002274 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00002275
Chris Lattnerdc046542009-05-08 06:58:22 +00002276 BUILTIN_ROW(__sync_val_compare_and_swap),
2277 BUILTIN_ROW(__sync_bool_compare_and_swap),
2278 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00002279 BUILTIN_ROW(__sync_lock_release),
2280 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00002281 };
Mike Stump11289f42009-09-09 15:08:12 +00002282#undef BUILTIN_ROW
2283
Chris Lattnerdc046542009-05-08 06:58:22 +00002284 // Determine the index of the size.
2285 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00002286 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00002287 case 1: SizeIndex = 0; break;
2288 case 2: SizeIndex = 1; break;
2289 case 4: SizeIndex = 2; break;
2290 case 8: SizeIndex = 3; break;
2291 case 16: SizeIndex = 4; break;
2292 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002293 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2294 << FirstArg->getType() << FirstArg->getSourceRange();
2295 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00002296 }
Mike Stump11289f42009-09-09 15:08:12 +00002297
Chris Lattnerdc046542009-05-08 06:58:22 +00002298 // Each of these builtins has one pointer argument, followed by some number of
2299 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2300 // that we ignore. Find out which row of BuiltinIndices to read from as well
2301 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002302 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00002303 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00002304 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00002305 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00002306 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00002307 case Builtin::BI__sync_fetch_and_add:
2308 case Builtin::BI__sync_fetch_and_add_1:
2309 case Builtin::BI__sync_fetch_and_add_2:
2310 case Builtin::BI__sync_fetch_and_add_4:
2311 case Builtin::BI__sync_fetch_and_add_8:
2312 case Builtin::BI__sync_fetch_and_add_16:
2313 BuiltinIndex = 0;
2314 break;
2315
2316 case Builtin::BI__sync_fetch_and_sub:
2317 case Builtin::BI__sync_fetch_and_sub_1:
2318 case Builtin::BI__sync_fetch_and_sub_2:
2319 case Builtin::BI__sync_fetch_and_sub_4:
2320 case Builtin::BI__sync_fetch_and_sub_8:
2321 case Builtin::BI__sync_fetch_and_sub_16:
2322 BuiltinIndex = 1;
2323 break;
2324
2325 case Builtin::BI__sync_fetch_and_or:
2326 case Builtin::BI__sync_fetch_and_or_1:
2327 case Builtin::BI__sync_fetch_and_or_2:
2328 case Builtin::BI__sync_fetch_and_or_4:
2329 case Builtin::BI__sync_fetch_and_or_8:
2330 case Builtin::BI__sync_fetch_and_or_16:
2331 BuiltinIndex = 2;
2332 break;
2333
2334 case Builtin::BI__sync_fetch_and_and:
2335 case Builtin::BI__sync_fetch_and_and_1:
2336 case Builtin::BI__sync_fetch_and_and_2:
2337 case Builtin::BI__sync_fetch_and_and_4:
2338 case Builtin::BI__sync_fetch_and_and_8:
2339 case Builtin::BI__sync_fetch_and_and_16:
2340 BuiltinIndex = 3;
2341 break;
Mike Stump11289f42009-09-09 15:08:12 +00002342
Douglas Gregor73722482011-11-28 16:30:08 +00002343 case Builtin::BI__sync_fetch_and_xor:
2344 case Builtin::BI__sync_fetch_and_xor_1:
2345 case Builtin::BI__sync_fetch_and_xor_2:
2346 case Builtin::BI__sync_fetch_and_xor_4:
2347 case Builtin::BI__sync_fetch_and_xor_8:
2348 case Builtin::BI__sync_fetch_and_xor_16:
2349 BuiltinIndex = 4;
2350 break;
2351
Hal Finkeld2208b52014-10-02 20:53:50 +00002352 case Builtin::BI__sync_fetch_and_nand:
2353 case Builtin::BI__sync_fetch_and_nand_1:
2354 case Builtin::BI__sync_fetch_and_nand_2:
2355 case Builtin::BI__sync_fetch_and_nand_4:
2356 case Builtin::BI__sync_fetch_and_nand_8:
2357 case Builtin::BI__sync_fetch_and_nand_16:
2358 BuiltinIndex = 5;
2359 WarnAboutSemanticsChange = true;
2360 break;
2361
Douglas Gregor73722482011-11-28 16:30:08 +00002362 case Builtin::BI__sync_add_and_fetch:
2363 case Builtin::BI__sync_add_and_fetch_1:
2364 case Builtin::BI__sync_add_and_fetch_2:
2365 case Builtin::BI__sync_add_and_fetch_4:
2366 case Builtin::BI__sync_add_and_fetch_8:
2367 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002368 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002369 break;
2370
2371 case Builtin::BI__sync_sub_and_fetch:
2372 case Builtin::BI__sync_sub_and_fetch_1:
2373 case Builtin::BI__sync_sub_and_fetch_2:
2374 case Builtin::BI__sync_sub_and_fetch_4:
2375 case Builtin::BI__sync_sub_and_fetch_8:
2376 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002377 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002378 break;
2379
2380 case Builtin::BI__sync_and_and_fetch:
2381 case Builtin::BI__sync_and_and_fetch_1:
2382 case Builtin::BI__sync_and_and_fetch_2:
2383 case Builtin::BI__sync_and_and_fetch_4:
2384 case Builtin::BI__sync_and_and_fetch_8:
2385 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002386 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002387 break;
2388
2389 case Builtin::BI__sync_or_and_fetch:
2390 case Builtin::BI__sync_or_and_fetch_1:
2391 case Builtin::BI__sync_or_and_fetch_2:
2392 case Builtin::BI__sync_or_and_fetch_4:
2393 case Builtin::BI__sync_or_and_fetch_8:
2394 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002395 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002396 break;
2397
2398 case Builtin::BI__sync_xor_and_fetch:
2399 case Builtin::BI__sync_xor_and_fetch_1:
2400 case Builtin::BI__sync_xor_and_fetch_2:
2401 case Builtin::BI__sync_xor_and_fetch_4:
2402 case Builtin::BI__sync_xor_and_fetch_8:
2403 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002404 BuiltinIndex = 10;
2405 break;
2406
2407 case Builtin::BI__sync_nand_and_fetch:
2408 case Builtin::BI__sync_nand_and_fetch_1:
2409 case Builtin::BI__sync_nand_and_fetch_2:
2410 case Builtin::BI__sync_nand_and_fetch_4:
2411 case Builtin::BI__sync_nand_and_fetch_8:
2412 case Builtin::BI__sync_nand_and_fetch_16:
2413 BuiltinIndex = 11;
2414 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002415 break;
Mike Stump11289f42009-09-09 15:08:12 +00002416
Chris Lattnerdc046542009-05-08 06:58:22 +00002417 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002418 case Builtin::BI__sync_val_compare_and_swap_1:
2419 case Builtin::BI__sync_val_compare_and_swap_2:
2420 case Builtin::BI__sync_val_compare_and_swap_4:
2421 case Builtin::BI__sync_val_compare_and_swap_8:
2422 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002423 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002424 NumFixed = 2;
2425 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002426
Chris Lattnerdc046542009-05-08 06:58:22 +00002427 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002428 case Builtin::BI__sync_bool_compare_and_swap_1:
2429 case Builtin::BI__sync_bool_compare_and_swap_2:
2430 case Builtin::BI__sync_bool_compare_and_swap_4:
2431 case Builtin::BI__sync_bool_compare_and_swap_8:
2432 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002433 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002434 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002435 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002436 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002437
2438 case Builtin::BI__sync_lock_test_and_set:
2439 case Builtin::BI__sync_lock_test_and_set_1:
2440 case Builtin::BI__sync_lock_test_and_set_2:
2441 case Builtin::BI__sync_lock_test_and_set_4:
2442 case Builtin::BI__sync_lock_test_and_set_8:
2443 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002444 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002445 break;
2446
Chris Lattnerdc046542009-05-08 06:58:22 +00002447 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002448 case Builtin::BI__sync_lock_release_1:
2449 case Builtin::BI__sync_lock_release_2:
2450 case Builtin::BI__sync_lock_release_4:
2451 case Builtin::BI__sync_lock_release_8:
2452 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002453 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002454 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002455 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002456 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002457
2458 case Builtin::BI__sync_swap:
2459 case Builtin::BI__sync_swap_1:
2460 case Builtin::BI__sync_swap_2:
2461 case Builtin::BI__sync_swap_4:
2462 case Builtin::BI__sync_swap_8:
2463 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002464 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002465 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002466 }
Mike Stump11289f42009-09-09 15:08:12 +00002467
Chris Lattnerdc046542009-05-08 06:58:22 +00002468 // Now that we know how many fixed arguments we expect, first check that we
2469 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002470 if (TheCall->getNumArgs() < 1+NumFixed) {
2471 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2472 << 0 << 1+NumFixed << TheCall->getNumArgs()
2473 << TheCall->getCallee()->getSourceRange();
2474 return ExprError();
2475 }
Mike Stump11289f42009-09-09 15:08:12 +00002476
Hal Finkeld2208b52014-10-02 20:53:50 +00002477 if (WarnAboutSemanticsChange) {
2478 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2479 << TheCall->getCallee()->getSourceRange();
2480 }
2481
Chris Lattner5b9241b2009-05-08 15:36:58 +00002482 // Get the decl for the concrete builtin from this, we can tell what the
2483 // concrete integer type we should convert to is.
2484 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Eric Christopher02d5d862015-08-06 01:01:12 +00002485 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002486 FunctionDecl *NewBuiltinDecl;
2487 if (NewBuiltinID == BuiltinID)
2488 NewBuiltinDecl = FDecl;
2489 else {
2490 // Perform builtin lookup to avoid redeclaring it.
2491 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2492 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2493 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2494 assert(Res.getFoundDecl());
2495 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00002496 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002497 return ExprError();
2498 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002499
John McCallcf142162010-08-07 06:22:56 +00002500 // The first argument --- the pointer --- has a fixed type; we
2501 // deduce the types of the rest of the arguments accordingly. Walk
2502 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00002503 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002504 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002505
Chris Lattnerdc046542009-05-08 06:58:22 +00002506 // GCC does an implicit conversion to the pointer or integer ValType. This
2507 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002508 // Initialize the argument.
2509 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2510 ValType, /*consume*/ false);
2511 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002512 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002513 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002514
Chris Lattnerdc046542009-05-08 06:58:22 +00002515 // Okay, we have something that *can* be converted to the right type. Check
2516 // to see if there is a potentially weird extension going on here. This can
2517 // happen when you do an atomic operation on something like an char* and
2518 // pass in 42. The 42 gets converted to char. This is even more strange
2519 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002520 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002521 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002522 }
Mike Stump11289f42009-09-09 15:08:12 +00002523
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002524 ASTContext& Context = this->getASTContext();
2525
2526 // Create a new DeclRefExpr to refer to the new decl.
2527 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2528 Context,
2529 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002530 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002531 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002532 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002533 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002534 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002535 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002536
Chris Lattnerdc046542009-05-08 06:58:22 +00002537 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002538 // FIXME: This loses syntactic information.
2539 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2540 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2541 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002542 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002543
Chandler Carruthbc8cab12010-07-18 07:23:17 +00002544 // Change the result type of the call to match the original value type. This
2545 // is arbitrary, but the codegen for these builtins ins design to handle it
2546 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00002547 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002548
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002549 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002550}
2551
Michael Zolotukhin84df1232015-09-08 23:52:33 +00002552/// SemaBuiltinNontemporalOverloaded - We have a call to
2553/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2554/// overloaded function based on the pointer type of its last argument.
2555///
2556/// This function goes through and does final semantic checking for these
2557/// builtins.
2558ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
2559 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2560 DeclRefExpr *DRE =
2561 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2562 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2563 unsigned BuiltinID = FDecl->getBuiltinID();
2564 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
2565 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
2566 "Unexpected nontemporal load/store builtin!");
2567 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
2568 unsigned numArgs = isStore ? 2 : 1;
2569
2570 // Ensure that we have the proper number of arguments.
2571 if (checkArgCount(*this, TheCall, numArgs))
2572 return ExprError();
2573
2574 // Inspect the last argument of the nontemporal builtin. This should always
2575 // be a pointer type, from which we imply the type of the memory access.
2576 // Because it is a pointer type, we don't have to worry about any implicit
2577 // casts here.
2578 Expr *PointerArg = TheCall->getArg(numArgs - 1);
2579 ExprResult PointerArgResult =
2580 DefaultFunctionArrayLvalueConversion(PointerArg);
2581
2582 if (PointerArgResult.isInvalid())
2583 return ExprError();
2584 PointerArg = PointerArgResult.get();
2585 TheCall->setArg(numArgs - 1, PointerArg);
2586
2587 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2588 if (!pointerType) {
2589 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
2590 << PointerArg->getType() << PointerArg->getSourceRange();
2591 return ExprError();
2592 }
2593
2594 QualType ValType = pointerType->getPointeeType();
2595
2596 // Strip any qualifiers off ValType.
2597 ValType = ValType.getUnqualifiedType();
2598 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2599 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
2600 !ValType->isVectorType()) {
2601 Diag(DRE->getLocStart(),
2602 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
2603 << PointerArg->getType() << PointerArg->getSourceRange();
2604 return ExprError();
2605 }
2606
2607 if (!isStore) {
2608 TheCall->setType(ValType);
2609 return TheCallResult;
2610 }
2611
2612 ExprResult ValArg = TheCall->getArg(0);
2613 InitializedEntity Entity = InitializedEntity::InitializeParameter(
2614 Context, ValType, /*consume*/ false);
2615 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2616 if (ValArg.isInvalid())
2617 return ExprError();
2618
2619 TheCall->setArg(0, ValArg.get());
2620 TheCall->setType(Context.VoidTy);
2621 return TheCallResult;
2622}
2623
Chris Lattner6436fb62009-02-18 06:01:06 +00002624/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002625/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002626/// Note: It might also make sense to do the UTF-16 conversion here (would
2627/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002628bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002629 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002630 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2631
Douglas Gregorfb65e592011-07-27 05:40:30 +00002632 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002633 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2634 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002635 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002636 }
Mike Stump11289f42009-09-09 15:08:12 +00002637
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002638 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002639 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002640 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002641 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002642 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002643 UTF16 *ToPtr = &ToBuf[0];
2644
2645 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2646 &ToPtr, ToPtr + NumBytes,
2647 strictConversion);
2648 // Check for conversion failure.
2649 if (Result != conversionOK)
2650 Diag(Arg->getLocStart(),
2651 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2652 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002653 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002654}
2655
Charles Davisc7d5c942015-09-17 20:55:33 +00002656/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
2657/// for validity. Emit an error and return true on failure; return false
2658/// on success.
2659bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00002660 Expr *Fn = TheCall->getCallee();
2661 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002662 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002663 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002664 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2665 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002666 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002667 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002668 return true;
2669 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002670
2671 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002672 return Diag(TheCall->getLocEnd(),
2673 diag::err_typecheck_call_too_few_args_at_least)
2674 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002675 }
2676
John McCall29ad95b2011-08-27 01:09:30 +00002677 // Type-check the first argument normally.
2678 if (checkBuiltinArgument(*this, TheCall, 0))
2679 return true;
2680
Chris Lattnere202e6a2007-12-20 00:05:45 +00002681 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002682 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002683 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002684 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002685 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002686 else if (FunctionDecl *FD = getCurFunctionDecl())
2687 isVariadic = FD->isVariadic();
2688 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002689 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002690
Chris Lattnere202e6a2007-12-20 00:05:45 +00002691 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002692 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2693 return true;
2694 }
Mike Stump11289f42009-09-09 15:08:12 +00002695
Chris Lattner43be2e62007-12-19 23:59:04 +00002696 // Verify that the second argument to the builtin is the last argument of the
2697 // current function or method.
2698 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002699 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002700
Nico Weber9eea7642013-05-24 23:31:57 +00002701 // These are valid if SecondArgIsLastNamedArgument is false after the next
2702 // block.
2703 QualType Type;
2704 SourceLocation ParamLoc;
2705
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002706 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2707 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002708 // FIXME: This isn't correct for methods (results in bogus warning).
2709 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002710 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002711 if (CurBlock)
2712 LastArg = *(CurBlock->TheDecl->param_end()-1);
2713 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002714 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002715 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002716 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002717 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002718
2719 Type = PV->getType();
2720 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002721 }
2722 }
Mike Stump11289f42009-09-09 15:08:12 +00002723
Chris Lattner43be2e62007-12-19 23:59:04 +00002724 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002725 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00002726 diag::warn_second_arg_of_va_start_not_last_named_param);
Nico Weber9eea7642013-05-24 23:31:57 +00002727 else if (Type->isReferenceType()) {
2728 Diag(Arg->getLocStart(),
2729 diag::warn_va_start_of_reference_type_is_undefined);
2730 Diag(ParamLoc, diag::note_parameter_type) << Type;
2731 }
2732
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002733 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002734 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002735}
Chris Lattner43be2e62007-12-19 23:59:04 +00002736
Charles Davisc7d5c942015-09-17 20:55:33 +00002737/// Check the arguments to '__builtin_va_start' for validity, and that
2738/// it was called from a function of the native ABI.
2739/// Emit an error and return true on failure; return false on success.
2740bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2741 // On x86-64 Unix, don't allow this in Win64 ABI functions.
2742 // On x64 Windows, don't allow this in System V ABI functions.
2743 // (Yes, that means there's no corresponding way to support variadic
2744 // System V ABI functions on Windows.)
2745 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
2746 unsigned OS = Context.getTargetInfo().getTriple().getOS();
2747 clang::CallingConv CC = CC_C;
2748 if (const FunctionDecl *FD = getCurFunctionDecl())
2749 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2750 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
2751 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
2752 return Diag(TheCall->getCallee()->getLocStart(),
2753 diag::err_va_start_used_in_wrong_abi_function)
2754 << (OS != llvm::Triple::Win32);
2755 }
2756 return SemaBuiltinVAStartImpl(TheCall);
2757}
2758
2759/// Check the arguments to '__builtin_ms_va_start' for validity, and that
2760/// it was called from a Win64 ABI function.
2761/// Emit an error and return true on failure; return false on success.
2762bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
2763 // This only makes sense for x86-64.
2764 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2765 Expr *Callee = TheCall->getCallee();
2766 if (TT.getArch() != llvm::Triple::x86_64)
2767 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
2768 // Don't allow this in System V ABI functions.
2769 clang::CallingConv CC = CC_C;
2770 if (const FunctionDecl *FD = getCurFunctionDecl())
2771 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2772 if (CC == CC_X86_64SysV ||
2773 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
2774 return Diag(Callee->getLocStart(),
2775 diag::err_ms_va_start_used_in_sysv_function);
2776 return SemaBuiltinVAStartImpl(TheCall);
2777}
2778
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002779bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2780 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2781 // const char *named_addr);
2782
2783 Expr *Func = Call->getCallee();
2784
2785 if (Call->getNumArgs() < 3)
2786 return Diag(Call->getLocEnd(),
2787 diag::err_typecheck_call_too_few_args_at_least)
2788 << 0 /*function call*/ << 3 << Call->getNumArgs();
2789
2790 // Determine whether the current function is variadic or not.
2791 bool IsVariadic;
2792 if (BlockScopeInfo *CurBlock = getCurBlock())
2793 IsVariadic = CurBlock->TheDecl->isVariadic();
2794 else if (FunctionDecl *FD = getCurFunctionDecl())
2795 IsVariadic = FD->isVariadic();
2796 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2797 IsVariadic = MD->isVariadic();
2798 else
2799 llvm_unreachable("unexpected statement type");
2800
2801 if (!IsVariadic) {
2802 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2803 return true;
2804 }
2805
2806 // Type-check the first argument normally.
2807 if (checkBuiltinArgument(*this, Call, 0))
2808 return true;
2809
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002810 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002811 unsigned ArgNo;
2812 QualType Type;
2813 } ArgumentTypes[] = {
2814 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2815 { 2, Context.getSizeType() },
2816 };
2817
2818 for (const auto &AT : ArgumentTypes) {
2819 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2820 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2821 continue;
2822 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2823 << Arg->getType() << AT.Type << 1 /* different class */
2824 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2825 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2826 }
2827
2828 return false;
2829}
2830
Chris Lattner2da14fb2007-12-20 00:26:33 +00002831/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2832/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002833bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2834 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002835 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002836 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002837 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002838 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002839 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002840 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002841 << SourceRange(TheCall->getArg(2)->getLocStart(),
2842 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002843
John Wiegley01296292011-04-08 18:41:53 +00002844 ExprResult OrigArg0 = TheCall->getArg(0);
2845 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002846
Chris Lattner2da14fb2007-12-20 00:26:33 +00002847 // Do standard promotions between the two arguments, returning their common
2848 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002849 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002850 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2851 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002852
2853 // Make sure any conversions are pushed back into the call; this is
2854 // type safe since unordered compare builtins are declared as "_Bool
2855 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002856 TheCall->setArg(0, OrigArg0.get());
2857 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002858
John Wiegley01296292011-04-08 18:41:53 +00002859 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002860 return false;
2861
Chris Lattner2da14fb2007-12-20 00:26:33 +00002862 // If the common type isn't a real floating type, then the arguments were
2863 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002864 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002865 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002866 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002867 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2868 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002869
Chris Lattner2da14fb2007-12-20 00:26:33 +00002870 return false;
2871}
2872
Benjamin Kramer634fc102010-02-15 22:42:31 +00002873/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2874/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002875/// to check everything. We expect the last argument to be a floating point
2876/// value.
2877bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2878 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002879 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002880 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002881 if (TheCall->getNumArgs() > NumArgs)
2882 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002883 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002884 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002885 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002886 (*(TheCall->arg_end()-1))->getLocEnd());
2887
Benjamin Kramer64aae502010-02-16 10:07:31 +00002888 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002889
Eli Friedman7e4faac2009-08-31 20:06:00 +00002890 if (OrigArg->isTypeDependent())
2891 return false;
2892
Chris Lattner68784ef2010-05-06 05:50:07 +00002893 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002894 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002895 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002896 diag::err_typecheck_call_invalid_unary_fp)
2897 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002898
Chris Lattner68784ef2010-05-06 05:50:07 +00002899 // If this is an implicit conversion from float -> double, remove it.
2900 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2901 Expr *CastArg = Cast->getSubExpr();
2902 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2903 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2904 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002905 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002906 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002907 }
2908 }
2909
Eli Friedman7e4faac2009-08-31 20:06:00 +00002910 return false;
2911}
2912
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002913/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2914// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002915ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002916 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002917 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002918 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002919 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2920 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002921
Nate Begemana0110022010-06-08 00:16:34 +00002922 // Determine which of the following types of shufflevector we're checking:
2923 // 1) unary, vector mask: (lhs, mask)
2924 // 2) binary, vector mask: (lhs, rhs, mask)
2925 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2926 QualType resType = TheCall->getArg(0)->getType();
2927 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002928
Douglas Gregorc25f7662009-05-19 22:10:17 +00002929 if (!TheCall->getArg(0)->isTypeDependent() &&
2930 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002931 QualType LHSType = TheCall->getArg(0)->getType();
2932 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002933
Craig Topperbaca3892013-07-29 06:47:04 +00002934 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2935 return ExprError(Diag(TheCall->getLocStart(),
2936 diag::err_shufflevector_non_vector)
2937 << SourceRange(TheCall->getArg(0)->getLocStart(),
2938 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002939
Nate Begemana0110022010-06-08 00:16:34 +00002940 numElements = LHSType->getAs<VectorType>()->getNumElements();
2941 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002942
Nate Begemana0110022010-06-08 00:16:34 +00002943 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2944 // with mask. If so, verify that RHS is an integer vector type with the
2945 // same number of elts as lhs.
2946 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002947 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002948 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002949 return ExprError(Diag(TheCall->getLocStart(),
2950 diag::err_shufflevector_incompatible_vector)
2951 << SourceRange(TheCall->getArg(1)->getLocStart(),
2952 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002953 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002954 return ExprError(Diag(TheCall->getLocStart(),
2955 diag::err_shufflevector_incompatible_vector)
2956 << SourceRange(TheCall->getArg(0)->getLocStart(),
2957 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002958 } else if (numElements != numResElements) {
2959 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002960 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002961 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002962 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002963 }
2964
2965 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002966 if (TheCall->getArg(i)->isTypeDependent() ||
2967 TheCall->getArg(i)->isValueDependent())
2968 continue;
2969
Nate Begemana0110022010-06-08 00:16:34 +00002970 llvm::APSInt Result(32);
2971 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2972 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002973 diag::err_shufflevector_nonconstant_argument)
2974 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002975
Craig Topper50ad5b72013-08-03 17:40:38 +00002976 // Allow -1 which will be translated to undef in the IR.
2977 if (Result.isSigned() && Result.isAllOnesValue())
2978 continue;
2979
Chris Lattner7ab824e2008-08-10 02:05:13 +00002980 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002981 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002982 diag::err_shufflevector_argument_too_large)
2983 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002984 }
2985
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002986 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002987
Chris Lattner7ab824e2008-08-10 02:05:13 +00002988 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002989 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002990 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002991 }
2992
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002993 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2994 TheCall->getCallee()->getLocStart(),
2995 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002996}
Chris Lattner43be2e62007-12-19 23:59:04 +00002997
Hal Finkelc4d7c822013-09-18 03:29:45 +00002998/// SemaConvertVectorExpr - Handle __builtin_convertvector
2999ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3000 SourceLocation BuiltinLoc,
3001 SourceLocation RParenLoc) {
3002 ExprValueKind VK = VK_RValue;
3003 ExprObjectKind OK = OK_Ordinary;
3004 QualType DstTy = TInfo->getType();
3005 QualType SrcTy = E->getType();
3006
3007 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3008 return ExprError(Diag(BuiltinLoc,
3009 diag::err_convertvector_non_vector)
3010 << E->getSourceRange());
3011 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3012 return ExprError(Diag(BuiltinLoc,
3013 diag::err_convertvector_non_vector_type));
3014
3015 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3016 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3017 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3018 if (SrcElts != DstElts)
3019 return ExprError(Diag(BuiltinLoc,
3020 diag::err_convertvector_incompatible_vector)
3021 << E->getSourceRange());
3022 }
3023
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003024 return new (Context)
3025 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003026}
3027
Daniel Dunbarb7257262008-07-21 22:59:13 +00003028/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3029// This is declared to take (const void*, ...) and can take two
3030// optional constant int args.
3031bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003032 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003033
Chris Lattner3b054132008-11-19 05:08:23 +00003034 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003035 return Diag(TheCall->getLocEnd(),
3036 diag::err_typecheck_call_too_many_args_at_most)
3037 << 0 /*function call*/ << 3 << NumArgs
3038 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003039
3040 // Argument 0 is checked for us and the remaining arguments must be
3041 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003042 for (unsigned i = 1; i != NumArgs; ++i)
3043 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003044 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003045
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003046 return false;
3047}
3048
Hal Finkelf0417332014-07-17 14:25:55 +00003049/// SemaBuiltinAssume - Handle __assume (MS Extension).
3050// __assume does not evaluate its arguments, and should warn if its argument
3051// has side effects.
3052bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3053 Expr *Arg = TheCall->getArg(0);
3054 if (Arg->isInstantiationDependent()) return false;
3055
3056 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003057 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003058 << Arg->getSourceRange()
3059 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3060
3061 return false;
3062}
3063
3064/// Handle __builtin_assume_aligned. This is declared
3065/// as (const void*, size_t, ...) and can take one optional constant int arg.
3066bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3067 unsigned NumArgs = TheCall->getNumArgs();
3068
3069 if (NumArgs > 3)
3070 return Diag(TheCall->getLocEnd(),
3071 diag::err_typecheck_call_too_many_args_at_most)
3072 << 0 /*function call*/ << 3 << NumArgs
3073 << TheCall->getSourceRange();
3074
3075 // The alignment must be a constant integer.
3076 Expr *Arg = TheCall->getArg(1);
3077
3078 // We can't check the value of a dependent argument.
3079 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3080 llvm::APSInt Result;
3081 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3082 return true;
3083
3084 if (!Result.isPowerOf2())
3085 return Diag(TheCall->getLocStart(),
3086 diag::err_alignment_not_power_of_two)
3087 << Arg->getSourceRange();
3088 }
3089
3090 if (NumArgs > 2) {
3091 ExprResult Arg(TheCall->getArg(2));
3092 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3093 Context.getSizeType(), false);
3094 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3095 if (Arg.isInvalid()) return true;
3096 TheCall->setArg(2, Arg.get());
3097 }
Hal Finkelf0417332014-07-17 14:25:55 +00003098
3099 return false;
3100}
3101
Eric Christopher8d0c6212010-04-17 02:26:23 +00003102/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3103/// TheCall is a constant expression.
3104bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3105 llvm::APSInt &Result) {
3106 Expr *Arg = TheCall->getArg(ArgNum);
3107 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3108 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3109
3110 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3111
3112 if (!Arg->isIntegerConstantExpr(Result, Context))
3113 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00003114 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00003115
Chris Lattnerd545ad12009-09-23 06:06:36 +00003116 return false;
3117}
3118
Richard Sandiford28940af2014-04-16 08:47:51 +00003119/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3120/// TheCall is a constant expression in the range [Low, High].
3121bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3122 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00003123 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003124
3125 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00003126 Expr *Arg = TheCall->getArg(ArgNum);
3127 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003128 return false;
3129
Eric Christopher8d0c6212010-04-17 02:26:23 +00003130 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00003131 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003132 return true;
3133
Richard Sandiford28940af2014-04-16 08:47:51 +00003134 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00003135 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00003136 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00003137
3138 return false;
3139}
3140
Luke Cheeseman59b2d832015-06-15 17:51:01 +00003141/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3142/// TheCall is an ARM/AArch64 special register string literal.
3143bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3144 int ArgNum, unsigned ExpectedFieldNum,
3145 bool AllowName) {
3146 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3147 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3148 BuiltinID == ARM::BI__builtin_arm_rsr ||
3149 BuiltinID == ARM::BI__builtin_arm_rsrp ||
3150 BuiltinID == ARM::BI__builtin_arm_wsr ||
3151 BuiltinID == ARM::BI__builtin_arm_wsrp;
3152 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3153 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3154 BuiltinID == AArch64::BI__builtin_arm_rsr ||
3155 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3156 BuiltinID == AArch64::BI__builtin_arm_wsr ||
3157 BuiltinID == AArch64::BI__builtin_arm_wsrp;
3158 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3159
3160 // We can't check the value of a dependent argument.
3161 Expr *Arg = TheCall->getArg(ArgNum);
3162 if (Arg->isTypeDependent() || Arg->isValueDependent())
3163 return false;
3164
3165 // Check if the argument is a string literal.
3166 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3167 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3168 << Arg->getSourceRange();
3169
3170 // Check the type of special register given.
3171 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3172 SmallVector<StringRef, 6> Fields;
3173 Reg.split(Fields, ":");
3174
3175 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3176 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3177 << Arg->getSourceRange();
3178
3179 // If the string is the name of a register then we cannot check that it is
3180 // valid here but if the string is of one the forms described in ACLE then we
3181 // can check that the supplied fields are integers and within the valid
3182 // ranges.
3183 if (Fields.size() > 1) {
3184 bool FiveFields = Fields.size() == 5;
3185
3186 bool ValidString = true;
3187 if (IsARMBuiltin) {
3188 ValidString &= Fields[0].startswith_lower("cp") ||
3189 Fields[0].startswith_lower("p");
3190 if (ValidString)
3191 Fields[0] =
3192 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3193
3194 ValidString &= Fields[2].startswith_lower("c");
3195 if (ValidString)
3196 Fields[2] = Fields[2].drop_front(1);
3197
3198 if (FiveFields) {
3199 ValidString &= Fields[3].startswith_lower("c");
3200 if (ValidString)
3201 Fields[3] = Fields[3].drop_front(1);
3202 }
3203 }
3204
3205 SmallVector<int, 5> Ranges;
3206 if (FiveFields)
3207 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3208 else
3209 Ranges.append({15, 7, 15});
3210
3211 for (unsigned i=0; i<Fields.size(); ++i) {
3212 int IntField;
3213 ValidString &= !Fields[i].getAsInteger(10, IntField);
3214 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3215 }
3216
3217 if (!ValidString)
3218 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3219 << Arg->getSourceRange();
3220
3221 } else if (IsAArch64Builtin && Fields.size() == 1) {
3222 // If the register name is one of those that appear in the condition below
3223 // and the special register builtin being used is one of the write builtins,
3224 // then we require that the argument provided for writing to the register
3225 // is an integer constant expression. This is because it will be lowered to
3226 // an MSR (immediate) instruction, so we need to know the immediate at
3227 // compile time.
3228 if (TheCall->getNumArgs() != 2)
3229 return false;
3230
3231 std::string RegLower = Reg.lower();
3232 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3233 RegLower != "pan" && RegLower != "uao")
3234 return false;
3235
3236 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3237 }
3238
3239 return false;
3240}
3241
Eli Friedmanc97d0142009-05-03 06:04:26 +00003242/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003243/// This checks that the target supports __builtin_longjmp and
3244/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003245bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003246 if (!Context.getTargetInfo().hasSjLjLowering())
3247 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3248 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3249
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003250 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00003251 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00003252
Eric Christopher8d0c6212010-04-17 02:26:23 +00003253 // TODO: This is less than ideal. Overload this to take a value.
3254 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3255 return true;
3256
3257 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003258 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3259 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3260
3261 return false;
3262}
3263
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003264/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3265/// This checks that the target supports __builtin_setjmp.
3266bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3267 if (!Context.getTargetInfo().hasSjLjLowering())
3268 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3269 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3270 return false;
3271}
3272
Richard Smithd7293d72013-08-05 18:49:43 +00003273namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003274class UncoveredArgHandler {
3275 enum { Unknown = -1, AllCovered = -2 };
3276 signed FirstUncoveredArg;
3277 SmallVector<const Expr *, 4> DiagnosticExprs;
3278
3279public:
3280 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
3281
3282 bool hasUncoveredArg() const {
3283 return (FirstUncoveredArg >= 0);
3284 }
3285
3286 unsigned getUncoveredArg() const {
3287 assert(hasUncoveredArg() && "no uncovered argument");
3288 return FirstUncoveredArg;
3289 }
3290
3291 void setAllCovered() {
3292 // A string has been found with all arguments covered, so clear out
3293 // the diagnostics.
3294 DiagnosticExprs.clear();
3295 FirstUncoveredArg = AllCovered;
3296 }
3297
3298 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
3299 assert(NewFirstUncoveredArg >= 0 && "Outside range");
3300
3301 // Don't update if a previous string covers all arguments.
3302 if (FirstUncoveredArg == AllCovered)
3303 return;
3304
3305 // UncoveredArgHandler tracks the highest uncovered argument index
3306 // and with it all the strings that match this index.
3307 if (NewFirstUncoveredArg == FirstUncoveredArg)
3308 DiagnosticExprs.push_back(StrExpr);
3309 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
3310 DiagnosticExprs.clear();
3311 DiagnosticExprs.push_back(StrExpr);
3312 FirstUncoveredArg = NewFirstUncoveredArg;
3313 }
3314 }
3315
3316 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
3317};
3318
Richard Smithd7293d72013-08-05 18:49:43 +00003319enum StringLiteralCheckType {
3320 SLCT_NotALiteral,
3321 SLCT_UncheckedLiteral,
3322 SLCT_CheckedLiteral
3323};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003324} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00003325
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003326static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
3327 const Expr *OrigFormatExpr,
3328 ArrayRef<const Expr *> Args,
3329 bool HasVAListArg, unsigned format_idx,
3330 unsigned firstDataArg,
3331 Sema::FormatStringType Type,
3332 bool inFunctionCall,
3333 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003334 llvm::SmallBitVector &CheckedVarArgs,
3335 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003336
Richard Smith55ce3522012-06-25 20:30:08 +00003337// Determine if an expression is a string literal or constant string.
3338// If this function returns false on the arguments to a function expecting a
3339// format string, we will usually need to emit a warning.
3340// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00003341static StringLiteralCheckType
3342checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3343 bool HasVAListArg, unsigned format_idx,
3344 unsigned firstDataArg, Sema::FormatStringType Type,
3345 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003346 llvm::SmallBitVector &CheckedVarArgs,
3347 UncoveredArgHandler &UncoveredArg) {
Ted Kremenek808829352010-09-09 03:51:39 +00003348 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00003349 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00003350 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003351
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003352 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00003353
Richard Smithd7293d72013-08-05 18:49:43 +00003354 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00003355 // Technically -Wformat-nonliteral does not warn about this case.
3356 // The behavior of printf and friends in this case is implementation
3357 // dependent. Ideally if the format string cannot be null then
3358 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00003359 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00003360
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003361 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00003362 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003363 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00003364 // The expression is a literal if both sub-expressions were, and it was
3365 // completely checked only if both sub-expressions were checked.
3366 const AbstractConditionalOperator *C =
3367 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003368
3369 // Determine whether it is necessary to check both sub-expressions, for
3370 // example, because the condition expression is a constant that can be
3371 // evaluated at compile time.
3372 bool CheckLeft = true, CheckRight = true;
3373
3374 bool Cond;
3375 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
3376 if (Cond)
3377 CheckRight = false;
3378 else
3379 CheckLeft = false;
3380 }
3381
3382 StringLiteralCheckType Left;
3383 if (!CheckLeft)
3384 Left = SLCT_UncheckedLiteral;
3385 else {
3386 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
3387 HasVAListArg, format_idx, firstDataArg,
3388 Type, CallType, InFunctionCall,
3389 CheckedVarArgs, UncoveredArg);
3390 if (Left == SLCT_NotALiteral || !CheckRight)
3391 return Left;
3392 }
3393
Richard Smith55ce3522012-06-25 20:30:08 +00003394 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00003395 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003396 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003397 Type, CallType, InFunctionCall, CheckedVarArgs,
3398 UncoveredArg);
3399
3400 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003401 }
3402
3403 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00003404 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3405 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003406 }
3407
John McCallc07a0c72011-02-17 10:25:35 +00003408 case Stmt::OpaqueValueExprClass:
3409 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3410 E = src;
3411 goto tryAgain;
3412 }
Richard Smith55ce3522012-06-25 20:30:08 +00003413 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00003414
Ted Kremeneka8890832011-02-24 23:03:04 +00003415 case Stmt::PredefinedExprClass:
3416 // While __func__, etc., are technically not string literals, they
3417 // cannot contain format specifiers and thus are not a security
3418 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00003419 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00003420
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003421 case Stmt::DeclRefExprClass: {
3422 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003423
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003424 // As an exception, do not flag errors for variables binding to
3425 // const string literals.
3426 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3427 bool isConstant = false;
3428 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003429
Richard Smithd7293d72013-08-05 18:49:43 +00003430 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3431 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003432 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00003433 isConstant = T.isConstant(S.Context) &&
3434 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00003435 } else if (T->isObjCObjectPointerType()) {
3436 // In ObjC, there is usually no "const ObjectPointer" type,
3437 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00003438 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003439 }
Mike Stump11289f42009-09-09 15:08:12 +00003440
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003441 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003442 if (const Expr *Init = VD->getAnyInitializer()) {
3443 // Look through initializers like const char c[] = { "foo" }
3444 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3445 if (InitList->isStringLiteralInit())
3446 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3447 }
Richard Smithd7293d72013-08-05 18:49:43 +00003448 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003449 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003450 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003451 /*InFunctionCall*/false, CheckedVarArgs,
3452 UncoveredArg);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003453 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003454 }
Mike Stump11289f42009-09-09 15:08:12 +00003455
Anders Carlssonb012ca92009-06-28 19:55:58 +00003456 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3457 // special check to see if the format string is a function parameter
3458 // of the function calling the printf function. If the function
3459 // has an attribute indicating it is a printf-like function, then we
3460 // should suppress warnings concerning non-literals being used in a call
3461 // to a vprintf function. For example:
3462 //
3463 // void
3464 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3465 // va_list ap;
3466 // va_start(ap, fmt);
3467 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3468 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00003469 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003470 if (HasVAListArg) {
3471 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3472 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3473 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003474 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003475 // adjust for implicit parameter
3476 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3477 if (MD->isInstance())
3478 ++PVIndex;
3479 // We also check if the formats are compatible.
3480 // We can't pass a 'scanf' string to a 'printf' function.
3481 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00003482 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00003483 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003484 }
3485 }
3486 }
3487 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003488 }
Mike Stump11289f42009-09-09 15:08:12 +00003489
Richard Smith55ce3522012-06-25 20:30:08 +00003490 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003491 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003492
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003493 case Stmt::CallExprClass:
3494 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003495 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003496 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3497 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3498 unsigned ArgIndex = FA->getFormatIdx();
3499 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3500 if (MD->isInstance())
3501 --ArgIndex;
3502 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00003503
Richard Smithd7293d72013-08-05 18:49:43 +00003504 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003505 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003506 Type, CallType, InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003507 CheckedVarArgs, UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003508 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3509 unsigned BuiltinID = FD->getBuiltinID();
3510 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3511 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3512 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00003513 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003514 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003515 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003516 InFunctionCall, CheckedVarArgs,
3517 UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003518 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003519 }
3520 }
Mike Stump11289f42009-09-09 15:08:12 +00003521
Richard Smith55ce3522012-06-25 20:30:08 +00003522 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003523 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003524 case Stmt::ObjCStringLiteralClass:
3525 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00003526 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003527
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003528 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003529 StrE = ObjCFExpr->getString();
3530 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003531 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003532
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003533 if (StrE) {
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003534 CheckFormatString(S, StrE, E, Args, HasVAListArg, format_idx,
3535 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003536 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00003537 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003538 }
Mike Stump11289f42009-09-09 15:08:12 +00003539
Richard Smith55ce3522012-06-25 20:30:08 +00003540 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003541 }
Mike Stump11289f42009-09-09 15:08:12 +00003542
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003543 default:
Richard Smith55ce3522012-06-25 20:30:08 +00003544 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003545 }
3546}
3547
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003548Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003549 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003550 .Case("scanf", FST_Scanf)
3551 .Cases("printf", "printf0", FST_Printf)
3552 .Cases("NSString", "CFString", FST_NSString)
3553 .Case("strftime", FST_Strftime)
3554 .Case("strfmon", FST_Strfmon)
3555 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003556 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00003557 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003558 .Default(FST_Unknown);
3559}
3560
Jordan Rose3e0ec582012-07-19 18:10:23 +00003561/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00003562/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003563/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003564bool Sema::CheckFormatArguments(const FormatAttr *Format,
3565 ArrayRef<const Expr *> Args,
3566 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003567 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003568 SourceLocation Loc, SourceRange Range,
3569 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00003570 FormatStringInfo FSI;
3571 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003572 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00003573 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00003574 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003575 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003576}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003577
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003578bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003579 bool HasVAListArg, unsigned format_idx,
3580 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003581 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003582 SourceLocation Loc, SourceRange Range,
3583 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003584 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003585 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003586 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00003587 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003588 }
Mike Stump11289f42009-09-09 15:08:12 +00003589
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003590 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003591
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003592 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00003593 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003594 // Dynamically generated format strings are difficult to
3595 // automatically vet at compile time. Requiring that format strings
3596 // are string literals: (1) permits the checking of format strings by
3597 // the compiler and thereby (2) can practically remove the source of
3598 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00003599
Mike Stump11289f42009-09-09 15:08:12 +00003600 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00003601 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00003602 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00003603 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003604 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00003605 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00003606 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3607 format_idx, firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003608 /*IsFunctionCall*/true, CheckedVarArgs,
3609 UncoveredArg);
3610
3611 // Generate a diagnostic where an uncovered argument is detected.
3612 if (UncoveredArg.hasUncoveredArg()) {
3613 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
3614 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
3615 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
3616 }
3617
Richard Smith55ce3522012-06-25 20:30:08 +00003618 if (CT != SLCT_NotALiteral)
3619 // Literal format string found, check done!
3620 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00003621
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003622 // Strftime is particular as it always uses a single 'time' argument,
3623 // so it is safe to pass a non-literal string.
3624 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00003625 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003626
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003627 // Do not emit diag when the string param is a macro expansion and the
3628 // format is either NSString or CFString. This is a hack to prevent
3629 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3630 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003631 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
3632 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00003633 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003634
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003635 // If there are no arguments specified, warn with -Wformat-security, otherwise
3636 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003637 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00003638 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
3639 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003640 switch (Type) {
3641 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003642 break;
3643 case FST_Kprintf:
3644 case FST_FreeBSDKPrintf:
3645 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00003646 Diag(FormatLoc, diag::note_format_security_fixit)
3647 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003648 break;
3649 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00003650 Diag(FormatLoc, diag::note_format_security_fixit)
3651 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003652 break;
3653 }
3654 } else {
3655 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003656 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003657 }
Richard Smith55ce3522012-06-25 20:30:08 +00003658 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003659}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003660
Ted Kremenekab278de2010-01-28 23:39:18 +00003661namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00003662class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3663protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00003664 Sema &S;
3665 const StringLiteral *FExpr;
3666 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003667 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00003668 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00003669 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00003670 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003671 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00003672 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00003673 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00003674 bool usesPositionalArgs;
3675 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003676 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00003677 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00003678 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003679 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003680
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003681public:
Ted Kremenek02087932010-07-16 02:11:22 +00003682 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003683 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003684 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003685 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003686 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003687 Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003688 llvm::SmallBitVector &CheckedVarArgs,
3689 UncoveredArgHandler &UncoveredArg)
Ted Kremenekab278de2010-01-28 23:39:18 +00003690 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003691 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3692 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003693 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00003694 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00003695 inFunctionCall(inFunctionCall), CallType(callType),
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003696 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00003697 CoveredArgs.resize(numDataArgs);
3698 CoveredArgs.reset();
3699 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003700
Ted Kremenek019d2242010-01-29 01:50:07 +00003701 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003702
Ted Kremenek02087932010-07-16 02:11:22 +00003703 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003704 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003705
Jordan Rose92303592012-09-08 04:00:03 +00003706 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003707 const analyze_format_string::FormatSpecifier &FS,
3708 const analyze_format_string::ConversionSpecifier &CS,
3709 const char *startSpecifier, unsigned specifierLen,
3710 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00003711
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003712 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003713 const analyze_format_string::FormatSpecifier &FS,
3714 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003715
3716 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003717 const analyze_format_string::ConversionSpecifier &CS,
3718 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003719
Craig Toppere14c0f82014-03-12 04:55:44 +00003720 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003721
Craig Toppere14c0f82014-03-12 04:55:44 +00003722 void HandleInvalidPosition(const char *startSpecifier,
3723 unsigned specifierLen,
3724 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003725
Craig Toppere14c0f82014-03-12 04:55:44 +00003726 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003727
Craig Toppere14c0f82014-03-12 04:55:44 +00003728 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003729
Richard Trieu03cf7b72011-10-28 00:41:25 +00003730 template <typename Range>
3731 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3732 const Expr *ArgumentExpr,
3733 PartialDiagnostic PDiag,
3734 SourceLocation StringLoc,
3735 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003736 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003737
Ted Kremenek02087932010-07-16 02:11:22 +00003738protected:
Ted Kremenekce815422010-07-19 21:25:57 +00003739 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3740 const char *startSpec,
3741 unsigned specifierLen,
3742 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003743
3744 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
3745 const char *startSpec,
3746 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003747
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003748 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00003749 CharSourceRange getSpecifierRange(const char *startSpecifier,
3750 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00003751 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003752
Ted Kremenek5739de72010-01-29 01:06:55 +00003753 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003754
3755 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
3756 const analyze_format_string::ConversionSpecifier &CS,
3757 const char *startSpecifier, unsigned specifierLen,
3758 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003759
3760 template <typename Range>
3761 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3762 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003763 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00003764};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003765} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00003766
Ted Kremenek02087932010-07-16 02:11:22 +00003767SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00003768 return OrigFormatExpr->getSourceRange();
3769}
3770
Ted Kremenek02087932010-07-16 02:11:22 +00003771CharSourceRange CheckFormatHandler::
3772getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00003773 SourceLocation Start = getLocationOfByte(startSpecifier);
3774 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3775
3776 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003777 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00003778
3779 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003780}
3781
Ted Kremenek02087932010-07-16 02:11:22 +00003782SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003783 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00003784}
3785
Ted Kremenek02087932010-07-16 02:11:22 +00003786void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
3787 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00003788 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
3789 getLocationOfByte(startSpecifier),
3790 /*IsStringLocation*/true,
3791 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00003792}
3793
Jordan Rose92303592012-09-08 04:00:03 +00003794void CheckFormatHandler::HandleInvalidLengthModifier(
3795 const analyze_format_string::FormatSpecifier &FS,
3796 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00003797 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00003798 using namespace analyze_format_string;
3799
3800 const LengthModifier &LM = FS.getLengthModifier();
3801 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3802
3803 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003804 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00003805 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003806 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003807 getLocationOfByte(LM.getStart()),
3808 /*IsStringLocation*/true,
3809 getSpecifierRange(startSpecifier, specifierLen));
3810
3811 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3812 << FixedLM->toString()
3813 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3814
3815 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003816 FixItHint Hint;
3817 if (DiagID == diag::warn_format_nonsensical_length)
3818 Hint = FixItHint::CreateRemoval(LMRange);
3819
3820 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003821 getLocationOfByte(LM.getStart()),
3822 /*IsStringLocation*/true,
3823 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00003824 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00003825 }
3826}
3827
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003828void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00003829 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003830 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003831 using namespace analyze_format_string;
3832
3833 const LengthModifier &LM = FS.getLengthModifier();
3834 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3835
3836 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003837 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00003838 if (FixedLM) {
3839 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3840 << LM.toString() << 0,
3841 getLocationOfByte(LM.getStart()),
3842 /*IsStringLocation*/true,
3843 getSpecifierRange(startSpecifier, specifierLen));
3844
3845 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3846 << FixedLM->toString()
3847 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3848
3849 } else {
3850 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3851 << LM.toString() << 0,
3852 getLocationOfByte(LM.getStart()),
3853 /*IsStringLocation*/true,
3854 getSpecifierRange(startSpecifier, specifierLen));
3855 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003856}
3857
3858void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3859 const analyze_format_string::ConversionSpecifier &CS,
3860 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00003861 using namespace analyze_format_string;
3862
3863 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00003864 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00003865 if (FixedCS) {
3866 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3867 << CS.toString() << /*conversion specifier*/1,
3868 getLocationOfByte(CS.getStart()),
3869 /*IsStringLocation*/true,
3870 getSpecifierRange(startSpecifier, specifierLen));
3871
3872 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3873 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3874 << FixedCS->toString()
3875 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3876 } else {
3877 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3878 << CS.toString() << /*conversion specifier*/1,
3879 getLocationOfByte(CS.getStart()),
3880 /*IsStringLocation*/true,
3881 getSpecifierRange(startSpecifier, specifierLen));
3882 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003883}
3884
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003885void CheckFormatHandler::HandlePosition(const char *startPos,
3886 unsigned posLen) {
3887 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3888 getLocationOfByte(startPos),
3889 /*IsStringLocation*/true,
3890 getSpecifierRange(startPos, posLen));
3891}
3892
Ted Kremenekd1668192010-02-27 01:41:03 +00003893void
Ted Kremenek02087932010-07-16 02:11:22 +00003894CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3895 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003896 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3897 << (unsigned) p,
3898 getLocationOfByte(startPos), /*IsStringLocation*/true,
3899 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003900}
3901
Ted Kremenek02087932010-07-16 02:11:22 +00003902void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003903 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003904 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3905 getLocationOfByte(startPos),
3906 /*IsStringLocation*/true,
3907 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003908}
3909
Ted Kremenek02087932010-07-16 02:11:22 +00003910void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003911 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003912 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003913 EmitFormatDiagnostic(
3914 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3915 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3916 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003917 }
Ted Kremenek02087932010-07-16 02:11:22 +00003918}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003919
Jordan Rose58bbe422012-07-19 18:10:08 +00003920// Note that this may return NULL if there was an error parsing or building
3921// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003922const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003923 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003924}
3925
3926void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003927 // Does the number of data arguments exceed the number of
3928 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00003929 if (!HasVAListArg) {
3930 // Find any arguments that weren't covered.
3931 CoveredArgs.flip();
3932 signed notCoveredArg = CoveredArgs.find_first();
3933 if (notCoveredArg >= 0) {
3934 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003935 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
3936 } else {
3937 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00003938 }
3939 }
3940}
3941
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003942void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
3943 const Expr *ArgExpr) {
3944 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
3945 "Invalid state");
3946
3947 if (!ArgExpr)
3948 return;
3949
3950 SourceLocation Loc = ArgExpr->getLocStart();
3951
3952 if (S.getSourceManager().isInSystemMacro(Loc))
3953 return;
3954
3955 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
3956 for (auto E : DiagnosticExprs)
3957 PDiag << E->getSourceRange();
3958
3959 CheckFormatHandler::EmitFormatDiagnostic(
3960 S, IsFunctionCall, DiagnosticExprs[0],
3961 PDiag, Loc, /*IsStringLocation*/false,
3962 DiagnosticExprs[0]->getSourceRange());
3963}
3964
Ted Kremenekce815422010-07-19 21:25:57 +00003965bool
3966CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3967 SourceLocation Loc,
3968 const char *startSpec,
3969 unsigned specifierLen,
3970 const char *csStart,
3971 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00003972 bool keepGoing = true;
3973 if (argIndex < NumDataArgs) {
3974 // Consider the argument coverered, even though the specifier doesn't
3975 // make sense.
3976 CoveredArgs.set(argIndex);
3977 }
3978 else {
3979 // If argIndex exceeds the number of data arguments we
3980 // don't issue a warning because that is just a cascade of warnings (and
3981 // they may have intended '%%' anyway). We don't want to continue processing
3982 // the format string after this point, however, as we will like just get
3983 // gibberish when trying to match arguments.
3984 keepGoing = false;
3985 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00003986
3987 StringRef Specifier(csStart, csLen);
3988
3989 // If the specifier in non-printable, it could be the first byte of a UTF-8
3990 // sequence. In that case, print the UTF-8 code point. If not, print the byte
3991 // hex value.
3992 std::string CodePointStr;
3993 if (!llvm::sys::locale::isPrint(*csStart)) {
3994 UTF32 CodePoint;
3995 const UTF8 **B = reinterpret_cast<const UTF8 **>(&csStart);
3996 const UTF8 *E =
3997 reinterpret_cast<const UTF8 *>(csStart + csLen);
3998 ConversionResult Result =
3999 llvm::convertUTF8Sequence(B, E, &CodePoint, strictConversion);
4000
4001 if (Result != conversionOK) {
4002 unsigned char FirstChar = *csStart;
4003 CodePoint = (UTF32)FirstChar;
4004 }
4005
4006 llvm::raw_string_ostream OS(CodePointStr);
4007 if (CodePoint < 256)
4008 OS << "\\x" << llvm::format("%02x", CodePoint);
4009 else if (CodePoint <= 0xFFFF)
4010 OS << "\\u" << llvm::format("%04x", CodePoint);
4011 else
4012 OS << "\\U" << llvm::format("%08x", CodePoint);
4013 OS.flush();
4014 Specifier = CodePointStr;
4015 }
4016
4017 EmitFormatDiagnostic(
4018 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
4019 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
4020
Ted Kremenekce815422010-07-19 21:25:57 +00004021 return keepGoing;
4022}
4023
Richard Trieu03cf7b72011-10-28 00:41:25 +00004024void
4025CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
4026 const char *startSpec,
4027 unsigned specifierLen) {
4028 EmitFormatDiagnostic(
4029 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
4030 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
4031}
4032
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004033bool
4034CheckFormatHandler::CheckNumArgs(
4035 const analyze_format_string::FormatSpecifier &FS,
4036 const analyze_format_string::ConversionSpecifier &CS,
4037 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
4038
4039 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004040 PartialDiagnostic PDiag = FS.usesPositionalArg()
4041 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
4042 << (argIndex+1) << NumDataArgs)
4043 : S.PDiag(diag::warn_printf_insufficient_data_args);
4044 EmitFormatDiagnostic(
4045 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
4046 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004047
4048 // Since more arguments than conversion tokens are given, by extension
4049 // all arguments are covered, so mark this as so.
4050 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004051 return false;
4052 }
4053 return true;
4054}
4055
Richard Trieu03cf7b72011-10-28 00:41:25 +00004056template<typename Range>
4057void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
4058 SourceLocation Loc,
4059 bool IsStringLocation,
4060 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00004061 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004062 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00004063 Loc, IsStringLocation, StringRange, FixIt);
4064}
4065
4066/// \brief If the format string is not within the funcion call, emit a note
4067/// so that the function call and string are in diagnostic messages.
4068///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004069/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00004070/// call and only one diagnostic message will be produced. Otherwise, an
4071/// extra note will be emitted pointing to location of the format string.
4072///
4073/// \param ArgumentExpr the expression that is passed as the format string
4074/// argument in the function call. Used for getting locations when two
4075/// diagnostics are emitted.
4076///
4077/// \param PDiag the callee should already have provided any strings for the
4078/// diagnostic message. This function only adds locations and fixits
4079/// to diagnostics.
4080///
4081/// \param Loc primary location for diagnostic. If two diagnostics are
4082/// required, one will be at Loc and a new SourceLocation will be created for
4083/// the other one.
4084///
4085/// \param IsStringLocation if true, Loc points to the format string should be
4086/// used for the note. Otherwise, Loc points to the argument list and will
4087/// be used with PDiag.
4088///
4089/// \param StringRange some or all of the string to highlight. This is
4090/// templated so it can accept either a CharSourceRange or a SourceRange.
4091///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004092/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004093template<typename Range>
4094void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
4095 const Expr *ArgumentExpr,
4096 PartialDiagnostic PDiag,
4097 SourceLocation Loc,
4098 bool IsStringLocation,
4099 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00004100 ArrayRef<FixItHint> FixIt) {
4101 if (InFunctionCall) {
4102 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
4103 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004104 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00004105 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004106 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
4107 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00004108
4109 const Sema::SemaDiagnosticBuilder &Note =
4110 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
4111 diag::note_format_string_defined);
4112
4113 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004114 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004115 }
4116}
4117
Ted Kremenek02087932010-07-16 02:11:22 +00004118//===--- CHECK: Printf format string checking ------------------------------===//
4119
4120namespace {
4121class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004122 bool ObjCContext;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004123
Ted Kremenek02087932010-07-16 02:11:22 +00004124public:
4125 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
4126 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004127 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00004128 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004129 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004130 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004131 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004132 llvm::SmallBitVector &CheckedVarArgs,
4133 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00004134 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4135 numDataArgs, beg, hasVAListArg, Args,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004136 formatIdx, inFunctionCall, CallType, CheckedVarArgs,
4137 UncoveredArg),
Richard Smithd7293d72013-08-05 18:49:43 +00004138 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004139 {}
4140
Ted Kremenek02087932010-07-16 02:11:22 +00004141 bool HandleInvalidPrintfConversionSpecifier(
4142 const analyze_printf::PrintfSpecifier &FS,
4143 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004144 unsigned specifierLen) override;
4145
Ted Kremenek02087932010-07-16 02:11:22 +00004146 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
4147 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004148 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004149 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4150 const char *StartSpecifier,
4151 unsigned SpecifierLen,
4152 const Expr *E);
4153
Ted Kremenek02087932010-07-16 02:11:22 +00004154 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
4155 const char *startSpecifier, unsigned specifierLen);
4156 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
4157 const analyze_printf::OptionalAmount &Amt,
4158 unsigned type,
4159 const char *startSpecifier, unsigned specifierLen);
4160 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
4161 const analyze_printf::OptionalFlag &flag,
4162 const char *startSpecifier, unsigned specifierLen);
4163 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
4164 const analyze_printf::OptionalFlag &ignoredFlag,
4165 const analyze_printf::OptionalFlag &flag,
4166 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004167 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00004168 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00004169
4170 void HandleEmptyObjCModifierFlag(const char *startFlag,
4171 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004172
Ted Kremenek2b417712015-07-02 05:39:16 +00004173 void HandleInvalidObjCModifierFlag(const char *startFlag,
4174 unsigned flagLen) override;
4175
4176 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
4177 const char *flagsEnd,
4178 const char *conversionPosition)
4179 override;
4180};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004181} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00004182
4183bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
4184 const analyze_printf::PrintfSpecifier &FS,
4185 const char *startSpecifier,
4186 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004187 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004188 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004189
Ted Kremenekce815422010-07-19 21:25:57 +00004190 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4191 getLocationOfByte(CS.getStart()),
4192 startSpecifier, specifierLen,
4193 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00004194}
4195
Ted Kremenek02087932010-07-16 02:11:22 +00004196bool CheckPrintfHandler::HandleAmount(
4197 const analyze_format_string::OptionalAmount &Amt,
4198 unsigned k, const char *startSpecifier,
4199 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004200 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004201 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00004202 unsigned argIndex = Amt.getArgIndex();
4203 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004204 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
4205 << k,
4206 getLocationOfByte(Amt.getStart()),
4207 /*IsStringLocation*/true,
4208 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004209 // Don't do any more checking. We will just emit
4210 // spurious errors.
4211 return false;
4212 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004213
Ted Kremenek5739de72010-01-29 01:06:55 +00004214 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00004215 // Although not in conformance with C99, we also allow the argument to be
4216 // an 'unsigned int' as that is a reasonably safe case. GCC also
4217 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00004218 CoveredArgs.set(argIndex);
4219 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004220 if (!Arg)
4221 return false;
4222
Ted Kremenek5739de72010-01-29 01:06:55 +00004223 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004224
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004225 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
4226 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004227
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004228 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004229 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004230 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00004231 << T << Arg->getSourceRange(),
4232 getLocationOfByte(Amt.getStart()),
4233 /*IsStringLocation*/true,
4234 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004235 // Don't do any more checking. We will just emit
4236 // spurious errors.
4237 return false;
4238 }
4239 }
4240 }
4241 return true;
4242}
Ted Kremenek5739de72010-01-29 01:06:55 +00004243
Tom Careb49ec692010-06-17 19:00:27 +00004244void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00004245 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004246 const analyze_printf::OptionalAmount &Amt,
4247 unsigned type,
4248 const char *startSpecifier,
4249 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004250 const analyze_printf::PrintfConversionSpecifier &CS =
4251 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00004252
Richard Trieu03cf7b72011-10-28 00:41:25 +00004253 FixItHint fixit =
4254 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
4255 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
4256 Amt.getConstantLength()))
4257 : FixItHint();
4258
4259 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
4260 << type << CS.toString(),
4261 getLocationOfByte(Amt.getStart()),
4262 /*IsStringLocation*/true,
4263 getSpecifierRange(startSpecifier, specifierLen),
4264 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00004265}
4266
Ted Kremenek02087932010-07-16 02:11:22 +00004267void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004268 const analyze_printf::OptionalFlag &flag,
4269 const char *startSpecifier,
4270 unsigned specifierLen) {
4271 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004272 const analyze_printf::PrintfConversionSpecifier &CS =
4273 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00004274 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
4275 << flag.toString() << CS.toString(),
4276 getLocationOfByte(flag.getPosition()),
4277 /*IsStringLocation*/true,
4278 getSpecifierRange(startSpecifier, specifierLen),
4279 FixItHint::CreateRemoval(
4280 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004281}
4282
4283void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00004284 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004285 const analyze_printf::OptionalFlag &ignoredFlag,
4286 const analyze_printf::OptionalFlag &flag,
4287 const char *startSpecifier,
4288 unsigned specifierLen) {
4289 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004290 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
4291 << ignoredFlag.toString() << flag.toString(),
4292 getLocationOfByte(ignoredFlag.getPosition()),
4293 /*IsStringLocation*/true,
4294 getSpecifierRange(startSpecifier, specifierLen),
4295 FixItHint::CreateRemoval(
4296 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004297}
4298
Ted Kremenek2b417712015-07-02 05:39:16 +00004299// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4300// bool IsStringLocation, Range StringRange,
4301// ArrayRef<FixItHint> Fixit = None);
4302
4303void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
4304 unsigned flagLen) {
4305 // Warn about an empty flag.
4306 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
4307 getLocationOfByte(startFlag),
4308 /*IsStringLocation*/true,
4309 getSpecifierRange(startFlag, flagLen));
4310}
4311
4312void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
4313 unsigned flagLen) {
4314 // Warn about an invalid flag.
4315 auto Range = getSpecifierRange(startFlag, flagLen);
4316 StringRef flag(startFlag, flagLen);
4317 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
4318 getLocationOfByte(startFlag),
4319 /*IsStringLocation*/true,
4320 Range, FixItHint::CreateRemoval(Range));
4321}
4322
4323void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
4324 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
4325 // Warn about using '[...]' without a '@' conversion.
4326 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
4327 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
4328 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
4329 getLocationOfByte(conversionPosition),
4330 /*IsStringLocation*/true,
4331 Range, FixItHint::CreateRemoval(Range));
4332}
4333
Richard Smith55ce3522012-06-25 20:30:08 +00004334// Determines if the specified is a C++ class or struct containing
4335// a member with the specified name and kind (e.g. a CXXMethodDecl named
4336// "c_str()").
4337template<typename MemberKind>
4338static llvm::SmallPtrSet<MemberKind*, 1>
4339CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
4340 const RecordType *RT = Ty->getAs<RecordType>();
4341 llvm::SmallPtrSet<MemberKind*, 1> Results;
4342
4343 if (!RT)
4344 return Results;
4345 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00004346 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00004347 return Results;
4348
Alp Tokerb6cc5922014-05-03 03:45:55 +00004349 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00004350 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00004351 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00004352
4353 // We just need to include all members of the right kind turned up by the
4354 // filter, at this point.
4355 if (S.LookupQualifiedName(R, RT->getDecl()))
4356 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4357 NamedDecl *decl = (*I)->getUnderlyingDecl();
4358 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
4359 Results.insert(FK);
4360 }
4361 return Results;
4362}
4363
Richard Smith2868a732014-02-28 01:36:39 +00004364/// Check if we could call '.c_str()' on an object.
4365///
4366/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
4367/// allow the call, or if it would be ambiguous).
4368bool Sema::hasCStrMethod(const Expr *E) {
4369 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4370 MethodSet Results =
4371 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
4372 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4373 MI != ME; ++MI)
4374 if ((*MI)->getMinRequiredArguments() == 0)
4375 return true;
4376 return false;
4377}
4378
Richard Smith55ce3522012-06-25 20:30:08 +00004379// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004380// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00004381// Returns true when a c_str() conversion method is found.
4382bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00004383 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00004384 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4385
4386 MethodSet Results =
4387 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
4388
4389 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4390 MI != ME; ++MI) {
4391 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00004392 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00004393 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00004394 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00004395 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00004396 S.Diag(E->getLocStart(), diag::note_printf_c_str)
4397 << "c_str()"
4398 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
4399 return true;
4400 }
4401 }
4402
4403 return false;
4404}
4405
Ted Kremenekab278de2010-01-28 23:39:18 +00004406bool
Ted Kremenek02087932010-07-16 02:11:22 +00004407CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00004408 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00004409 const char *startSpecifier,
4410 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004411 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00004412 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004413 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00004414
Ted Kremenek6cd69422010-07-19 22:01:06 +00004415 if (FS.consumesDataArgument()) {
4416 if (atFirstArg) {
4417 atFirstArg = false;
4418 usesPositionalArgs = FS.usesPositionalArg();
4419 }
4420 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004421 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4422 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004423 return false;
4424 }
Ted Kremenek5739de72010-01-29 01:06:55 +00004425 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004426
Ted Kremenekd1668192010-02-27 01:41:03 +00004427 // First check if the field width, precision, and conversion specifier
4428 // have matching data arguments.
4429 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4430 startSpecifier, specifierLen)) {
4431 return false;
4432 }
4433
4434 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4435 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004436 return false;
4437 }
4438
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004439 if (!CS.consumesDataArgument()) {
4440 // FIXME: Technically specifying a precision or field width here
4441 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00004442 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004443 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004444
Ted Kremenek4a49d982010-02-26 19:18:41 +00004445 // Consume the argument.
4446 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00004447 if (argIndex < NumDataArgs) {
4448 // The check to see if the argIndex is valid will come later.
4449 // We set the bit here because we may exit early from this
4450 // function if we encounter some other error.
4451 CoveredArgs.set(argIndex);
4452 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00004453
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004454 // FreeBSD kernel extensions.
4455 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4456 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4457 // We need at least two arguments.
4458 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4459 return false;
4460
4461 // Claim the second argument.
4462 CoveredArgs.set(argIndex + 1);
4463
4464 // Type check the first argument (int for %b, pointer for %D)
4465 const Expr *Ex = getDataArg(argIndex);
4466 const analyze_printf::ArgType &AT =
4467 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4468 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4469 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4470 EmitFormatDiagnostic(
4471 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4472 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4473 << false << Ex->getSourceRange(),
4474 Ex->getLocStart(), /*IsStringLocation*/false,
4475 getSpecifierRange(startSpecifier, specifierLen));
4476
4477 // Type check the second argument (char * for both %b and %D)
4478 Ex = getDataArg(argIndex + 1);
4479 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4480 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4481 EmitFormatDiagnostic(
4482 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4483 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4484 << false << Ex->getSourceRange(),
4485 Ex->getLocStart(), /*IsStringLocation*/false,
4486 getSpecifierRange(startSpecifier, specifierLen));
4487
4488 return true;
4489 }
4490
Ted Kremenek4a49d982010-02-26 19:18:41 +00004491 // Check for using an Objective-C specific conversion specifier
4492 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004493 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00004494 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4495 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00004496 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004497
Tom Careb49ec692010-06-17 19:00:27 +00004498 // Check for invalid use of field width
4499 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00004500 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00004501 startSpecifier, specifierLen);
4502 }
4503
4504 // Check for invalid use of precision
4505 if (!FS.hasValidPrecision()) {
4506 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4507 startSpecifier, specifierLen);
4508 }
4509
4510 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00004511 if (!FS.hasValidThousandsGroupingPrefix())
4512 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004513 if (!FS.hasValidLeadingZeros())
4514 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4515 if (!FS.hasValidPlusPrefix())
4516 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00004517 if (!FS.hasValidSpacePrefix())
4518 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004519 if (!FS.hasValidAlternativeForm())
4520 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4521 if (!FS.hasValidLeftJustified())
4522 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4523
4524 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00004525 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4526 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4527 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004528 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4529 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4530 startSpecifier, specifierLen);
4531
4532 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004533 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004534 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4535 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004536 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004537 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004538 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004539 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4540 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00004541
Jordan Rose92303592012-09-08 04:00:03 +00004542 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4543 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4544
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004545 // The remaining checks depend on the data arguments.
4546 if (HasVAListArg)
4547 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004548
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004549 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004550 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004551
Jordan Rose58bbe422012-07-19 18:10:08 +00004552 const Expr *Arg = getDataArg(argIndex);
4553 if (!Arg)
4554 return true;
4555
4556 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00004557}
4558
Jordan Roseaee34382012-09-05 22:56:26 +00004559static bool requiresParensToAddCast(const Expr *E) {
4560 // FIXME: We should have a general way to reason about operator
4561 // precedence and whether parens are actually needed here.
4562 // Take care of a few common cases where they aren't.
4563 const Expr *Inside = E->IgnoreImpCasts();
4564 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
4565 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
4566
4567 switch (Inside->getStmtClass()) {
4568 case Stmt::ArraySubscriptExprClass:
4569 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004570 case Stmt::CharacterLiteralClass:
4571 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004572 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004573 case Stmt::FloatingLiteralClass:
4574 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004575 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004576 case Stmt::ObjCArrayLiteralClass:
4577 case Stmt::ObjCBoolLiteralExprClass:
4578 case Stmt::ObjCBoxedExprClass:
4579 case Stmt::ObjCDictionaryLiteralClass:
4580 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004581 case Stmt::ObjCIvarRefExprClass:
4582 case Stmt::ObjCMessageExprClass:
4583 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004584 case Stmt::ObjCStringLiteralClass:
4585 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004586 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004587 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004588 case Stmt::UnaryOperatorClass:
4589 return false;
4590 default:
4591 return true;
4592 }
4593}
4594
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004595static std::pair<QualType, StringRef>
4596shouldNotPrintDirectly(const ASTContext &Context,
4597 QualType IntendedTy,
4598 const Expr *E) {
4599 // Use a 'while' to peel off layers of typedefs.
4600 QualType TyTy = IntendedTy;
4601 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
4602 StringRef Name = UserTy->getDecl()->getName();
4603 QualType CastTy = llvm::StringSwitch<QualType>(Name)
4604 .Case("NSInteger", Context.LongTy)
4605 .Case("NSUInteger", Context.UnsignedLongTy)
4606 .Case("SInt32", Context.IntTy)
4607 .Case("UInt32", Context.UnsignedIntTy)
4608 .Default(QualType());
4609
4610 if (!CastTy.isNull())
4611 return std::make_pair(CastTy, Name);
4612
4613 TyTy = UserTy->desugar();
4614 }
4615
4616 // Strip parens if necessary.
4617 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4618 return shouldNotPrintDirectly(Context,
4619 PE->getSubExpr()->getType(),
4620 PE->getSubExpr());
4621
4622 // If this is a conditional expression, then its result type is constructed
4623 // via usual arithmetic conversions and thus there might be no necessary
4624 // typedef sugar there. Recurse to operands to check for NSInteger &
4625 // Co. usage condition.
4626 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4627 QualType TrueTy, FalseTy;
4628 StringRef TrueName, FalseName;
4629
4630 std::tie(TrueTy, TrueName) =
4631 shouldNotPrintDirectly(Context,
4632 CO->getTrueExpr()->getType(),
4633 CO->getTrueExpr());
4634 std::tie(FalseTy, FalseName) =
4635 shouldNotPrintDirectly(Context,
4636 CO->getFalseExpr()->getType(),
4637 CO->getFalseExpr());
4638
4639 if (TrueTy == FalseTy)
4640 return std::make_pair(TrueTy, TrueName);
4641 else if (TrueTy.isNull())
4642 return std::make_pair(FalseTy, FalseName);
4643 else if (FalseTy.isNull())
4644 return std::make_pair(TrueTy, TrueName);
4645 }
4646
4647 return std::make_pair(QualType(), StringRef());
4648}
4649
Richard Smith55ce3522012-06-25 20:30:08 +00004650bool
4651CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4652 const char *StartSpecifier,
4653 unsigned SpecifierLen,
4654 const Expr *E) {
4655 using namespace analyze_format_string;
4656 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004657 // Now type check the data expression that matches the
4658 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004659 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4660 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00004661 if (!AT.isValid())
4662 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00004663
Jordan Rose598ec092012-12-05 18:44:40 +00004664 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00004665 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4666 ExprTy = TET->getUnderlyingExpr()->getType();
4667 }
4668
Seth Cantrellb4802962015-03-04 03:12:10 +00004669 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4670
4671 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00004672 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004673 }
Jordan Rose98709982012-06-04 22:48:57 +00004674
Jordan Rose22b74712012-09-05 22:56:19 +00004675 // Look through argument promotions for our error message's reported type.
4676 // This includes the integral and floating promotions, but excludes array
4677 // and function pointer decay; seeing that an argument intended to be a
4678 // string has type 'char [6]' is probably more confusing than 'char *'.
4679 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4680 if (ICE->getCastKind() == CK_IntegralCast ||
4681 ICE->getCastKind() == CK_FloatingCast) {
4682 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00004683 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00004684
4685 // Check if we didn't match because of an implicit cast from a 'char'
4686 // or 'short' to an 'int'. This is done because printf is a varargs
4687 // function.
4688 if (ICE->getType() == S.Context.IntTy ||
4689 ICE->getType() == S.Context.UnsignedIntTy) {
4690 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00004691 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00004692 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00004693 }
Jordan Rose98709982012-06-04 22:48:57 +00004694 }
Jordan Rose598ec092012-12-05 18:44:40 +00004695 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4696 // Special case for 'a', which has type 'int' in C.
4697 // Note, however, that we do /not/ want to treat multibyte constants like
4698 // 'MooV' as characters! This form is deprecated but still exists.
4699 if (ExprTy == S.Context.IntTy)
4700 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4701 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00004702 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004703
Jordan Rosebc53ed12014-05-31 04:12:14 +00004704 // Look through enums to their underlying type.
4705 bool IsEnum = false;
4706 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4707 ExprTy = EnumTy->getDecl()->getIntegerType();
4708 IsEnum = true;
4709 }
4710
Jordan Rose0e5badd2012-12-05 18:44:49 +00004711 // %C in an Objective-C context prints a unichar, not a wchar_t.
4712 // If the argument is an integer of some kind, believe the %C and suggest
4713 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00004714 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004715 if (ObjCContext &&
4716 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4717 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4718 !ExprTy->isCharType()) {
4719 // 'unichar' is defined as a typedef of unsigned short, but we should
4720 // prefer using the typedef if it is visible.
4721 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00004722
4723 // While we are here, check if the value is an IntegerLiteral that happens
4724 // to be within the valid range.
4725 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4726 const llvm::APInt &V = IL->getValue();
4727 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4728 return true;
4729 }
4730
Jordan Rose0e5badd2012-12-05 18:44:49 +00004731 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4732 Sema::LookupOrdinaryName);
4733 if (S.LookupName(Result, S.getCurScope())) {
4734 NamedDecl *ND = Result.getFoundDecl();
4735 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4736 if (TD->getUnderlyingType() == IntendedTy)
4737 IntendedTy = S.Context.getTypedefType(TD);
4738 }
4739 }
4740 }
4741
4742 // Special-case some of Darwin's platform-independence types by suggesting
4743 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004744 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00004745 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004746 QualType CastTy;
4747 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
4748 if (!CastTy.isNull()) {
4749 IntendedTy = CastTy;
4750 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00004751 }
4752 }
4753
Jordan Rose22b74712012-09-05 22:56:19 +00004754 // We may be able to offer a FixItHint if it is a supported type.
4755 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00004756 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00004757 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004758
Jordan Rose22b74712012-09-05 22:56:19 +00004759 if (success) {
4760 // Get the fix string from the fixed format specifier
4761 SmallString<16> buf;
4762 llvm::raw_svector_ostream os(buf);
4763 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004764
Jordan Roseaee34382012-09-05 22:56:26 +00004765 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4766
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004767 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00004768 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4769 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4770 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4771 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00004772 // In this case, the specifier is wrong and should be changed to match
4773 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00004774 EmitFormatDiagnostic(S.PDiag(diag)
4775 << AT.getRepresentativeTypeName(S.Context)
4776 << IntendedTy << IsEnum << E->getSourceRange(),
4777 E->getLocStart(),
4778 /*IsStringLocation*/ false, SpecRange,
4779 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00004780 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00004781 // The canonical type for formatting this value is different from the
4782 // actual type of the expression. (This occurs, for example, with Darwin's
4783 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
4784 // should be printed as 'long' for 64-bit compatibility.)
4785 // Rather than emitting a normal format/argument mismatch, we want to
4786 // add a cast to the recommended type (and correct the format string
4787 // if necessary).
4788 SmallString<16> CastBuf;
4789 llvm::raw_svector_ostream CastFix(CastBuf);
4790 CastFix << "(";
4791 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
4792 CastFix << ")";
4793
4794 SmallVector<FixItHint,4> Hints;
4795 if (!AT.matchesType(S.Context, IntendedTy))
4796 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
4797
4798 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
4799 // If there's already a cast present, just replace it.
4800 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
4801 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
4802
4803 } else if (!requiresParensToAddCast(E)) {
4804 // If the expression has high enough precedence,
4805 // just write the C-style cast.
4806 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4807 CastFix.str()));
4808 } else {
4809 // Otherwise, add parens around the expression as well as the cast.
4810 CastFix << "(";
4811 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4812 CastFix.str()));
4813
Alp Tokerb6cc5922014-05-03 03:45:55 +00004814 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00004815 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
4816 }
4817
Jordan Rose0e5badd2012-12-05 18:44:49 +00004818 if (ShouldNotPrintDirectly) {
4819 // The expression has a type that should not be printed directly.
4820 // We extract the name from the typedef because we don't want to show
4821 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004822 StringRef Name;
4823 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
4824 Name = TypedefTy->getDecl()->getName();
4825 else
4826 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004827 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00004828 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004829 << E->getSourceRange(),
4830 E->getLocStart(), /*IsStringLocation=*/false,
4831 SpecRange, Hints);
4832 } else {
4833 // In this case, the expression could be printed using a different
4834 // specifier, but we've decided that the specifier is probably correct
4835 // and we should cast instead. Just use the normal warning message.
4836 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00004837 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4838 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004839 << E->getSourceRange(),
4840 E->getLocStart(), /*IsStringLocation*/false,
4841 SpecRange, Hints);
4842 }
Jordan Roseaee34382012-09-05 22:56:26 +00004843 }
Jordan Rose22b74712012-09-05 22:56:19 +00004844 } else {
4845 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
4846 SpecifierLen);
4847 // Since the warning for passing non-POD types to variadic functions
4848 // was deferred until now, we emit a warning for non-POD
4849 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00004850 switch (S.isValidVarArgType(ExprTy)) {
4851 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00004852 case Sema::VAK_ValidInCXX11: {
4853 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4854 if (match == analyze_printf::ArgType::NoMatchPedantic) {
4855 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4856 }
Richard Smithd7293d72013-08-05 18:49:43 +00004857
Seth Cantrellb4802962015-03-04 03:12:10 +00004858 EmitFormatDiagnostic(
4859 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4860 << IsEnum << CSR << E->getSourceRange(),
4861 E->getLocStart(), /*IsStringLocation*/ false, CSR);
4862 break;
4863 }
Richard Smithd7293d72013-08-05 18:49:43 +00004864 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00004865 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00004866 EmitFormatDiagnostic(
4867 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004868 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00004869 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00004870 << CallType
4871 << AT.getRepresentativeTypeName(S.Context)
4872 << CSR
4873 << E->getSourceRange(),
4874 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00004875 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00004876 break;
4877
4878 case Sema::VAK_Invalid:
4879 if (ExprTy->isObjCObjectType())
4880 EmitFormatDiagnostic(
4881 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4882 << S.getLangOpts().CPlusPlus11
4883 << ExprTy
4884 << CallType
4885 << AT.getRepresentativeTypeName(S.Context)
4886 << CSR
4887 << E->getSourceRange(),
4888 E->getLocStart(), /*IsStringLocation*/false, CSR);
4889 else
4890 // FIXME: If this is an initializer list, suggest removing the braces
4891 // or inserting a cast to the target type.
4892 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4893 << isa<InitListExpr>(E) << ExprTy << CallType
4894 << AT.getRepresentativeTypeName(S.Context)
4895 << E->getSourceRange();
4896 break;
4897 }
4898
4899 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4900 "format string specifier index out of range");
4901 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004902 }
4903
Ted Kremenekab278de2010-01-28 23:39:18 +00004904 return true;
4905}
4906
Ted Kremenek02087932010-07-16 02:11:22 +00004907//===--- CHECK: Scanf format string checking ------------------------------===//
4908
4909namespace {
4910class CheckScanfHandler : public CheckFormatHandler {
4911public:
4912 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4913 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004914 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004915 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004916 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004917 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004918 llvm::SmallBitVector &CheckedVarArgs,
4919 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00004920 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4921 numDataArgs, beg, hasVAListArg,
4922 Args, formatIdx, inFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004923 CheckedVarArgs, UncoveredArg)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004924 {}
Ted Kremenek02087932010-07-16 02:11:22 +00004925
4926 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4927 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004928 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00004929
4930 bool HandleInvalidScanfConversionSpecifier(
4931 const analyze_scanf::ScanfSpecifier &FS,
4932 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004933 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004934
Craig Toppere14c0f82014-03-12 04:55:44 +00004935 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00004936};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004937} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004938
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004939void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4940 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004941 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4942 getLocationOfByte(end), /*IsStringLocation*/true,
4943 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004944}
4945
Ted Kremenekce815422010-07-19 21:25:57 +00004946bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4947 const analyze_scanf::ScanfSpecifier &FS,
4948 const char *startSpecifier,
4949 unsigned specifierLen) {
4950
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004951 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004952 FS.getConversionSpecifier();
4953
4954 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4955 getLocationOfByte(CS.getStart()),
4956 startSpecifier, specifierLen,
4957 CS.getStart(), CS.getLength());
4958}
4959
Ted Kremenek02087932010-07-16 02:11:22 +00004960bool CheckScanfHandler::HandleScanfSpecifier(
4961 const analyze_scanf::ScanfSpecifier &FS,
4962 const char *startSpecifier,
4963 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00004964 using namespace analyze_scanf;
4965 using namespace analyze_format_string;
4966
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004967 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004968
Ted Kremenek6cd69422010-07-19 22:01:06 +00004969 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4970 // be used to decide if we are using positional arguments consistently.
4971 if (FS.consumesDataArgument()) {
4972 if (atFirstArg) {
4973 atFirstArg = false;
4974 usesPositionalArgs = FS.usesPositionalArg();
4975 }
4976 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004977 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4978 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004979 return false;
4980 }
Ted Kremenek02087932010-07-16 02:11:22 +00004981 }
4982
4983 // Check if the field with is non-zero.
4984 const OptionalAmount &Amt = FS.getFieldWidth();
4985 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4986 if (Amt.getConstantAmount() == 0) {
4987 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4988 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00004989 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4990 getLocationOfByte(Amt.getStart()),
4991 /*IsStringLocation*/true, R,
4992 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00004993 }
4994 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004995
Ted Kremenek02087932010-07-16 02:11:22 +00004996 if (!FS.consumesDataArgument()) {
4997 // FIXME: Technically specifying a precision or field width here
4998 // makes no sense. Worth issuing a warning at some point.
4999 return true;
5000 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005001
Ted Kremenek02087932010-07-16 02:11:22 +00005002 // Consume the argument.
5003 unsigned argIndex = FS.getArgIndex();
5004 if (argIndex < NumDataArgs) {
5005 // The check to see if the argIndex is valid will come later.
5006 // We set the bit here because we may exit early from this
5007 // function if we encounter some other error.
5008 CoveredArgs.set(argIndex);
5009 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005010
Ted Kremenek4407ea42010-07-20 20:04:47 +00005011 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005012 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005013 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5014 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005015 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005016 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005017 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005018 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5019 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005020
Jordan Rose92303592012-09-08 04:00:03 +00005021 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5022 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5023
Ted Kremenek02087932010-07-16 02:11:22 +00005024 // The remaining checks depend on the data arguments.
5025 if (HasVAListArg)
5026 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005027
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005028 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00005029 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00005030
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005031 // Check that the argument type matches the format specifier.
5032 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005033 if (!Ex)
5034 return true;
5035
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00005036 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00005037
5038 if (!AT.isValid()) {
5039 return true;
5040 }
5041
Seth Cantrellb4802962015-03-04 03:12:10 +00005042 analyze_format_string::ArgType::MatchKind match =
5043 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00005044 if (match == analyze_format_string::ArgType::Match) {
5045 return true;
5046 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005047
Seth Cantrell79340072015-03-04 05:58:08 +00005048 ScanfSpecifier fixedFS = FS;
5049 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
5050 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005051
Seth Cantrell79340072015-03-04 05:58:08 +00005052 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5053 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5054 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5055 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005056
Seth Cantrell79340072015-03-04 05:58:08 +00005057 if (success) {
5058 // Get the fix string from the fixed format specifier.
5059 SmallString<128> buf;
5060 llvm::raw_svector_ostream os(buf);
5061 fixedFS.toString(os);
5062
5063 EmitFormatDiagnostic(
5064 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
5065 << Ex->getType() << false << Ex->getSourceRange(),
5066 Ex->getLocStart(),
5067 /*IsStringLocation*/ false,
5068 getSpecifierRange(startSpecifier, specifierLen),
5069 FixItHint::CreateReplacement(
5070 getSpecifierRange(startSpecifier, specifierLen), os.str()));
5071 } else {
5072 EmitFormatDiagnostic(S.PDiag(diag)
5073 << AT.getRepresentativeTypeName(S.Context)
5074 << Ex->getType() << false << Ex->getSourceRange(),
5075 Ex->getLocStart(),
5076 /*IsStringLocation*/ false,
5077 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005078 }
5079
Ted Kremenek02087932010-07-16 02:11:22 +00005080 return true;
5081}
5082
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005083static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
5084 const Expr *OrigFormatExpr,
5085 ArrayRef<const Expr *> Args,
5086 bool HasVAListArg, unsigned format_idx,
5087 unsigned firstDataArg,
5088 Sema::FormatStringType Type,
5089 bool inFunctionCall,
5090 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005091 llvm::SmallBitVector &CheckedVarArgs,
5092 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00005093 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00005094 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005095 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005096 S, inFunctionCall, Args[format_idx],
5097 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005098 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005099 return;
5100 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005101
Ted Kremenekab278de2010-01-28 23:39:18 +00005102 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005103 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00005104 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005105 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005106 const ConstantArrayType *T =
5107 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005108 assert(T && "String literal not of constant array type!");
5109 size_t TypeSize = T->getSize().getZExtValue();
5110 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005111 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005112
5113 // Emit a warning if the string literal is truncated and does not contain an
5114 // embedded null character.
5115 if (TypeSize <= StrRef.size() &&
5116 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
5117 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005118 S, inFunctionCall, Args[format_idx],
5119 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005120 FExpr->getLocStart(),
5121 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
5122 return;
5123 }
5124
Ted Kremenekab278de2010-01-28 23:39:18 +00005125 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00005126 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005127 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005128 S, inFunctionCall, Args[format_idx],
5129 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005130 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005131 return;
5132 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005133
5134 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
5135 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
5136 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
5137 numDataArgs, (Type == Sema::FST_NSString ||
5138 Type == Sema::FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005139 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005140 inFunctionCall, CallType, CheckedVarArgs,
5141 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005142
Hans Wennborg23926bd2011-12-15 10:25:47 +00005143 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005144 S.getLangOpts(),
5145 S.Context.getTargetInfo(),
5146 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00005147 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005148 } else if (Type == Sema::FST_Scanf) {
5149 CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005150 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005151 inFunctionCall, CallType, CheckedVarArgs,
5152 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005153
Hans Wennborg23926bd2011-12-15 10:25:47 +00005154 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005155 S.getLangOpts(),
5156 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00005157 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005158 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00005159}
5160
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00005161bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
5162 // Str - The format string. NOTE: this is NOT null-terminated!
5163 StringRef StrRef = FExpr->getString();
5164 const char *Str = StrRef.data();
5165 // Account for cases where the string literal is truncated in a declaration.
5166 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
5167 assert(T && "String literal not of constant array type!");
5168 size_t TypeSize = T->getSize().getZExtValue();
5169 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5170 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
5171 getLangOpts(),
5172 Context.getTargetInfo());
5173}
5174
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005175//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
5176
5177// Returns the related absolute value function that is larger, of 0 if one
5178// does not exist.
5179static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
5180 switch (AbsFunction) {
5181 default:
5182 return 0;
5183
5184 case Builtin::BI__builtin_abs:
5185 return Builtin::BI__builtin_labs;
5186 case Builtin::BI__builtin_labs:
5187 return Builtin::BI__builtin_llabs;
5188 case Builtin::BI__builtin_llabs:
5189 return 0;
5190
5191 case Builtin::BI__builtin_fabsf:
5192 return Builtin::BI__builtin_fabs;
5193 case Builtin::BI__builtin_fabs:
5194 return Builtin::BI__builtin_fabsl;
5195 case Builtin::BI__builtin_fabsl:
5196 return 0;
5197
5198 case Builtin::BI__builtin_cabsf:
5199 return Builtin::BI__builtin_cabs;
5200 case Builtin::BI__builtin_cabs:
5201 return Builtin::BI__builtin_cabsl;
5202 case Builtin::BI__builtin_cabsl:
5203 return 0;
5204
5205 case Builtin::BIabs:
5206 return Builtin::BIlabs;
5207 case Builtin::BIlabs:
5208 return Builtin::BIllabs;
5209 case Builtin::BIllabs:
5210 return 0;
5211
5212 case Builtin::BIfabsf:
5213 return Builtin::BIfabs;
5214 case Builtin::BIfabs:
5215 return Builtin::BIfabsl;
5216 case Builtin::BIfabsl:
5217 return 0;
5218
5219 case Builtin::BIcabsf:
5220 return Builtin::BIcabs;
5221 case Builtin::BIcabs:
5222 return Builtin::BIcabsl;
5223 case Builtin::BIcabsl:
5224 return 0;
5225 }
5226}
5227
5228// Returns the argument type of the absolute value function.
5229static QualType getAbsoluteValueArgumentType(ASTContext &Context,
5230 unsigned AbsType) {
5231 if (AbsType == 0)
5232 return QualType();
5233
5234 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
5235 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
5236 if (Error != ASTContext::GE_None)
5237 return QualType();
5238
5239 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
5240 if (!FT)
5241 return QualType();
5242
5243 if (FT->getNumParams() != 1)
5244 return QualType();
5245
5246 return FT->getParamType(0);
5247}
5248
5249// Returns the best absolute value function, or zero, based on type and
5250// current absolute value function.
5251static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
5252 unsigned AbsFunctionKind) {
5253 unsigned BestKind = 0;
5254 uint64_t ArgSize = Context.getTypeSize(ArgType);
5255 for (unsigned Kind = AbsFunctionKind; Kind != 0;
5256 Kind = getLargerAbsoluteValueFunction(Kind)) {
5257 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
5258 if (Context.getTypeSize(ParamType) >= ArgSize) {
5259 if (BestKind == 0)
5260 BestKind = Kind;
5261 else if (Context.hasSameType(ParamType, ArgType)) {
5262 BestKind = Kind;
5263 break;
5264 }
5265 }
5266 }
5267 return BestKind;
5268}
5269
5270enum AbsoluteValueKind {
5271 AVK_Integer,
5272 AVK_Floating,
5273 AVK_Complex
5274};
5275
5276static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
5277 if (T->isIntegralOrEnumerationType())
5278 return AVK_Integer;
5279 if (T->isRealFloatingType())
5280 return AVK_Floating;
5281 if (T->isAnyComplexType())
5282 return AVK_Complex;
5283
5284 llvm_unreachable("Type not integer, floating, or complex");
5285}
5286
5287// Changes the absolute value function to a different type. Preserves whether
5288// the function is a builtin.
5289static unsigned changeAbsFunction(unsigned AbsKind,
5290 AbsoluteValueKind ValueKind) {
5291 switch (ValueKind) {
5292 case AVK_Integer:
5293 switch (AbsKind) {
5294 default:
5295 return 0;
5296 case Builtin::BI__builtin_fabsf:
5297 case Builtin::BI__builtin_fabs:
5298 case Builtin::BI__builtin_fabsl:
5299 case Builtin::BI__builtin_cabsf:
5300 case Builtin::BI__builtin_cabs:
5301 case Builtin::BI__builtin_cabsl:
5302 return Builtin::BI__builtin_abs;
5303 case Builtin::BIfabsf:
5304 case Builtin::BIfabs:
5305 case Builtin::BIfabsl:
5306 case Builtin::BIcabsf:
5307 case Builtin::BIcabs:
5308 case Builtin::BIcabsl:
5309 return Builtin::BIabs;
5310 }
5311 case AVK_Floating:
5312 switch (AbsKind) {
5313 default:
5314 return 0;
5315 case Builtin::BI__builtin_abs:
5316 case Builtin::BI__builtin_labs:
5317 case Builtin::BI__builtin_llabs:
5318 case Builtin::BI__builtin_cabsf:
5319 case Builtin::BI__builtin_cabs:
5320 case Builtin::BI__builtin_cabsl:
5321 return Builtin::BI__builtin_fabsf;
5322 case Builtin::BIabs:
5323 case Builtin::BIlabs:
5324 case Builtin::BIllabs:
5325 case Builtin::BIcabsf:
5326 case Builtin::BIcabs:
5327 case Builtin::BIcabsl:
5328 return Builtin::BIfabsf;
5329 }
5330 case AVK_Complex:
5331 switch (AbsKind) {
5332 default:
5333 return 0;
5334 case Builtin::BI__builtin_abs:
5335 case Builtin::BI__builtin_labs:
5336 case Builtin::BI__builtin_llabs:
5337 case Builtin::BI__builtin_fabsf:
5338 case Builtin::BI__builtin_fabs:
5339 case Builtin::BI__builtin_fabsl:
5340 return Builtin::BI__builtin_cabsf;
5341 case Builtin::BIabs:
5342 case Builtin::BIlabs:
5343 case Builtin::BIllabs:
5344 case Builtin::BIfabsf:
5345 case Builtin::BIfabs:
5346 case Builtin::BIfabsl:
5347 return Builtin::BIcabsf;
5348 }
5349 }
5350 llvm_unreachable("Unable to convert function");
5351}
5352
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00005353static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005354 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
5355 if (!FnInfo)
5356 return 0;
5357
5358 switch (FDecl->getBuiltinID()) {
5359 default:
5360 return 0;
5361 case Builtin::BI__builtin_abs:
5362 case Builtin::BI__builtin_fabs:
5363 case Builtin::BI__builtin_fabsf:
5364 case Builtin::BI__builtin_fabsl:
5365 case Builtin::BI__builtin_labs:
5366 case Builtin::BI__builtin_llabs:
5367 case Builtin::BI__builtin_cabs:
5368 case Builtin::BI__builtin_cabsf:
5369 case Builtin::BI__builtin_cabsl:
5370 case Builtin::BIabs:
5371 case Builtin::BIlabs:
5372 case Builtin::BIllabs:
5373 case Builtin::BIfabs:
5374 case Builtin::BIfabsf:
5375 case Builtin::BIfabsl:
5376 case Builtin::BIcabs:
5377 case Builtin::BIcabsf:
5378 case Builtin::BIcabsl:
5379 return FDecl->getBuiltinID();
5380 }
5381 llvm_unreachable("Unknown Builtin type");
5382}
5383
5384// If the replacement is valid, emit a note with replacement function.
5385// Additionally, suggest including the proper header if not already included.
5386static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00005387 unsigned AbsKind, QualType ArgType) {
5388 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00005389 const char *HeaderName = nullptr;
5390 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005391 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
5392 FunctionName = "std::abs";
5393 if (ArgType->isIntegralOrEnumerationType()) {
5394 HeaderName = "cstdlib";
5395 } else if (ArgType->isRealFloatingType()) {
5396 HeaderName = "cmath";
5397 } else {
5398 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005399 }
Richard Trieubeffb832014-04-15 23:47:53 +00005400
5401 // Lookup all std::abs
5402 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00005403 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00005404 R.suppressDiagnostics();
5405 S.LookupQualifiedName(R, Std);
5406
5407 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005408 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005409 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
5410 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
5411 } else {
5412 FDecl = dyn_cast<FunctionDecl>(I);
5413 }
5414 if (!FDecl)
5415 continue;
5416
5417 // Found std::abs(), check that they are the right ones.
5418 if (FDecl->getNumParams() != 1)
5419 continue;
5420
5421 // Check that the parameter type can handle the argument.
5422 QualType ParamType = FDecl->getParamDecl(0)->getType();
5423 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
5424 S.Context.getTypeSize(ArgType) <=
5425 S.Context.getTypeSize(ParamType)) {
5426 // Found a function, don't need the header hint.
5427 EmitHeaderHint = false;
5428 break;
5429 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005430 }
Richard Trieubeffb832014-04-15 23:47:53 +00005431 }
5432 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00005433 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00005434 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5435
5436 if (HeaderName) {
5437 DeclarationName DN(&S.Context.Idents.get(FunctionName));
5438 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5439 R.suppressDiagnostics();
5440 S.LookupName(R, S.getCurScope());
5441
5442 if (R.isSingleResult()) {
5443 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5444 if (FD && FD->getBuiltinID() == AbsKind) {
5445 EmitHeaderHint = false;
5446 } else {
5447 return;
5448 }
5449 } else if (!R.empty()) {
5450 return;
5451 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005452 }
5453 }
5454
5455 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00005456 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005457
Richard Trieubeffb832014-04-15 23:47:53 +00005458 if (!HeaderName)
5459 return;
5460
5461 if (!EmitHeaderHint)
5462 return;
5463
Alp Toker5d96e0a2014-07-11 20:53:51 +00005464 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5465 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00005466}
5467
5468static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5469 if (!FDecl)
5470 return false;
5471
5472 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5473 return false;
5474
5475 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5476
5477 while (ND && ND->isInlineNamespace()) {
5478 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005479 }
Richard Trieubeffb832014-04-15 23:47:53 +00005480
5481 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5482 return false;
5483
5484 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5485 return false;
5486
5487 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005488}
5489
5490// Warn when using the wrong abs() function.
5491void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5492 const FunctionDecl *FDecl,
5493 IdentifierInfo *FnInfo) {
5494 if (Call->getNumArgs() != 1)
5495 return;
5496
5497 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00005498 bool IsStdAbs = IsFunctionStdAbs(FDecl);
5499 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005500 return;
5501
5502 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5503 QualType ParamType = Call->getArg(0)->getType();
5504
Alp Toker5d96e0a2014-07-11 20:53:51 +00005505 // Unsigned types cannot be negative. Suggest removing the absolute value
5506 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005507 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00005508 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00005509 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005510 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5511 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00005512 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005513 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5514 return;
5515 }
5516
David Majnemer7f77eb92015-11-15 03:04:34 +00005517 // Taking the absolute value of a pointer is very suspicious, they probably
5518 // wanted to index into an array, dereference a pointer, call a function, etc.
5519 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
5520 unsigned DiagType = 0;
5521 if (ArgType->isFunctionType())
5522 DiagType = 1;
5523 else if (ArgType->isArrayType())
5524 DiagType = 2;
5525
5526 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
5527 return;
5528 }
5529
Richard Trieubeffb832014-04-15 23:47:53 +00005530 // std::abs has overloads which prevent most of the absolute value problems
5531 // from occurring.
5532 if (IsStdAbs)
5533 return;
5534
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005535 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5536 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5537
5538 // The argument and parameter are the same kind. Check if they are the right
5539 // size.
5540 if (ArgValueKind == ParamValueKind) {
5541 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
5542 return;
5543
5544 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
5545 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
5546 << FDecl << ArgType << ParamType;
5547
5548 if (NewAbsKind == 0)
5549 return;
5550
5551 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005552 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005553 return;
5554 }
5555
5556 // ArgValueKind != ParamValueKind
5557 // The wrong type of absolute value function was used. Attempt to find the
5558 // proper one.
5559 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
5560 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
5561 if (NewAbsKind == 0)
5562 return;
5563
5564 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
5565 << FDecl << ParamValueKind << ArgValueKind;
5566
5567 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005568 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005569}
5570
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005571//===--- CHECK: Standard memory functions ---------------------------------===//
5572
Nico Weber0e6daef2013-12-26 23:38:39 +00005573/// \brief Takes the expression passed to the size_t parameter of functions
5574/// such as memcmp, strncat, etc and warns if it's a comparison.
5575///
5576/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
5577static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
5578 IdentifierInfo *FnName,
5579 SourceLocation FnLoc,
5580 SourceLocation RParenLoc) {
5581 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
5582 if (!Size)
5583 return false;
5584
5585 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
5586 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
5587 return false;
5588
Nico Weber0e6daef2013-12-26 23:38:39 +00005589 SourceRange SizeRange = Size->getSourceRange();
5590 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
5591 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00005592 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005593 << FnName << FixItHint::CreateInsertion(
5594 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00005595 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00005596 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00005597 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00005598 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
5599 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00005600
5601 return true;
5602}
5603
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005604/// \brief Determine whether the given type is or contains a dynamic class type
5605/// (e.g., whether it has a vtable).
5606static const CXXRecordDecl *getContainedDynamicClass(QualType T,
5607 bool &IsContained) {
5608 // Look through array types while ignoring qualifiers.
5609 const Type *Ty = T->getBaseElementTypeUnsafe();
5610 IsContained = false;
5611
5612 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5613 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00005614 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005615 return nullptr;
5616
5617 if (RD->isDynamicClass())
5618 return RD;
5619
5620 // Check all the fields. If any bases were dynamic, the class is dynamic.
5621 // It's impossible for a class to transitively contain itself by value, so
5622 // infinite recursion is impossible.
5623 for (auto *FD : RD->fields()) {
5624 bool SubContained;
5625 if (const CXXRecordDecl *ContainedRD =
5626 getContainedDynamicClass(FD->getType(), SubContained)) {
5627 IsContained = true;
5628 return ContainedRD;
5629 }
5630 }
5631
5632 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00005633}
5634
Chandler Carruth889ed862011-06-21 23:04:20 +00005635/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005636/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00005637static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00005638 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005639 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5640 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5641 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005642
Craig Topperc3ec1492014-05-26 06:22:03 +00005643 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005644}
5645
Chandler Carruth889ed862011-06-21 23:04:20 +00005646/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00005647static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005648 if (const UnaryExprOrTypeTraitExpr *SizeOf =
5649 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5650 if (SizeOf->getKind() == clang::UETT_SizeOf)
5651 return SizeOf->getTypeOfArgument();
5652
5653 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00005654}
5655
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005656/// \brief Check for dangerous or invalid arguments to memset().
5657///
Chandler Carruthac687262011-06-03 06:23:57 +00005658/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005659/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5660/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005661///
5662/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005663void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00005664 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005665 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00005666 assert(BId != 0);
5667
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005668 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00005669 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00005670 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00005671 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005672 return;
5673
Anna Zaks22122702012-01-17 00:37:07 +00005674 unsigned LastArg = (BId == Builtin::BImemset ||
5675 BId == Builtin::BIstrndup ? 1 : 2);
5676 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00005677 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005678
Nico Weber0e6daef2013-12-26 23:38:39 +00005679 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5680 Call->getLocStart(), Call->getRParenLoc()))
5681 return;
5682
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005683 // We have special checking when the length is a sizeof expression.
5684 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5685 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5686 llvm::FoldingSetNodeID SizeOfArgID;
5687
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005688 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5689 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005690 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005691
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005692 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00005693 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005694 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00005695 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00005696
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005697 // Never warn about void type pointers. This can be used to suppress
5698 // false positives.
5699 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005700 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005701
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005702 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5703 // actually comparing the expressions for equality. Because computing the
5704 // expression IDs can be expensive, we only do this if the diagnostic is
5705 // enabled.
5706 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005707 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5708 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005709 // We only compute IDs for expressions if the warning is enabled, and
5710 // cache the sizeof arg's ID.
5711 if (SizeOfArgID == llvm::FoldingSetNodeID())
5712 SizeOfArg->Profile(SizeOfArgID, Context, true);
5713 llvm::FoldingSetNodeID DestID;
5714 Dest->Profile(DestID, Context, true);
5715 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00005716 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5717 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005718 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00005719 StringRef ReadableName = FnName->getName();
5720
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005721 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00005722 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005723 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00005724 if (!PointeeTy->isIncompleteType() &&
5725 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005726 ActionIdx = 2; // If the pointee's size is sizeof(char),
5727 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00005728
5729 // If the function is defined as a builtin macro, do not show macro
5730 // expansion.
5731 SourceLocation SL = SizeOfArg->getExprLoc();
5732 SourceRange DSR = Dest->getSourceRange();
5733 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005734 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00005735
5736 if (SM.isMacroArgExpansion(SL)) {
5737 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5738 SL = SM.getSpellingLoc(SL);
5739 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5740 SM.getSpellingLoc(DSR.getEnd()));
5741 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5742 SM.getSpellingLoc(SSR.getEnd()));
5743 }
5744
Anna Zaksd08d9152012-05-30 23:14:52 +00005745 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005746 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00005747 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00005748 << PointeeTy
5749 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00005750 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00005751 << SSR);
5752 DiagRuntimeBehavior(SL, SizeOfArg,
5753 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5754 << ActionIdx
5755 << SSR);
5756
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005757 break;
5758 }
5759 }
5760
5761 // Also check for cases where the sizeof argument is the exact same
5762 // type as the memory argument, and where it points to a user-defined
5763 // record type.
5764 if (SizeOfArgTy != QualType()) {
5765 if (PointeeTy->isRecordType() &&
5766 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
5767 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
5768 PDiag(diag::warn_sizeof_pointer_type_memaccess)
5769 << FnName << SizeOfArgTy << ArgIdx
5770 << PointeeTy << Dest->getSourceRange()
5771 << LenExpr->getSourceRange());
5772 break;
5773 }
Nico Weberc5e73862011-06-14 16:14:58 +00005774 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00005775 } else if (DestTy->isArrayType()) {
5776 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00005777 }
Nico Weberc5e73862011-06-14 16:14:58 +00005778
Nico Weberc44b35e2015-03-21 17:37:46 +00005779 if (PointeeTy == QualType())
5780 continue;
Anna Zaks22122702012-01-17 00:37:07 +00005781
Nico Weberc44b35e2015-03-21 17:37:46 +00005782 // Always complain about dynamic classes.
5783 bool IsContained;
5784 if (const CXXRecordDecl *ContainedRD =
5785 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00005786
Nico Weberc44b35e2015-03-21 17:37:46 +00005787 unsigned OperationType = 0;
5788 // "overwritten" if we're warning about the destination for any call
5789 // but memcmp; otherwise a verb appropriate to the call.
5790 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
5791 if (BId == Builtin::BImemcpy)
5792 OperationType = 1;
5793 else if(BId == Builtin::BImemmove)
5794 OperationType = 2;
5795 else if (BId == Builtin::BImemcmp)
5796 OperationType = 3;
5797 }
5798
John McCall31168b02011-06-15 23:02:42 +00005799 DiagRuntimeBehavior(
5800 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00005801 PDiag(diag::warn_dyn_class_memaccess)
5802 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
5803 << FnName << IsContained << ContainedRD << OperationType
5804 << Call->getCallee()->getSourceRange());
5805 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
5806 BId != Builtin::BImemset)
5807 DiagRuntimeBehavior(
5808 Dest->getExprLoc(), Dest,
5809 PDiag(diag::warn_arc_object_memaccess)
5810 << ArgIdx << FnName << PointeeTy
5811 << Call->getCallee()->getSourceRange());
5812 else
5813 continue;
5814
5815 DiagRuntimeBehavior(
5816 Dest->getExprLoc(), Dest,
5817 PDiag(diag::note_bad_memaccess_silence)
5818 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
5819 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005820 }
5821}
5822
Ted Kremenek6865f772011-08-18 20:55:45 +00005823// A little helper routine: ignore addition and subtraction of integer literals.
5824// This intentionally does not ignore all integer constant expressions because
5825// we don't want to remove sizeof().
5826static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
5827 Ex = Ex->IgnoreParenCasts();
5828
5829 for (;;) {
5830 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
5831 if (!BO || !BO->isAdditiveOp())
5832 break;
5833
5834 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
5835 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
5836
5837 if (isa<IntegerLiteral>(RHS))
5838 Ex = LHS;
5839 else if (isa<IntegerLiteral>(LHS))
5840 Ex = RHS;
5841 else
5842 break;
5843 }
5844
5845 return Ex;
5846}
5847
Anna Zaks13b08572012-08-08 21:42:23 +00005848static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
5849 ASTContext &Context) {
5850 // Only handle constant-sized or VLAs, but not flexible members.
5851 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
5852 // Only issue the FIXIT for arrays of size > 1.
5853 if (CAT->getSize().getSExtValue() <= 1)
5854 return false;
5855 } else if (!Ty->isVariableArrayType()) {
5856 return false;
5857 }
5858 return true;
5859}
5860
Ted Kremenek6865f772011-08-18 20:55:45 +00005861// Warn if the user has made the 'size' argument to strlcpy or strlcat
5862// be the size of the source, instead of the destination.
5863void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
5864 IdentifierInfo *FnName) {
5865
5866 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00005867 unsigned NumArgs = Call->getNumArgs();
5868 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00005869 return;
5870
5871 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5872 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00005873 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00005874
5875 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5876 Call->getLocStart(), Call->getRParenLoc()))
5877 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00005878
5879 // Look for 'strlcpy(dst, x, sizeof(x))'
5880 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5881 CompareWithSrc = Ex;
5882 else {
5883 // Look for 'strlcpy(dst, x, strlen(x))'
5884 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00005885 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5886 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00005887 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5888 }
5889 }
5890
5891 if (!CompareWithSrc)
5892 return;
5893
5894 // Determine if the argument to sizeof/strlen is equal to the source
5895 // argument. In principle there's all kinds of things you could do
5896 // here, for instance creating an == expression and evaluating it with
5897 // EvaluateAsBooleanCondition, but this uses a more direct technique:
5898 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5899 if (!SrcArgDRE)
5900 return;
5901
5902 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5903 if (!CompareWithSrcDRE ||
5904 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5905 return;
5906
5907 const Expr *OriginalSizeArg = Call->getArg(2);
5908 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5909 << OriginalSizeArg->getSourceRange() << FnName;
5910
5911 // Output a FIXIT hint if the destination is an array (rather than a
5912 // pointer to an array). This could be enhanced to handle some
5913 // pointers if we know the actual size, like if DstArg is 'array+2'
5914 // we could say 'sizeof(array)-2'.
5915 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00005916 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00005917 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005918
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005919 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005920 llvm::raw_svector_ostream OS(sizeString);
5921 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005922 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00005923 OS << ")";
5924
5925 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5926 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5927 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00005928}
5929
Anna Zaks314cd092012-02-01 19:08:57 +00005930/// Check if two expressions refer to the same declaration.
5931static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5932 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5933 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5934 return D1->getDecl() == D2->getDecl();
5935 return false;
5936}
5937
5938static const Expr *getStrlenExprArg(const Expr *E) {
5939 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5940 const FunctionDecl *FD = CE->getDirectCallee();
5941 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00005942 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005943 return CE->getArg(0)->IgnoreParenCasts();
5944 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005945 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005946}
5947
5948// Warn on anti-patterns as the 'size' argument to strncat.
5949// The correct size argument should look like following:
5950// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5951void Sema::CheckStrncatArguments(const CallExpr *CE,
5952 IdentifierInfo *FnName) {
5953 // Don't crash if the user has the wrong number of arguments.
5954 if (CE->getNumArgs() < 3)
5955 return;
5956 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5957 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5958 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5959
Nico Weber0e6daef2013-12-26 23:38:39 +00005960 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5961 CE->getRParenLoc()))
5962 return;
5963
Anna Zaks314cd092012-02-01 19:08:57 +00005964 // Identify common expressions, which are wrongly used as the size argument
5965 // to strncat and may lead to buffer overflows.
5966 unsigned PatternType = 0;
5967 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5968 // - sizeof(dst)
5969 if (referToTheSameDecl(SizeOfArg, DstArg))
5970 PatternType = 1;
5971 // - sizeof(src)
5972 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5973 PatternType = 2;
5974 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5975 if (BE->getOpcode() == BO_Sub) {
5976 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5977 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5978 // - sizeof(dst) - strlen(dst)
5979 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5980 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5981 PatternType = 1;
5982 // - sizeof(src) - (anything)
5983 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5984 PatternType = 2;
5985 }
5986 }
5987
5988 if (PatternType == 0)
5989 return;
5990
Anna Zaks5069aa32012-02-03 01:27:37 +00005991 // Generate the diagnostic.
5992 SourceLocation SL = LenArg->getLocStart();
5993 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005994 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00005995
5996 // If the function is defined as a builtin macro, do not show macro expansion.
5997 if (SM.isMacroArgExpansion(SL)) {
5998 SL = SM.getSpellingLoc(SL);
5999 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
6000 SM.getSpellingLoc(SR.getEnd()));
6001 }
6002
Anna Zaks13b08572012-08-08 21:42:23 +00006003 // Check if the destination is an array (rather than a pointer to an array).
6004 QualType DstTy = DstArg->getType();
6005 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
6006 Context);
6007 if (!isKnownSizeArray) {
6008 if (PatternType == 1)
6009 Diag(SL, diag::warn_strncat_wrong_size) << SR;
6010 else
6011 Diag(SL, diag::warn_strncat_src_size) << SR;
6012 return;
6013 }
6014
Anna Zaks314cd092012-02-01 19:08:57 +00006015 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00006016 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006017 else
Anna Zaks5069aa32012-02-03 01:27:37 +00006018 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006019
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006020 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00006021 llvm::raw_svector_ostream OS(sizeString);
6022 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006023 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006024 OS << ") - ";
6025 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006026 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006027 OS << ") - 1";
6028
Anna Zaks5069aa32012-02-03 01:27:37 +00006029 Diag(SL, diag::note_strncat_wrong_size)
6030 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00006031}
6032
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006033//===--- CHECK: Return Address of Stack Variable --------------------------===//
6034
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006035static const Expr *EvalVal(const Expr *E,
6036 SmallVectorImpl<const DeclRefExpr *> &refVars,
6037 const Decl *ParentDecl);
6038static const Expr *EvalAddr(const Expr *E,
6039 SmallVectorImpl<const DeclRefExpr *> &refVars,
6040 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006041
6042/// CheckReturnStackAddr - Check if a return statement returns the address
6043/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006044static void
6045CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
6046 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00006047
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006048 const Expr *stackE = nullptr;
6049 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006050
6051 // Perform checking for returned stack addresses, local blocks,
6052 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00006053 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006054 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006055 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00006056 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006057 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006058 }
6059
Craig Topperc3ec1492014-05-26 06:22:03 +00006060 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006061 return; // Nothing suspicious was found.
6062
6063 SourceLocation diagLoc;
6064 SourceRange diagRange;
6065 if (refVars.empty()) {
6066 diagLoc = stackE->getLocStart();
6067 diagRange = stackE->getSourceRange();
6068 } else {
6069 // We followed through a reference variable. 'stackE' contains the
6070 // problematic expression but we will warn at the return statement pointing
6071 // at the reference variable. We will later display the "trail" of
6072 // reference variables using notes.
6073 diagLoc = refVars[0]->getLocStart();
6074 diagRange = refVars[0]->getSourceRange();
6075 }
6076
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006077 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
6078 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00006079 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006080 << DR->getDecl()->getDeclName() << diagRange;
6081 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006082 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006083 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006084 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006085 } else { // local temporary.
Craig Topperda7b27f2015-11-17 05:40:09 +00006086 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
6087 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006088 }
6089
6090 // Display the "trail" of reference variables that we followed until we
6091 // found the problematic expression using notes.
6092 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006093 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006094 // If this var binds to another reference var, show the range of the next
6095 // var, otherwise the var binds to the problematic expression, in which case
6096 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006097 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
6098 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006099 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
6100 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006101 }
6102}
6103
6104/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
6105/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006106/// to a location on the stack, a local block, an address of a label, or a
6107/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006108/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006109/// encounter a subexpression that (1) clearly does not lead to one of the
6110/// above problematic expressions (2) is something we cannot determine leads to
6111/// a problematic expression based on such local checking.
6112///
6113/// Both EvalAddr and EvalVal follow through reference variables to evaluate
6114/// the expression that they point to. Such variables are added to the
6115/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006116///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00006117/// EvalAddr processes expressions that are pointers that are used as
6118/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006119/// At the base case of the recursion is a check for the above problematic
6120/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006121///
6122/// This implementation handles:
6123///
6124/// * pointer-to-pointer casts
6125/// * implicit conversions from array references to pointers
6126/// * taking the address of fields
6127/// * arbitrary interplay between "&" and "*" operators
6128/// * pointer arithmetic from an address of a stack variable
6129/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006130static const Expr *EvalAddr(const Expr *E,
6131 SmallVectorImpl<const DeclRefExpr *> &refVars,
6132 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006133 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00006134 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006135
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006136 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00006137 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00006138 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006139 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00006140 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00006141
Peter Collingbourne91147592011-04-15 00:35:48 +00006142 E = E->IgnoreParens();
6143
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006144 // Our "symbolic interpreter" is just a dispatch off the currently
6145 // viewed AST node. We then recursively traverse the AST by calling
6146 // EvalAddr and EvalVal appropriately.
6147 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006148 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006149 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006150
Richard Smith40f08eb2014-01-30 22:05:38 +00006151 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00006152 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00006153 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00006154
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006155 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006156 // If this is a reference variable, follow through to the expression that
6157 // it points to.
6158 if (V->hasLocalStorage() &&
6159 V->getType()->isReferenceType() && V->hasInit()) {
6160 // Add the reference variable to the "trail".
6161 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006162 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006163 }
6164
Craig Topperc3ec1492014-05-26 06:22:03 +00006165 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006166 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006167
Chris Lattner934edb22007-12-28 05:31:15 +00006168 case Stmt::UnaryOperatorClass: {
6169 // The only unary operator that make sense to handle here
6170 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006171 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006172
John McCalle3027922010-08-25 11:45:40 +00006173 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006174 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006175 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006176 }
Mike Stump11289f42009-09-09 15:08:12 +00006177
Chris Lattner934edb22007-12-28 05:31:15 +00006178 case Stmt::BinaryOperatorClass: {
6179 // Handle pointer arithmetic. All other binary operators are not valid
6180 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006181 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00006182 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00006183
John McCalle3027922010-08-25 11:45:40 +00006184 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00006185 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006186
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006187 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00006188
6189 // Determine which argument is the real pointer base. It could be
6190 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006191 if (!Base->getType()->isPointerType())
6192 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00006193
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006194 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006195 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006196 }
Steve Naroff2752a172008-09-10 19:17:48 +00006197
Chris Lattner934edb22007-12-28 05:31:15 +00006198 // For conditional operators we need to see if either the LHS or RHS are
6199 // valid DeclRefExpr*s. If one of them is valid, we return it.
6200 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006201 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006202
Chris Lattner934edb22007-12-28 05:31:15 +00006203 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006204 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006205 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006206 // In C++, we can have a throw-expression, which has 'void' type.
6207 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006208 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006209 return LHS;
6210 }
Chris Lattner934edb22007-12-28 05:31:15 +00006211
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006212 // In C++, we can have a throw-expression, which has 'void' type.
6213 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00006214 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006215
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006216 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006217 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006218
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006219 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00006220 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006221 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00006222 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006223
6224 case Stmt::AddrLabelExprClass:
6225 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00006226
John McCall28fc7092011-11-10 05:35:25 +00006227 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006228 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6229 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00006230
Ted Kremenekc3b4c522008-08-07 00:49:01 +00006231 // For casts, we need to handle conversions from arrays to
6232 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00006233 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00006234 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00006235 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00006236 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00006237 case Stmt::CXXStaticCastExprClass:
6238 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00006239 case Stmt::CXXConstCastExprClass:
6240 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006241 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00006242 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00006243 case CK_LValueToRValue:
6244 case CK_NoOp:
6245 case CK_BaseToDerived:
6246 case CK_DerivedToBase:
6247 case CK_UncheckedDerivedToBase:
6248 case CK_Dynamic:
6249 case CK_CPointerToObjCPointerCast:
6250 case CK_BlockPointerToObjCPointerCast:
6251 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006252 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006253
6254 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006255 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006256
Richard Trieudadefde2014-07-02 04:39:38 +00006257 case CK_BitCast:
6258 if (SubExpr->getType()->isAnyPointerType() ||
6259 SubExpr->getType()->isBlockPointerType() ||
6260 SubExpr->getType()->isObjCQualifiedIdType())
6261 return EvalAddr(SubExpr, refVars, ParentDecl);
6262 else
6263 return nullptr;
6264
Eli Friedman8195ad72012-02-23 23:04:32 +00006265 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006266 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00006267 }
Chris Lattner934edb22007-12-28 05:31:15 +00006268 }
Mike Stump11289f42009-09-09 15:08:12 +00006269
Douglas Gregorfe314812011-06-21 17:03:29 +00006270 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006271 if (const Expr *Result =
6272 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6273 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00006274 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00006275 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006276
Chris Lattner934edb22007-12-28 05:31:15 +00006277 // Everything else: we simply don't reason about them.
6278 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006279 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00006280 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006281}
Mike Stump11289f42009-09-09 15:08:12 +00006282
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006283/// EvalVal - This function is complements EvalAddr in the mutual recursion.
6284/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006285static const Expr *EvalVal(const Expr *E,
6286 SmallVectorImpl<const DeclRefExpr *> &refVars,
6287 const Decl *ParentDecl) {
6288 do {
6289 // We should only be called for evaluating non-pointer expressions, or
6290 // expressions with a pointer type that are not used as references but
6291 // instead
6292 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00006293
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006294 // Our "symbolic interpreter" is just a dispatch off the currently
6295 // viewed AST node. We then recursively traverse the AST by calling
6296 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00006297
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006298 E = E->IgnoreParens();
6299 switch (E->getStmtClass()) {
6300 case Stmt::ImplicitCastExprClass: {
6301 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
6302 if (IE->getValueKind() == VK_LValue) {
6303 E = IE->getSubExpr();
6304 continue;
6305 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006306 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006307 }
Richard Smith40f08eb2014-01-30 22:05:38 +00006308
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006309 case Stmt::ExprWithCleanupsClass:
6310 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6311 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006312
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006313 case Stmt::DeclRefExprClass: {
6314 // When we hit a DeclRefExpr we are looking at code that refers to a
6315 // variable's name. If it's not a reference variable we check if it has
6316 // local storage within the function, and if so, return the expression.
6317 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6318
6319 // If we leave the immediate function, the lifetime isn't about to end.
6320 if (DR->refersToEnclosingVariableOrCapture())
6321 return nullptr;
6322
6323 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
6324 // Check if it refers to itself, e.g. "int& i = i;".
6325 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006326 return DR;
6327
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006328 if (V->hasLocalStorage()) {
6329 if (!V->getType()->isReferenceType())
6330 return DR;
6331
6332 // Reference variable, follow through to the expression that
6333 // it points to.
6334 if (V->hasInit()) {
6335 // Add the reference variable to the "trail".
6336 refVars.push_back(DR);
6337 return EvalVal(V->getInit(), refVars, V);
6338 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006339 }
6340 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006341
6342 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006343 }
Mike Stump11289f42009-09-09 15:08:12 +00006344
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006345 case Stmt::UnaryOperatorClass: {
6346 // The only unary operator that make sense to handle here
6347 // is Deref. All others don't resolve to a "name." This includes
6348 // handling all sorts of rvalues passed to a unary operator.
6349 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006350
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006351 if (U->getOpcode() == UO_Deref)
6352 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006353
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006354 return nullptr;
6355 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006356
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006357 case Stmt::ArraySubscriptExprClass: {
6358 // Array subscripts are potential references to data on the stack. We
6359 // retrieve the DeclRefExpr* for the array variable if it indeed
6360 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00006361 const auto *ASE = cast<ArraySubscriptExpr>(E);
6362 if (ASE->isTypeDependent())
6363 return nullptr;
6364 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006365 }
Mike Stump11289f42009-09-09 15:08:12 +00006366
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006367 case Stmt::OMPArraySectionExprClass: {
6368 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
6369 ParentDecl);
6370 }
Mike Stump11289f42009-09-09 15:08:12 +00006371
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006372 case Stmt::ConditionalOperatorClass: {
6373 // For conditional operators we need to see if either the LHS or RHS are
6374 // non-NULL Expr's. If one is non-NULL, we return it.
6375 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006376
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006377 // Handle the GNU extension for missing LHS.
6378 if (const Expr *LHSExpr = C->getLHS()) {
6379 // In C++, we can have a throw-expression, which has 'void' type.
6380 if (!LHSExpr->getType()->isVoidType())
6381 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
6382 return LHS;
6383 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006384
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006385 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006386 if (C->getRHS()->getType()->isVoidType())
6387 return nullptr;
6388
6389 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006390 }
6391
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006392 // Accesses to members are potential references to data on the stack.
6393 case Stmt::MemberExprClass: {
6394 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00006395
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006396 // Check for indirect access. We only want direct field accesses.
6397 if (M->isArrow())
6398 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006399
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006400 // Check whether the member type is itself a reference, in which case
6401 // we're not going to refer to the member, but to what the member refers
6402 // to.
6403 if (M->getMemberDecl()->getType()->isReferenceType())
6404 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006405
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006406 return EvalVal(M->getBase(), refVars, ParentDecl);
6407 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00006408
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006409 case Stmt::MaterializeTemporaryExprClass:
6410 if (const Expr *Result =
6411 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6412 refVars, ParentDecl))
6413 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006414 return E;
6415
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006416 default:
6417 // Check that we don't return or take the address of a reference to a
6418 // temporary. This is only useful in C++.
6419 if (!E->isTypeDependent() && E->isRValue())
6420 return E;
6421
6422 // Everything else: we simply don't reason about them.
6423 return nullptr;
6424 }
6425 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006426}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006427
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006428void
6429Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
6430 SourceLocation ReturnLoc,
6431 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00006432 const AttrVec *Attrs,
6433 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006434 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
6435
6436 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00006437 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6438 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00006439 CheckNonNullExpr(*this, RetValExp))
6440 Diag(ReturnLoc, diag::warn_null_ret)
6441 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00006442
6443 // C++11 [basic.stc.dynamic.allocation]p4:
6444 // If an allocation function declared with a non-throwing
6445 // exception-specification fails to allocate storage, it shall return
6446 // a null pointer. Any other allocation function that fails to allocate
6447 // storage shall indicate failure only by throwing an exception [...]
6448 if (FD) {
6449 OverloadedOperatorKind Op = FD->getOverloadedOperator();
6450 if (Op == OO_New || Op == OO_Array_New) {
6451 const FunctionProtoType *Proto
6452 = FD->getType()->castAs<FunctionProtoType>();
6453 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6454 CheckNonNullExpr(*this, RetValExp))
6455 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6456 << FD << getLangOpts().CPlusPlus11;
6457 }
6458 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006459}
6460
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006461//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6462
6463/// Check for comparisons of floating point operands using != and ==.
6464/// Issue a warning if these are no self-comparisons, as they are not likely
6465/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00006466void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00006467 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
6468 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006469
6470 // Special case: check for x == x (which is OK).
6471 // Do not emit warnings for such cases.
6472 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6473 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6474 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00006475 return;
Mike Stump11289f42009-09-09 15:08:12 +00006476
Ted Kremenekeda40e22007-11-29 00:59:04 +00006477 // Special case: check for comparisons against literals that can be exactly
6478 // represented by APFloat. In such cases, do not emit a warning. This
6479 // is a heuristic: often comparison against such literals are used to
6480 // detect if a value in a variable has not changed. This clearly can
6481 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00006482 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6483 if (FLL->isExact())
6484 return;
6485 } else
6486 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6487 if (FLR->isExact())
6488 return;
Mike Stump11289f42009-09-09 15:08:12 +00006489
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006490 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00006491 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006492 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006493 return;
Mike Stump11289f42009-09-09 15:08:12 +00006494
David Blaikie1f4ff152012-07-16 20:47:22 +00006495 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006496 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006497 return;
Mike Stump11289f42009-09-09 15:08:12 +00006498
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006499 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00006500 Diag(Loc, diag::warn_floatingpoint_eq)
6501 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006502}
John McCallca01b222010-01-04 23:21:16 +00006503
John McCall70aa5392010-01-06 05:24:50 +00006504//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6505//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00006506
John McCall70aa5392010-01-06 05:24:50 +00006507namespace {
John McCallca01b222010-01-04 23:21:16 +00006508
John McCall70aa5392010-01-06 05:24:50 +00006509/// Structure recording the 'active' range of an integer-valued
6510/// expression.
6511struct IntRange {
6512 /// The number of bits active in the int.
6513 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00006514
John McCall70aa5392010-01-06 05:24:50 +00006515 /// True if the int is known not to have negative values.
6516 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00006517
John McCall70aa5392010-01-06 05:24:50 +00006518 IntRange(unsigned Width, bool NonNegative)
6519 : Width(Width), NonNegative(NonNegative)
6520 {}
John McCallca01b222010-01-04 23:21:16 +00006521
John McCall817d4af2010-11-10 23:38:19 +00006522 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00006523 static IntRange forBoolType() {
6524 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00006525 }
6526
John McCall817d4af2010-11-10 23:38:19 +00006527 /// Returns the range of an opaque value of the given integral type.
6528 static IntRange forValueOfType(ASTContext &C, QualType T) {
6529 return forValueOfCanonicalType(C,
6530 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00006531 }
6532
John McCall817d4af2010-11-10 23:38:19 +00006533 /// Returns the range of an opaque value of a canonical integral type.
6534 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00006535 assert(T->isCanonicalUnqualified());
6536
6537 if (const VectorType *VT = dyn_cast<VectorType>(T))
6538 T = VT->getElementType().getTypePtr();
6539 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6540 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006541 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6542 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00006543
David Majnemer6a426652013-06-07 22:07:20 +00006544 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00006545 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00006546 EnumDecl *Enum = ET->getDecl();
6547 if (!Enum->isCompleteDefinition())
6548 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00006549
David Majnemer6a426652013-06-07 22:07:20 +00006550 unsigned NumPositive = Enum->getNumPositiveBits();
6551 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00006552
David Majnemer6a426652013-06-07 22:07:20 +00006553 if (NumNegative == 0)
6554 return IntRange(NumPositive, true/*NonNegative*/);
6555 else
6556 return IntRange(std::max(NumPositive + 1, NumNegative),
6557 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00006558 }
John McCall70aa5392010-01-06 05:24:50 +00006559
6560 const BuiltinType *BT = cast<BuiltinType>(T);
6561 assert(BT->isInteger());
6562
6563 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6564 }
6565
John McCall817d4af2010-11-10 23:38:19 +00006566 /// Returns the "target" range of a canonical integral type, i.e.
6567 /// the range of values expressible in the type.
6568 ///
6569 /// This matches forValueOfCanonicalType except that enums have the
6570 /// full range of their type, not the range of their enumerators.
6571 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
6572 assert(T->isCanonicalUnqualified());
6573
6574 if (const VectorType *VT = dyn_cast<VectorType>(T))
6575 T = VT->getElementType().getTypePtr();
6576 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6577 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006578 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6579 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006580 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00006581 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006582
6583 const BuiltinType *BT = cast<BuiltinType>(T);
6584 assert(BT->isInteger());
6585
6586 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6587 }
6588
6589 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00006590 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00006591 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00006592 L.NonNegative && R.NonNegative);
6593 }
6594
John McCall817d4af2010-11-10 23:38:19 +00006595 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00006596 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00006597 return IntRange(std::min(L.Width, R.Width),
6598 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00006599 }
6600};
6601
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006602IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006603 if (value.isSigned() && value.isNegative())
6604 return IntRange(value.getMinSignedBits(), false);
6605
6606 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006607 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006608
6609 // isNonNegative() just checks the sign bit without considering
6610 // signedness.
6611 return IntRange(value.getActiveBits(), true);
6612}
6613
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006614IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
6615 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006616 if (result.isInt())
6617 return GetValueRange(C, result.getInt(), MaxWidth);
6618
6619 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00006620 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6621 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6622 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6623 R = IntRange::join(R, El);
6624 }
John McCall70aa5392010-01-06 05:24:50 +00006625 return R;
6626 }
6627
6628 if (result.isComplexInt()) {
6629 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6630 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6631 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00006632 }
6633
6634 // This can happen with lossless casts to intptr_t of "based" lvalues.
6635 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00006636 // FIXME: The only reason we need to pass the type in here is to get
6637 // the sign right on this one case. It would be nice if APValue
6638 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006639 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00006640 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00006641}
John McCall70aa5392010-01-06 05:24:50 +00006642
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006643QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006644 QualType Ty = E->getType();
6645 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6646 Ty = AtomicRHS->getValueType();
6647 return Ty;
6648}
6649
John McCall70aa5392010-01-06 05:24:50 +00006650/// Pseudo-evaluate the given integer expression, estimating the
6651/// range of values it might take.
6652///
6653/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006654IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006655 E = E->IgnoreParens();
6656
6657 // Try a full evaluation first.
6658 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006659 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00006660 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006661
6662 // I think we only want to look through implicit casts here; if the
6663 // user has an explicit widening cast, we should treat the value as
6664 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006665 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00006666 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00006667 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6668
Eli Friedmane6d33952013-07-08 20:20:06 +00006669 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00006670
George Burgess IVdf1ed002016-01-13 01:52:39 +00006671 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
6672 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00006673
John McCall70aa5392010-01-06 05:24:50 +00006674 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00006675 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00006676 return OutputTypeRange;
6677
6678 IntRange SubRange
6679 = GetExprRange(C, CE->getSubExpr(),
6680 std::min(MaxWidth, OutputTypeRange.Width));
6681
6682 // Bail out if the subexpr's range is as wide as the cast type.
6683 if (SubRange.Width >= OutputTypeRange.Width)
6684 return OutputTypeRange;
6685
6686 // Otherwise, we take the smaller width, and we're non-negative if
6687 // either the output type or the subexpr is.
6688 return IntRange(SubRange.Width,
6689 SubRange.NonNegative || OutputTypeRange.NonNegative);
6690 }
6691
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006692 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006693 // If we can fold the condition, just take that operand.
6694 bool CondResult;
6695 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6696 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6697 : CO->getFalseExpr(),
6698 MaxWidth);
6699
6700 // Otherwise, conservatively merge.
6701 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6702 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6703 return IntRange::join(L, R);
6704 }
6705
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006706 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006707 switch (BO->getOpcode()) {
6708
6709 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00006710 case BO_LAnd:
6711 case BO_LOr:
6712 case BO_LT:
6713 case BO_GT:
6714 case BO_LE:
6715 case BO_GE:
6716 case BO_EQ:
6717 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00006718 return IntRange::forBoolType();
6719
John McCallc3688382011-07-13 06:35:24 +00006720 // The type of the assignments is the type of the LHS, so the RHS
6721 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00006722 case BO_MulAssign:
6723 case BO_DivAssign:
6724 case BO_RemAssign:
6725 case BO_AddAssign:
6726 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00006727 case BO_XorAssign:
6728 case BO_OrAssign:
6729 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00006730 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00006731
John McCallc3688382011-07-13 06:35:24 +00006732 // Simple assignments just pass through the RHS, which will have
6733 // been coerced to the LHS type.
6734 case BO_Assign:
6735 // TODO: bitfields?
6736 return GetExprRange(C, BO->getRHS(), MaxWidth);
6737
John McCall70aa5392010-01-06 05:24:50 +00006738 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006739 case BO_PtrMemD:
6740 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00006741 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006742
John McCall2ce81ad2010-01-06 22:07:33 +00006743 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00006744 case BO_And:
6745 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00006746 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6747 GetExprRange(C, BO->getRHS(), MaxWidth));
6748
John McCall70aa5392010-01-06 05:24:50 +00006749 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00006750 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00006751 // ...except that we want to treat '1 << (blah)' as logically
6752 // positive. It's an important idiom.
6753 if (IntegerLiteral *I
6754 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6755 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006756 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00006757 return IntRange(R.Width, /*NonNegative*/ true);
6758 }
6759 }
6760 // fallthrough
6761
John McCalle3027922010-08-25 11:45:40 +00006762 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00006763 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006764
John McCall2ce81ad2010-01-06 22:07:33 +00006765 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00006766 case BO_Shr:
6767 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00006768 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6769
6770 // If the shift amount is a positive constant, drop the width by
6771 // that much.
6772 llvm::APSInt shift;
6773 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6774 shift.isNonNegative()) {
6775 unsigned zext = shift.getZExtValue();
6776 if (zext >= L.Width)
6777 L.Width = (L.NonNegative ? 0 : 1);
6778 else
6779 L.Width -= zext;
6780 }
6781
6782 return L;
6783 }
6784
6785 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00006786 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00006787 return GetExprRange(C, BO->getRHS(), MaxWidth);
6788
John McCall2ce81ad2010-01-06 22:07:33 +00006789 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00006790 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00006791 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00006792 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006793 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006794
John McCall51431812011-07-14 22:39:48 +00006795 // The width of a division result is mostly determined by the size
6796 // of the LHS.
6797 case BO_Div: {
6798 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006799 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006800 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6801
6802 // If the divisor is constant, use that.
6803 llvm::APSInt divisor;
6804 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
6805 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
6806 if (log2 >= L.Width)
6807 L.Width = (L.NonNegative ? 0 : 1);
6808 else
6809 L.Width = std::min(L.Width - log2, MaxWidth);
6810 return L;
6811 }
6812
6813 // Otherwise, just use the LHS's width.
6814 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6815 return IntRange(L.Width, L.NonNegative && R.NonNegative);
6816 }
6817
6818 // The result of a remainder can't be larger than the result of
6819 // either side.
6820 case BO_Rem: {
6821 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006822 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006823 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6824 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6825
6826 IntRange meet = IntRange::meet(L, R);
6827 meet.Width = std::min(meet.Width, MaxWidth);
6828 return meet;
6829 }
6830
6831 // The default behavior is okay for these.
6832 case BO_Mul:
6833 case BO_Add:
6834 case BO_Xor:
6835 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00006836 break;
6837 }
6838
John McCall51431812011-07-14 22:39:48 +00006839 // The default case is to treat the operation as if it were closed
6840 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00006841 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6842 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
6843 return IntRange::join(L, R);
6844 }
6845
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006846 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006847 switch (UO->getOpcode()) {
6848 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00006849 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00006850 return IntRange::forBoolType();
6851
6852 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006853 case UO_Deref:
6854 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00006855 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006856
6857 default:
6858 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
6859 }
6860 }
6861
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006862 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00006863 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
6864
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006865 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00006866 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00006867 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00006868
Eli Friedmane6d33952013-07-08 20:20:06 +00006869 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006870}
John McCall263a48b2010-01-04 23:31:57 +00006871
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006872IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006873 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00006874}
6875
John McCall263a48b2010-01-04 23:31:57 +00006876/// Checks whether the given value, which currently has the given
6877/// source semantics, has the same value when coerced through the
6878/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006879bool IsSameFloatAfterCast(const llvm::APFloat &value,
6880 const llvm::fltSemantics &Src,
6881 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006882 llvm::APFloat truncated = value;
6883
6884 bool ignored;
6885 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6886 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6887
6888 return truncated.bitwiseIsEqual(value);
6889}
6890
6891/// Checks whether the given value, which currently has the given
6892/// source semantics, has the same value when coerced through the
6893/// target semantics.
6894///
6895/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006896bool IsSameFloatAfterCast(const APValue &value,
6897 const llvm::fltSemantics &Src,
6898 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006899 if (value.isFloat())
6900 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6901
6902 if (value.isVector()) {
6903 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6904 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6905 return false;
6906 return true;
6907 }
6908
6909 assert(value.isComplexFloat());
6910 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6911 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6912}
6913
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006914void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006915
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006916bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00006917 // Suppress cases where we are comparing against an enum constant.
6918 if (const DeclRefExpr *DR =
6919 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6920 if (isa<EnumConstantDecl>(DR->getDecl()))
6921 return false;
6922
6923 // Suppress cases where the '0' value is expanded from a macro.
6924 if (E->getLocStart().isMacroID())
6925 return false;
6926
John McCallcc7e5bf2010-05-06 08:58:33 +00006927 llvm::APSInt Value;
6928 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6929}
6930
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006931bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00006932 // Strip off implicit integral promotions.
6933 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006934 if (ICE->getCastKind() != CK_IntegralCast &&
6935 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00006936 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006937 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00006938 }
6939
6940 return E->getType()->isEnumeralType();
6941}
6942
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006943void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00006944 // Disable warning in template instantiations.
6945 if (!S.ActiveTemplateInstantiations.empty())
6946 return;
6947
John McCalle3027922010-08-25 11:45:40 +00006948 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00006949 if (E->isValueDependent())
6950 return;
6951
John McCalle3027922010-08-25 11:45:40 +00006952 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006953 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006954 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006955 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006956 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006957 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006958 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006959 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006960 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006961 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006962 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006963 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006964 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006965 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006966 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006967 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6968 }
6969}
6970
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006971void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
6972 Expr *Constant, Expr *Other,
6973 llvm::APSInt Value,
6974 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00006975 // Disable warning in template instantiations.
6976 if (!S.ActiveTemplateInstantiations.empty())
6977 return;
6978
Richard Trieu0f097742014-04-04 04:13:47 +00006979 // TODO: Investigate using GetExprRange() to get tighter bounds
6980 // on the bit ranges.
6981 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00006982 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00006983 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00006984 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6985 unsigned OtherWidth = OtherRange.Width;
6986
6987 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6988
Richard Trieu560910c2012-11-14 22:50:24 +00006989 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00006990 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00006991 return;
6992
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006993 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00006994 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006995
Richard Trieu0f097742014-04-04 04:13:47 +00006996 // Used for diagnostic printout.
6997 enum {
6998 LiteralConstant = 0,
6999 CXXBoolLiteralTrue,
7000 CXXBoolLiteralFalse
7001 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007002
Richard Trieu0f097742014-04-04 04:13:47 +00007003 if (!OtherIsBooleanType) {
7004 QualType ConstantT = Constant->getType();
7005 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00007006
Richard Trieu0f097742014-04-04 04:13:47 +00007007 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
7008 return;
7009 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
7010 "comparison with non-integer type");
7011
7012 bool ConstantSigned = ConstantT->isSignedIntegerType();
7013 bool CommonSigned = CommonT->isSignedIntegerType();
7014
7015 bool EqualityOnly = false;
7016
7017 if (CommonSigned) {
7018 // The common type is signed, therefore no signed to unsigned conversion.
7019 if (!OtherRange.NonNegative) {
7020 // Check that the constant is representable in type OtherT.
7021 if (ConstantSigned) {
7022 if (OtherWidth >= Value.getMinSignedBits())
7023 return;
7024 } else { // !ConstantSigned
7025 if (OtherWidth >= Value.getActiveBits() + 1)
7026 return;
7027 }
7028 } else { // !OtherSigned
7029 // Check that the constant is representable in type OtherT.
7030 // Negative values are out of range.
7031 if (ConstantSigned) {
7032 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
7033 return;
7034 } else { // !ConstantSigned
7035 if (OtherWidth >= Value.getActiveBits())
7036 return;
7037 }
Richard Trieu560910c2012-11-14 22:50:24 +00007038 }
Richard Trieu0f097742014-04-04 04:13:47 +00007039 } else { // !CommonSigned
7040 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00007041 if (OtherWidth >= Value.getActiveBits())
7042 return;
Craig Toppercf360162014-06-18 05:13:11 +00007043 } else { // OtherSigned
7044 assert(!ConstantSigned &&
7045 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00007046 // Check to see if the constant is representable in OtherT.
7047 if (OtherWidth > Value.getActiveBits())
7048 return;
7049 // Check to see if the constant is equivalent to a negative value
7050 // cast to CommonT.
7051 if (S.Context.getIntWidth(ConstantT) ==
7052 S.Context.getIntWidth(CommonT) &&
7053 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
7054 return;
7055 // The constant value rests between values that OtherT can represent
7056 // after conversion. Relational comparison still works, but equality
7057 // comparisons will be tautological.
7058 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007059 }
7060 }
Richard Trieu0f097742014-04-04 04:13:47 +00007061
7062 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
7063
7064 if (op == BO_EQ || op == BO_NE) {
7065 IsTrue = op == BO_NE;
7066 } else if (EqualityOnly) {
7067 return;
7068 } else if (RhsConstant) {
7069 if (op == BO_GT || op == BO_GE)
7070 IsTrue = !PositiveConstant;
7071 else // op == BO_LT || op == BO_LE
7072 IsTrue = PositiveConstant;
7073 } else {
7074 if (op == BO_LT || op == BO_LE)
7075 IsTrue = !PositiveConstant;
7076 else // op == BO_GT || op == BO_GE
7077 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007078 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007079 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00007080 // Other isKnownToHaveBooleanValue
7081 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
7082 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
7083 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
7084
7085 static const struct LinkedConditions {
7086 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
7087 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
7088 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
7089 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
7090 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
7091 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
7092
7093 } TruthTable = {
7094 // Constant on LHS. | Constant on RHS. |
7095 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
7096 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
7097 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
7098 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
7099 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
7100 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
7101 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
7102 };
7103
7104 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
7105
7106 enum ConstantValue ConstVal = Zero;
7107 if (Value.isUnsigned() || Value.isNonNegative()) {
7108 if (Value == 0) {
7109 LiteralOrBoolConstant =
7110 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
7111 ConstVal = Zero;
7112 } else if (Value == 1) {
7113 LiteralOrBoolConstant =
7114 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
7115 ConstVal = One;
7116 } else {
7117 LiteralOrBoolConstant = LiteralConstant;
7118 ConstVal = GT_One;
7119 }
7120 } else {
7121 ConstVal = LT_Zero;
7122 }
7123
7124 CompareBoolWithConstantResult CmpRes;
7125
7126 switch (op) {
7127 case BO_LT:
7128 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
7129 break;
7130 case BO_GT:
7131 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
7132 break;
7133 case BO_LE:
7134 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
7135 break;
7136 case BO_GE:
7137 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
7138 break;
7139 case BO_EQ:
7140 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
7141 break;
7142 case BO_NE:
7143 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
7144 break;
7145 default:
7146 CmpRes = Unkwn;
7147 break;
7148 }
7149
7150 if (CmpRes == AFals) {
7151 IsTrue = false;
7152 } else if (CmpRes == ATrue) {
7153 IsTrue = true;
7154 } else {
7155 return;
7156 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007157 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007158
7159 // If this is a comparison to an enum constant, include that
7160 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00007161 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007162 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
7163 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
7164
7165 SmallString<64> PrettySourceValue;
7166 llvm::raw_svector_ostream OS(PrettySourceValue);
7167 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00007168 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007169 else
7170 OS << Value;
7171
Richard Trieu0f097742014-04-04 04:13:47 +00007172 S.DiagRuntimeBehavior(
7173 E->getOperatorLoc(), E,
7174 S.PDiag(diag::warn_out_of_range_compare)
7175 << OS.str() << LiteralOrBoolConstant
7176 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
7177 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007178}
7179
John McCallcc7e5bf2010-05-06 08:58:33 +00007180/// Analyze the operands of the given comparison. Implements the
7181/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007182void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00007183 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7184 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007185}
John McCall263a48b2010-01-04 23:31:57 +00007186
John McCallca01b222010-01-04 23:21:16 +00007187/// \brief Implements -Wsign-compare.
7188///
Richard Trieu82402a02011-09-15 21:56:47 +00007189/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007190void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007191 // The type the comparison is being performed in.
7192 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00007193
7194 // Only analyze comparison operators where both sides have been converted to
7195 // the same type.
7196 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
7197 return AnalyzeImpConvsInComparison(S, E);
7198
7199 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00007200 if (E->isValueDependent())
7201 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007202
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007203 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
7204 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007205
7206 bool IsComparisonConstant = false;
7207
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007208 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007209 // of 'true' or 'false'.
7210 if (T->isIntegralType(S.Context)) {
7211 llvm::APSInt RHSValue;
7212 bool IsRHSIntegralLiteral =
7213 RHS->isIntegerConstantExpr(RHSValue, S.Context);
7214 llvm::APSInt LHSValue;
7215 bool IsLHSIntegralLiteral =
7216 LHS->isIntegerConstantExpr(LHSValue, S.Context);
7217 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
7218 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
7219 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
7220 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
7221 else
7222 IsComparisonConstant =
7223 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007224 } else if (!T->hasUnsignedIntegerRepresentation())
7225 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007226
John McCallcc7e5bf2010-05-06 08:58:33 +00007227 // We don't do anything special if this isn't an unsigned integral
7228 // comparison: we're only interested in integral comparisons, and
7229 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00007230 //
7231 // We also don't care about value-dependent expressions or expressions
7232 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007233 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00007234 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007235
John McCallcc7e5bf2010-05-06 08:58:33 +00007236 // Check to see if one of the (unmodified) operands is of different
7237 // signedness.
7238 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00007239 if (LHS->getType()->hasSignedIntegerRepresentation()) {
7240 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00007241 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00007242 signedOperand = LHS;
7243 unsignedOperand = RHS;
7244 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
7245 signedOperand = RHS;
7246 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00007247 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00007248 CheckTrivialUnsignedComparison(S, E);
7249 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007250 }
7251
John McCallcc7e5bf2010-05-06 08:58:33 +00007252 // Otherwise, calculate the effective range of the signed operand.
7253 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00007254
John McCallcc7e5bf2010-05-06 08:58:33 +00007255 // Go ahead and analyze implicit conversions in the operands. Note
7256 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00007257 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
7258 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00007259
John McCallcc7e5bf2010-05-06 08:58:33 +00007260 // If the signed range is non-negative, -Wsign-compare won't fire,
7261 // but we should still check for comparisons which are always true
7262 // or false.
7263 if (signedRange.NonNegative)
7264 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007265
7266 // For (in)equality comparisons, if the unsigned operand is a
7267 // constant which cannot collide with a overflowed signed operand,
7268 // then reinterpreting the signed operand as unsigned will not
7269 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00007270 if (E->isEqualityOp()) {
7271 unsigned comparisonWidth = S.Context.getIntWidth(T);
7272 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00007273
John McCallcc7e5bf2010-05-06 08:58:33 +00007274 // We should never be unable to prove that the unsigned operand is
7275 // non-negative.
7276 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
7277
7278 if (unsignedRange.Width < comparisonWidth)
7279 return;
7280 }
7281
Douglas Gregorbfb4a212012-05-01 01:53:49 +00007282 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
7283 S.PDiag(diag::warn_mixed_sign_comparison)
7284 << LHS->getType() << RHS->getType()
7285 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00007286}
7287
John McCall1f425642010-11-11 03:21:53 +00007288/// Analyzes an attempt to assign the given value to a bitfield.
7289///
7290/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007291bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
7292 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00007293 assert(Bitfield->isBitField());
7294 if (Bitfield->isInvalidDecl())
7295 return false;
7296
John McCalldeebbcf2010-11-11 05:33:51 +00007297 // White-list bool bitfields.
7298 if (Bitfield->getType()->isBooleanType())
7299 return false;
7300
Douglas Gregor789adec2011-02-04 13:09:01 +00007301 // Ignore value- or type-dependent expressions.
7302 if (Bitfield->getBitWidth()->isValueDependent() ||
7303 Bitfield->getBitWidth()->isTypeDependent() ||
7304 Init->isValueDependent() ||
7305 Init->isTypeDependent())
7306 return false;
7307
John McCall1f425642010-11-11 03:21:53 +00007308 Expr *OriginalInit = Init->IgnoreParenImpCasts();
7309
Richard Smith5fab0c92011-12-28 19:48:30 +00007310 llvm::APSInt Value;
7311 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00007312 return false;
7313
John McCall1f425642010-11-11 03:21:53 +00007314 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00007315 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00007316
7317 if (OriginalWidth <= FieldWidth)
7318 return false;
7319
Eli Friedmanc267a322012-01-26 23:11:39 +00007320 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007321 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00007322 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00007323
Eli Friedmanc267a322012-01-26 23:11:39 +00007324 // Check whether the stored value is equal to the original value.
7325 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00007326 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00007327 return false;
7328
Eli Friedmanc267a322012-01-26 23:11:39 +00007329 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00007330 // therefore don't strictly fit into a signed bitfield of width 1.
7331 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00007332 return false;
7333
John McCall1f425642010-11-11 03:21:53 +00007334 std::string PrettyValue = Value.toString(10);
7335 std::string PrettyTrunc = TruncatedValue.toString(10);
7336
7337 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
7338 << PrettyValue << PrettyTrunc << OriginalInit->getType()
7339 << Init->getSourceRange();
7340
7341 return true;
7342}
7343
John McCalld2a53122010-11-09 23:24:47 +00007344/// Analyze the given simple or compound assignment for warning-worthy
7345/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007346void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00007347 // Just recurse on the LHS.
7348 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7349
7350 // We want to recurse on the RHS as normal unless we're assigning to
7351 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00007352 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007353 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00007354 E->getOperatorLoc())) {
7355 // Recurse, ignoring any implicit conversions on the RHS.
7356 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
7357 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00007358 }
7359 }
7360
7361 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7362}
7363
John McCall263a48b2010-01-04 23:31:57 +00007364/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007365void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
7366 SourceLocation CContext, unsigned diag,
7367 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007368 if (pruneControlFlow) {
7369 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7370 S.PDiag(diag)
7371 << SourceType << T << E->getSourceRange()
7372 << SourceRange(CContext));
7373 return;
7374 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00007375 S.Diag(E->getExprLoc(), diag)
7376 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
7377}
7378
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007379/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007380void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
7381 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007382 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007383}
7384
Richard Trieube234c32016-04-21 21:04:55 +00007385
7386/// Diagnose an implicit cast from a floating point value to an integer value.
7387void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
7388
7389 SourceLocation CContext) {
7390 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
7391 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
7392
7393 Expr *InnerE = E->IgnoreParenImpCasts();
7394 // We also want to warn on, e.g., "int i = -1.234"
7395 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7396 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7397 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7398
7399 const bool IsLiteral =
7400 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
7401
7402 llvm::APFloat Value(0.0);
7403 bool IsConstant =
7404 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
7405 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00007406 return DiagnoseImpCast(S, E, T, CContext,
7407 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00007408 }
7409
Chandler Carruth016ef402011-04-10 08:36:24 +00007410 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00007411
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00007412 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
7413 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00007414 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
7415 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00007416 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00007417 if (IsLiteral) return;
7418 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
7419 PruneWarnings);
7420 }
7421
7422 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00007423 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00007424 // Warn on floating point literal to integer.
7425 DiagID = diag::warn_impcast_literal_float_to_integer;
7426 } else if (IntegerValue == 0) {
7427 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
7428 return DiagnoseImpCast(S, E, T, CContext,
7429 diag::warn_impcast_float_integer, PruneWarnings);
7430 }
7431 // Warn on non-zero to zero conversion.
7432 DiagID = diag::warn_impcast_float_to_integer_zero;
7433 } else {
7434 if (IntegerValue.isUnsigned()) {
7435 if (!IntegerValue.isMaxValue()) {
7436 return DiagnoseImpCast(S, E, T, CContext,
7437 diag::warn_impcast_float_integer, PruneWarnings);
7438 }
7439 } else { // IntegerValue.isSigned()
7440 if (!IntegerValue.isMaxSignedValue() &&
7441 !IntegerValue.isMinSignedValue()) {
7442 return DiagnoseImpCast(S, E, T, CContext,
7443 diag::warn_impcast_float_integer, PruneWarnings);
7444 }
7445 }
7446 // Warn on evaluatable floating point expression to integer conversion.
7447 DiagID = diag::warn_impcast_float_to_integer;
7448 }
Chandler Carruth016ef402011-04-10 08:36:24 +00007449
Eli Friedman07185912013-08-29 23:44:43 +00007450 // FIXME: Force the precision of the source value down so we don't print
7451 // digits which are usually useless (we don't really care here if we
7452 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
7453 // would automatically print the shortest representation, but it's a bit
7454 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00007455 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00007456 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
7457 precision = (precision * 59 + 195) / 196;
7458 Value.toString(PrettySourceValue, precision);
7459
David Blaikie9b88cc02012-05-15 17:18:27 +00007460 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00007461 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00007462 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00007463 else
David Blaikie9b88cc02012-05-15 17:18:27 +00007464 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00007465
Richard Trieube234c32016-04-21 21:04:55 +00007466 if (PruneWarnings) {
7467 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7468 S.PDiag(DiagID)
7469 << E->getType() << T.getUnqualifiedType()
7470 << PrettySourceValue << PrettyTargetValue
7471 << E->getSourceRange() << SourceRange(CContext));
7472 } else {
7473 S.Diag(E->getExprLoc(), DiagID)
7474 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
7475 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
7476 }
Chandler Carruth016ef402011-04-10 08:36:24 +00007477}
7478
John McCall18a2c2c2010-11-09 22:22:12 +00007479std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
7480 if (!Range.Width) return "0";
7481
7482 llvm::APSInt ValueInRange = Value;
7483 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00007484 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00007485 return ValueInRange.toString(10);
7486}
7487
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007488bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007489 if (!isa<ImplicitCastExpr>(Ex))
7490 return false;
7491
7492 Expr *InnerE = Ex->IgnoreParenImpCasts();
7493 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
7494 const Type *Source =
7495 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7496 if (Target->isDependentType())
7497 return false;
7498
7499 const BuiltinType *FloatCandidateBT =
7500 dyn_cast<BuiltinType>(ToBool ? Source : Target);
7501 const Type *BoolCandidateType = ToBool ? Target : Source;
7502
7503 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7504 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
7505}
7506
7507void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
7508 SourceLocation CC) {
7509 unsigned NumArgs = TheCall->getNumArgs();
7510 for (unsigned i = 0; i < NumArgs; ++i) {
7511 Expr *CurrA = TheCall->getArg(i);
7512 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
7513 continue;
7514
7515 bool IsSwapped = ((i > 0) &&
7516 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
7517 IsSwapped |= ((i < (NumArgs - 1)) &&
7518 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
7519 if (IsSwapped) {
7520 // Warn on this floating-point to bool conversion.
7521 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
7522 CurrA->getType(), CC,
7523 diag::warn_impcast_floating_point_to_bool);
7524 }
7525 }
7526}
7527
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007528void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00007529 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
7530 E->getExprLoc()))
7531 return;
7532
Richard Trieu09d6b802016-01-08 23:35:06 +00007533 // Don't warn on functions which have return type nullptr_t.
7534 if (isa<CallExpr>(E))
7535 return;
7536
Richard Trieu5b993502014-10-15 03:42:06 +00007537 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
7538 const Expr::NullPointerConstantKind NullKind =
7539 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
7540 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
7541 return;
7542
7543 // Return if target type is a safe conversion.
7544 if (T->isAnyPointerType() || T->isBlockPointerType() ||
7545 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
7546 return;
7547
7548 SourceLocation Loc = E->getSourceRange().getBegin();
7549
Richard Trieu0a5e1662016-02-13 00:58:53 +00007550 // Venture through the macro stacks to get to the source of macro arguments.
7551 // The new location is a better location than the complete location that was
7552 // passed in.
7553 while (S.SourceMgr.isMacroArgExpansion(Loc))
7554 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
7555
7556 while (S.SourceMgr.isMacroArgExpansion(CC))
7557 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
7558
Richard Trieu5b993502014-10-15 03:42:06 +00007559 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00007560 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
7561 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
7562 Loc, S.SourceMgr, S.getLangOpts());
7563 if (MacroName == "NULL")
7564 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00007565 }
7566
7567 // Only warn if the null and context location are in the same macro expansion.
7568 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
7569 return;
7570
7571 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
7572 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
7573 << FixItHint::CreateReplacement(Loc,
7574 S.getFixItZeroLiteralForType(T, Loc));
7575}
7576
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007577void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7578 ObjCArrayLiteral *ArrayLiteral);
7579void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7580 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00007581
7582/// Check a single element within a collection literal against the
7583/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007584void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
7585 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007586 // Skip a bitcast to 'id' or qualified 'id'.
7587 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
7588 if (ICE->getCastKind() == CK_BitCast &&
7589 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
7590 Element = ICE->getSubExpr();
7591 }
7592
7593 QualType ElementType = Element->getType();
7594 ExprResult ElementResult(Element);
7595 if (ElementType->getAs<ObjCObjectPointerType>() &&
7596 S.CheckSingleAssignmentConstraints(TargetElementType,
7597 ElementResult,
7598 false, false)
7599 != Sema::Compatible) {
7600 S.Diag(Element->getLocStart(),
7601 diag::warn_objc_collection_literal_element)
7602 << ElementType << ElementKind << TargetElementType
7603 << Element->getSourceRange();
7604 }
7605
7606 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7607 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7608 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7609 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7610}
7611
7612/// Check an Objective-C array literal being converted to the given
7613/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007614void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7615 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007616 if (!S.NSArrayDecl)
7617 return;
7618
7619 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7620 if (!TargetObjCPtr)
7621 return;
7622
7623 if (TargetObjCPtr->isUnspecialized() ||
7624 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7625 != S.NSArrayDecl->getCanonicalDecl())
7626 return;
7627
7628 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7629 if (TypeArgs.size() != 1)
7630 return;
7631
7632 QualType TargetElementType = TypeArgs[0];
7633 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
7634 checkObjCCollectionLiteralElement(S, TargetElementType,
7635 ArrayLiteral->getElement(I),
7636 0);
7637 }
7638}
7639
7640/// Check an Objective-C dictionary literal being converted to the given
7641/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007642void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7643 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007644 if (!S.NSDictionaryDecl)
7645 return;
7646
7647 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7648 if (!TargetObjCPtr)
7649 return;
7650
7651 if (TargetObjCPtr->isUnspecialized() ||
7652 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7653 != S.NSDictionaryDecl->getCanonicalDecl())
7654 return;
7655
7656 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7657 if (TypeArgs.size() != 2)
7658 return;
7659
7660 QualType TargetKeyType = TypeArgs[0];
7661 QualType TargetObjectType = TypeArgs[1];
7662 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
7663 auto Element = DictionaryLiteral->getKeyValueElement(I);
7664 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7665 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7666 }
7667}
7668
Richard Trieufc404c72016-02-05 23:02:38 +00007669// Helper function to filter out cases for constant width constant conversion.
7670// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007671bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
7672 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00007673 // If initializing from a constant, and the constant starts with '0',
7674 // then it is a binary, octal, or hexadecimal. Allow these constants
7675 // to fill all the bits, even if there is a sign change.
7676 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
7677 const char FirstLiteralCharacter =
7678 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
7679 if (FirstLiteralCharacter == '0')
7680 return false;
7681 }
7682
7683 // If the CC location points to a '{', and the type is char, then assume
7684 // assume it is an array initialization.
7685 if (CC.isValid() && T->isCharType()) {
7686 const char FirstContextCharacter =
7687 S.getSourceManager().getCharacterData(CC)[0];
7688 if (FirstContextCharacter == '{')
7689 return false;
7690 }
7691
7692 return true;
7693}
7694
John McCallcc7e5bf2010-05-06 08:58:33 +00007695void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00007696 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007697 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00007698
John McCallcc7e5bf2010-05-06 08:58:33 +00007699 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
7700 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
7701 if (Source == Target) return;
7702 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00007703
Chandler Carruthc22845a2011-07-26 05:40:03 +00007704 // If the conversion context location is invalid don't complain. We also
7705 // don't want to emit a warning if the issue occurs from the expansion of
7706 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
7707 // delay this check as long as possible. Once we detect we are in that
7708 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007709 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00007710 return;
7711
Richard Trieu021baa32011-09-23 20:10:00 +00007712 // Diagnose implicit casts to bool.
7713 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
7714 if (isa<StringLiteral>(E))
7715 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00007716 // and expressions, for instance, assert(0 && "error here"), are
7717 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00007718 return DiagnoseImpCast(S, E, T, CC,
7719 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00007720 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7721 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7722 // This covers the literal expressions that evaluate to Objective-C
7723 // objects.
7724 return DiagnoseImpCast(S, E, T, CC,
7725 diag::warn_impcast_objective_c_literal_to_bool);
7726 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007727 if (Source->isPointerType() || Source->canDecayToPointerType()) {
7728 // Warn on pointer to bool conversion that is always true.
7729 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
7730 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00007731 }
Richard Trieu021baa32011-09-23 20:10:00 +00007732 }
John McCall263a48b2010-01-04 23:31:57 +00007733
Douglas Gregor5054cb02015-07-07 03:58:22 +00007734 // Check implicit casts from Objective-C collection literals to specialized
7735 // collection types, e.g., NSArray<NSString *> *.
7736 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7737 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
7738 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7739 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
7740
John McCall263a48b2010-01-04 23:31:57 +00007741 // Strip vector types.
7742 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007743 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007744 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007745 return;
John McCallacf0ee52010-10-08 02:01:28 +00007746 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007747 }
Chris Lattneree7286f2011-06-14 04:51:15 +00007748
7749 // If the vector cast is cast between two vectors of the same size, it is
7750 // a bitcast, not a conversion.
7751 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
7752 return;
John McCall263a48b2010-01-04 23:31:57 +00007753
7754 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
7755 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
7756 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00007757 if (auto VecTy = dyn_cast<VectorType>(Target))
7758 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00007759
7760 // Strip complex types.
7761 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007762 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007763 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007764 return;
7765
John McCallacf0ee52010-10-08 02:01:28 +00007766 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007767 }
John McCall263a48b2010-01-04 23:31:57 +00007768
7769 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
7770 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
7771 }
7772
7773 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
7774 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
7775
7776 // If the source is floating point...
7777 if (SourceBT && SourceBT->isFloatingPoint()) {
7778 // ...and the target is floating point...
7779 if (TargetBT && TargetBT->isFloatingPoint()) {
7780 // ...then warn if we're dropping FP rank.
7781
7782 // Builtin FP kinds are ordered by increasing FP rank.
7783 if (SourceBT->getKind() > TargetBT->getKind()) {
7784 // Don't warn about float constants that are precisely
7785 // representable in the target type.
7786 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007787 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00007788 // Value might be a float, a float vector, or a float complex.
7789 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00007790 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
7791 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00007792 return;
7793 }
7794
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007795 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007796 return;
7797
John McCallacf0ee52010-10-08 02:01:28 +00007798 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00007799 }
7800 // ... or possibly if we're increasing rank, too
7801 else if (TargetBT->getKind() > SourceBT->getKind()) {
7802 if (S.SourceMgr.isInSystemMacro(CC))
7803 return;
7804
7805 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00007806 }
7807 return;
7808 }
7809
Richard Trieube234c32016-04-21 21:04:55 +00007810 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00007811 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007812 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007813 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00007814
Richard Trieube234c32016-04-21 21:04:55 +00007815 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00007816 }
John McCall263a48b2010-01-04 23:31:57 +00007817
Richard Smith54894fd2015-12-30 01:06:52 +00007818 // Detect the case where a call result is converted from floating-point to
7819 // to bool, and the final argument to the call is converted from bool, to
7820 // discover this typo:
7821 //
7822 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
7823 //
7824 // FIXME: This is an incredibly special case; is there some more general
7825 // way to detect this class of misplaced-parentheses bug?
7826 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007827 // Check last argument of function call to see if it is an
7828 // implicit cast from a type matching the type the result
7829 // is being cast to.
7830 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00007831 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007832 Expr *LastA = CEx->getArg(NumArgs - 1);
7833 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00007834 if (isa<ImplicitCastExpr>(LastA) &&
7835 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007836 // Warn on this floating-point to bool conversion
7837 DiagnoseImpCast(S, E, T, CC,
7838 diag::warn_impcast_floating_point_to_bool);
7839 }
7840 }
7841 }
John McCall263a48b2010-01-04 23:31:57 +00007842 return;
7843 }
7844
Richard Trieu5b993502014-10-15 03:42:06 +00007845 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00007846
David Blaikie9366d2b2012-06-19 21:19:06 +00007847 if (!Source->isIntegerType() || !Target->isIntegerType())
7848 return;
7849
David Blaikie7555b6a2012-05-15 16:56:36 +00007850 // TODO: remove this early return once the false positives for constant->bool
7851 // in templates, macros, etc, are reduced or removed.
7852 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
7853 return;
7854
John McCallcc7e5bf2010-05-06 08:58:33 +00007855 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00007856 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00007857
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007858 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00007859 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007860 // TODO: this should happen for bitfield stores, too.
7861 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00007862 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007863 if (S.SourceMgr.isInSystemMacro(CC))
7864 return;
7865
John McCall18a2c2c2010-11-09 22:22:12 +00007866 std::string PrettySourceValue = Value.toString(10);
7867 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007868
Ted Kremenek33ba9952011-10-22 02:37:33 +00007869 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7870 S.PDiag(diag::warn_impcast_integer_precision_constant)
7871 << PrettySourceValue << PrettyTargetValue
7872 << E->getType() << T << E->getSourceRange()
7873 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00007874 return;
7875 }
7876
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007877 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
7878 if (S.SourceMgr.isInSystemMacro(CC))
7879 return;
7880
David Blaikie9455da02012-04-12 22:40:54 +00007881 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00007882 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
7883 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00007884 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00007885 }
7886
Richard Trieudcb55572016-01-29 23:51:16 +00007887 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
7888 SourceRange.NonNegative && Source->isSignedIntegerType()) {
7889 // Warn when doing a signed to signed conversion, warn if the positive
7890 // source value is exactly the width of the target type, which will
7891 // cause a negative value to be stored.
7892
7893 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00007894 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
7895 !S.SourceMgr.isInSystemMacro(CC)) {
7896 if (isSameWidthConstantConversion(S, E, T, CC)) {
7897 std::string PrettySourceValue = Value.toString(10);
7898 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00007899
Richard Trieufc404c72016-02-05 23:02:38 +00007900 S.DiagRuntimeBehavior(
7901 E->getExprLoc(), E,
7902 S.PDiag(diag::warn_impcast_integer_precision_constant)
7903 << PrettySourceValue << PrettyTargetValue << E->getType() << T
7904 << E->getSourceRange() << clang::SourceRange(CC));
7905 return;
Richard Trieudcb55572016-01-29 23:51:16 +00007906 }
7907 }
Richard Trieufc404c72016-02-05 23:02:38 +00007908
Richard Trieudcb55572016-01-29 23:51:16 +00007909 // Fall through for non-constants to give a sign conversion warning.
7910 }
7911
John McCallcc7e5bf2010-05-06 08:58:33 +00007912 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
7913 (!TargetRange.NonNegative && SourceRange.NonNegative &&
7914 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007915 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007916 return;
7917
John McCallcc7e5bf2010-05-06 08:58:33 +00007918 unsigned DiagID = diag::warn_impcast_integer_sign;
7919
7920 // Traditionally, gcc has warned about this under -Wsign-compare.
7921 // We also want to warn about it in -Wconversion.
7922 // So if -Wconversion is off, use a completely identical diagnostic
7923 // in the sign-compare group.
7924 // The conditional-checking code will
7925 if (ICContext) {
7926 DiagID = diag::warn_impcast_integer_sign_conditional;
7927 *ICContext = true;
7928 }
7929
John McCallacf0ee52010-10-08 02:01:28 +00007930 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00007931 }
7932
Douglas Gregora78f1932011-02-22 02:45:07 +00007933 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00007934 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
7935 // type, to give us better diagnostics.
7936 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007937 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00007938 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7939 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
7940 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
7941 SourceType = S.Context.getTypeDeclType(Enum);
7942 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
7943 }
7944 }
7945
Douglas Gregora78f1932011-02-22 02:45:07 +00007946 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
7947 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00007948 if (SourceEnum->getDecl()->hasNameForLinkage() &&
7949 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007950 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007951 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007952 return;
7953
Douglas Gregor364f7db2011-03-12 00:14:31 +00007954 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00007955 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007956 }
John McCall263a48b2010-01-04 23:31:57 +00007957}
7958
David Blaikie18e9ac72012-05-15 21:57:38 +00007959void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7960 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007961
7962void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00007963 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007964 E = E->IgnoreParenImpCasts();
7965
7966 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00007967 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007968
John McCallacf0ee52010-10-08 02:01:28 +00007969 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007970 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007971 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00007972}
7973
David Blaikie18e9ac72012-05-15 21:57:38 +00007974void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7975 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00007976 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007977
7978 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00007979 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
7980 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007981
7982 // If -Wconversion would have warned about either of the candidates
7983 // for a signedness conversion to the context type...
7984 if (!Suspicious) return;
7985
7986 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007987 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00007988 return;
7989
John McCallcc7e5bf2010-05-06 08:58:33 +00007990 // ...then check whether it would have warned about either of the
7991 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00007992 if (E->getType() == T) return;
7993
7994 Suspicious = false;
7995 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
7996 E->getType(), CC, &Suspicious);
7997 if (!Suspicious)
7998 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00007999 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008000}
8001
Richard Trieu65724892014-11-15 06:37:39 +00008002/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8003/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008004void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00008005 if (S.getLangOpts().Bool)
8006 return;
8007 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
8008}
8009
John McCallcc7e5bf2010-05-06 08:58:33 +00008010/// AnalyzeImplicitConversions - Find and report any interesting
8011/// implicit conversions in the given expression. There are a couple
8012/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008013void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00008014 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00008015 Expr *E = OrigE->IgnoreParenImpCasts();
8016
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00008017 if (E->isTypeDependent() || E->isValueDependent())
8018 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00008019
John McCallcc7e5bf2010-05-06 08:58:33 +00008020 // For conditional operators, we analyze the arguments as if they
8021 // were being fed directly into the output.
8022 if (isa<ConditionalOperator>(E)) {
8023 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00008024 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008025 return;
8026 }
8027
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008028 // Check implicit argument conversions for function calls.
8029 if (CallExpr *Call = dyn_cast<CallExpr>(E))
8030 CheckImplicitArgumentConversions(S, Call, CC);
8031
John McCallcc7e5bf2010-05-06 08:58:33 +00008032 // Go ahead and check any implicit conversions we might have skipped.
8033 // The non-canonical typecheck is just an optimization;
8034 // CheckImplicitConversion will filter out dead implicit conversions.
8035 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008036 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008037
8038 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00008039
8040 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
8041 // The bound subexpressions in a PseudoObjectExpr are not reachable
8042 // as transitive children.
8043 // FIXME: Use a more uniform representation for this.
8044 for (auto *SE : POE->semantics())
8045 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
8046 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00008047 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00008048
John McCallcc7e5bf2010-05-06 08:58:33 +00008049 // Skip past explicit casts.
8050 if (isa<ExplicitCastExpr>(E)) {
8051 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00008052 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008053 }
8054
John McCalld2a53122010-11-09 23:24:47 +00008055 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8056 // Do a somewhat different check with comparison operators.
8057 if (BO->isComparisonOp())
8058 return AnalyzeComparison(S, BO);
8059
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008060 // And with simple assignments.
8061 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00008062 return AnalyzeAssignment(S, BO);
8063 }
John McCallcc7e5bf2010-05-06 08:58:33 +00008064
8065 // These break the otherwise-useful invariant below. Fortunately,
8066 // we don't really need to recurse into them, because any internal
8067 // expressions should have been analyzed already when they were
8068 // built into statements.
8069 if (isa<StmtExpr>(E)) return;
8070
8071 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00008072 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00008073
8074 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00008075 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00008076 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00008077 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00008078 for (Stmt *SubStmt : E->children()) {
8079 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00008080 if (!ChildExpr)
8081 continue;
8082
Richard Trieu955231d2014-01-25 01:10:35 +00008083 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00008084 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00008085 // Ignore checking string literals that are in logical and operators.
8086 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00008087 continue;
8088 AnalyzeImplicitConversions(S, ChildExpr, CC);
8089 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008090
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008091 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00008092 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
8093 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008094 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00008095
8096 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
8097 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008098 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008099 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008100
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008101 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
8102 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00008103 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008104}
8105
8106} // end anonymous namespace
8107
Richard Trieuc1888e02014-06-28 23:25:37 +00008108// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
8109// Returns true when emitting a warning about taking the address of a reference.
8110static bool CheckForReference(Sema &SemaRef, const Expr *E,
8111 PartialDiagnostic PD) {
8112 E = E->IgnoreParenImpCasts();
8113
8114 const FunctionDecl *FD = nullptr;
8115
8116 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8117 if (!DRE->getDecl()->getType()->isReferenceType())
8118 return false;
8119 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8120 if (!M->getMemberDecl()->getType()->isReferenceType())
8121 return false;
8122 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00008123 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00008124 return false;
8125 FD = Call->getDirectCallee();
8126 } else {
8127 return false;
8128 }
8129
8130 SemaRef.Diag(E->getExprLoc(), PD);
8131
8132 // If possible, point to location of function.
8133 if (FD) {
8134 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
8135 }
8136
8137 return true;
8138}
8139
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008140// Returns true if the SourceLocation is expanded from any macro body.
8141// Returns false if the SourceLocation is invalid, is from not in a macro
8142// expansion, or is from expanded from a top-level macro argument.
8143static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
8144 if (Loc.isInvalid())
8145 return false;
8146
8147 while (Loc.isMacroID()) {
8148 if (SM.isMacroBodyExpansion(Loc))
8149 return true;
8150 Loc = SM.getImmediateMacroCallerLoc(Loc);
8151 }
8152
8153 return false;
8154}
8155
Richard Trieu3bb8b562014-02-26 02:36:06 +00008156/// \brief Diagnose pointers that are always non-null.
8157/// \param E the expression containing the pointer
8158/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
8159/// compared to a null pointer
8160/// \param IsEqual True when the comparison is equal to a null pointer
8161/// \param Range Extra SourceRange to highlight in the diagnostic
8162void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
8163 Expr::NullPointerConstantKind NullKind,
8164 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00008165 if (!E)
8166 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008167
8168 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008169 if (E->getExprLoc().isMacroID()) {
8170 const SourceManager &SM = getSourceManager();
8171 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
8172 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00008173 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008174 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008175 E = E->IgnoreImpCasts();
8176
8177 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
8178
Richard Trieuf7432752014-06-06 21:39:26 +00008179 if (isa<CXXThisExpr>(E)) {
8180 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
8181 : diag::warn_this_bool_conversion;
8182 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
8183 return;
8184 }
8185
Richard Trieu3bb8b562014-02-26 02:36:06 +00008186 bool IsAddressOf = false;
8187
8188 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8189 if (UO->getOpcode() != UO_AddrOf)
8190 return;
8191 IsAddressOf = true;
8192 E = UO->getSubExpr();
8193 }
8194
Richard Trieuc1888e02014-06-28 23:25:37 +00008195 if (IsAddressOf) {
8196 unsigned DiagID = IsCompare
8197 ? diag::warn_address_of_reference_null_compare
8198 : diag::warn_address_of_reference_bool_conversion;
8199 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
8200 << IsEqual;
8201 if (CheckForReference(*this, E, PD)) {
8202 return;
8203 }
8204 }
8205
George Burgess IV850269a2015-12-08 22:02:00 +00008206 auto ComplainAboutNonnullParamOrCall = [&](bool IsParam) {
8207 std::string Str;
8208 llvm::raw_string_ostream S(Str);
8209 E->printPretty(S, nullptr, getPrintingPolicy());
8210 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
8211 : diag::warn_cast_nonnull_to_bool;
8212 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
8213 << E->getSourceRange() << Range << IsEqual;
8214 };
8215
8216 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
8217 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
8218 if (auto *Callee = Call->getDirectCallee()) {
8219 if (Callee->hasAttr<ReturnsNonNullAttr>()) {
8220 ComplainAboutNonnullParamOrCall(false);
8221 return;
8222 }
8223 }
8224 }
8225
Richard Trieu3bb8b562014-02-26 02:36:06 +00008226 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00008227 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008228 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
8229 D = R->getDecl();
8230 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8231 D = M->getMemberDecl();
8232 }
8233
8234 // Weak Decls can be null.
8235 if (!D || D->isWeak())
8236 return;
George Burgess IV850269a2015-12-08 22:02:00 +00008237
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008238 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00008239 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
8240 if (getCurFunction() &&
8241 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
8242 if (PV->hasAttr<NonNullAttr>()) {
8243 ComplainAboutNonnullParamOrCall(true);
8244 return;
8245 }
8246
8247 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
8248 auto ParamIter = std::find(FD->param_begin(), FD->param_end(), PV);
8249 assert(ParamIter != FD->param_end());
8250 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
8251
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008252 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
8253 if (!NonNull->args_size()) {
George Burgess IV850269a2015-12-08 22:02:00 +00008254 ComplainAboutNonnullParamOrCall(true);
8255 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008256 }
George Burgess IV850269a2015-12-08 22:02:00 +00008257
8258 for (unsigned ArgNo : NonNull->args()) {
8259 if (ArgNo == ParamNo) {
8260 ComplainAboutNonnullParamOrCall(true);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008261 return;
8262 }
George Burgess IV850269a2015-12-08 22:02:00 +00008263 }
8264 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008265 }
8266 }
George Burgess IV850269a2015-12-08 22:02:00 +00008267 }
8268
Richard Trieu3bb8b562014-02-26 02:36:06 +00008269 QualType T = D->getType();
8270 const bool IsArray = T->isArrayType();
8271 const bool IsFunction = T->isFunctionType();
8272
Richard Trieuc1888e02014-06-28 23:25:37 +00008273 // Address of function is used to silence the function warning.
8274 if (IsAddressOf && IsFunction) {
8275 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008276 }
8277
8278 // Found nothing.
8279 if (!IsAddressOf && !IsFunction && !IsArray)
8280 return;
8281
8282 // Pretty print the expression for the diagnostic.
8283 std::string Str;
8284 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00008285 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00008286
8287 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
8288 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00008289 enum {
8290 AddressOf,
8291 FunctionPointer,
8292 ArrayPointer
8293 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008294 if (IsAddressOf)
8295 DiagType = AddressOf;
8296 else if (IsFunction)
8297 DiagType = FunctionPointer;
8298 else if (IsArray)
8299 DiagType = ArrayPointer;
8300 else
8301 llvm_unreachable("Could not determine diagnostic.");
8302 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
8303 << Range << IsEqual;
8304
8305 if (!IsFunction)
8306 return;
8307
8308 // Suggest '&' to silence the function warning.
8309 Diag(E->getExprLoc(), diag::note_function_warning_silence)
8310 << FixItHint::CreateInsertion(E->getLocStart(), "&");
8311
8312 // Check to see if '()' fixit should be emitted.
8313 QualType ReturnType;
8314 UnresolvedSet<4> NonTemplateOverloads;
8315 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
8316 if (ReturnType.isNull())
8317 return;
8318
8319 if (IsCompare) {
8320 // There are two cases here. If there is null constant, the only suggest
8321 // for a pointer return type. If the null is 0, then suggest if the return
8322 // type is a pointer or an integer type.
8323 if (!ReturnType->isPointerType()) {
8324 if (NullKind == Expr::NPCK_ZeroExpression ||
8325 NullKind == Expr::NPCK_ZeroLiteral) {
8326 if (!ReturnType->isIntegerType())
8327 return;
8328 } else {
8329 return;
8330 }
8331 }
8332 } else { // !IsCompare
8333 // For function to bool, only suggest if the function pointer has bool
8334 // return type.
8335 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
8336 return;
8337 }
8338 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008339 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00008340}
8341
John McCallcc7e5bf2010-05-06 08:58:33 +00008342/// Diagnoses "dangerous" implicit conversions within the given
8343/// expression (which is a full expression). Implements -Wconversion
8344/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008345///
8346/// \param CC the "context" location of the implicit conversion, i.e.
8347/// the most location of the syntactic entity requiring the implicit
8348/// conversion
8349void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008350 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00008351 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00008352 return;
8353
8354 // Don't diagnose for value- or type-dependent expressions.
8355 if (E->isTypeDependent() || E->isValueDependent())
8356 return;
8357
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008358 // Check for array bounds violations in cases where the check isn't triggered
8359 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
8360 // ArraySubscriptExpr is on the RHS of a variable initialization.
8361 CheckArrayAccess(E);
8362
John McCallacf0ee52010-10-08 02:01:28 +00008363 // This is not the right CC for (e.g.) a variable initialization.
8364 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008365}
8366
Richard Trieu65724892014-11-15 06:37:39 +00008367/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8368/// Input argument E is a logical expression.
8369void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
8370 ::CheckBoolLikeConversion(*this, E, CC);
8371}
8372
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008373/// Diagnose when expression is an integer constant expression and its evaluation
8374/// results in integer overflow
8375void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00008376 // Use a work list to deal with nested struct initializers.
8377 SmallVector<Expr *, 2> Exprs(1, E);
8378
8379 do {
8380 Expr *E = Exprs.pop_back_val();
8381
8382 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
8383 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
8384 continue;
8385 }
8386
8387 if (auto InitList = dyn_cast<InitListExpr>(E))
8388 Exprs.append(InitList->inits().begin(), InitList->inits().end());
8389 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008390}
8391
Richard Smithc406cb72013-01-17 01:17:56 +00008392namespace {
8393/// \brief Visitor for expressions which looks for unsequenced operations on the
8394/// same object.
8395class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008396 typedef EvaluatedExprVisitor<SequenceChecker> Base;
8397
Richard Smithc406cb72013-01-17 01:17:56 +00008398 /// \brief A tree of sequenced regions within an expression. Two regions are
8399 /// unsequenced if one is an ancestor or a descendent of the other. When we
8400 /// finish processing an expression with sequencing, such as a comma
8401 /// expression, we fold its tree nodes into its parent, since they are
8402 /// unsequenced with respect to nodes we will visit later.
8403 class SequenceTree {
8404 struct Value {
8405 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
8406 unsigned Parent : 31;
8407 bool Merged : 1;
8408 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008409 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00008410
8411 public:
8412 /// \brief A region within an expression which may be sequenced with respect
8413 /// to some other region.
8414 class Seq {
8415 explicit Seq(unsigned N) : Index(N) {}
8416 unsigned Index;
8417 friend class SequenceTree;
8418 public:
8419 Seq() : Index(0) {}
8420 };
8421
8422 SequenceTree() { Values.push_back(Value(0)); }
8423 Seq root() const { return Seq(0); }
8424
8425 /// \brief Create a new sequence of operations, which is an unsequenced
8426 /// subset of \p Parent. This sequence of operations is sequenced with
8427 /// respect to other children of \p Parent.
8428 Seq allocate(Seq Parent) {
8429 Values.push_back(Value(Parent.Index));
8430 return Seq(Values.size() - 1);
8431 }
8432
8433 /// \brief Merge a sequence of operations into its parent.
8434 void merge(Seq S) {
8435 Values[S.Index].Merged = true;
8436 }
8437
8438 /// \brief Determine whether two operations are unsequenced. This operation
8439 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
8440 /// should have been merged into its parent as appropriate.
8441 bool isUnsequenced(Seq Cur, Seq Old) {
8442 unsigned C = representative(Cur.Index);
8443 unsigned Target = representative(Old.Index);
8444 while (C >= Target) {
8445 if (C == Target)
8446 return true;
8447 C = Values[C].Parent;
8448 }
8449 return false;
8450 }
8451
8452 private:
8453 /// \brief Pick a representative for a sequence.
8454 unsigned representative(unsigned K) {
8455 if (Values[K].Merged)
8456 // Perform path compression as we go.
8457 return Values[K].Parent = representative(Values[K].Parent);
8458 return K;
8459 }
8460 };
8461
8462 /// An object for which we can track unsequenced uses.
8463 typedef NamedDecl *Object;
8464
8465 /// Different flavors of object usage which we track. We only track the
8466 /// least-sequenced usage of each kind.
8467 enum UsageKind {
8468 /// A read of an object. Multiple unsequenced reads are OK.
8469 UK_Use,
8470 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00008471 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00008472 UK_ModAsValue,
8473 /// A modification of an object which is not sequenced before the value
8474 /// computation of the expression, such as n++.
8475 UK_ModAsSideEffect,
8476
8477 UK_Count = UK_ModAsSideEffect + 1
8478 };
8479
8480 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00008481 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00008482 Expr *Use;
8483 SequenceTree::Seq Seq;
8484 };
8485
8486 struct UsageInfo {
8487 UsageInfo() : Diagnosed(false) {}
8488 Usage Uses[UK_Count];
8489 /// Have we issued a diagnostic for this variable already?
8490 bool Diagnosed;
8491 };
8492 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
8493
8494 Sema &SemaRef;
8495 /// Sequenced regions within the expression.
8496 SequenceTree Tree;
8497 /// Declaration modifications and references which we have seen.
8498 UsageInfoMap UsageMap;
8499 /// The region we are currently within.
8500 SequenceTree::Seq Region;
8501 /// Filled in with declarations which were modified as a side-effect
8502 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008503 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00008504 /// Expressions to check later. We defer checking these to reduce
8505 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008506 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00008507
8508 /// RAII object wrapping the visitation of a sequenced subexpression of an
8509 /// expression. At the end of this process, the side-effects of the evaluation
8510 /// become sequenced with respect to the value computation of the result, so
8511 /// we downgrade any UK_ModAsSideEffect within the evaluation to
8512 /// UK_ModAsValue.
8513 struct SequencedSubexpression {
8514 SequencedSubexpression(SequenceChecker &Self)
8515 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
8516 Self.ModAsSideEffect = &ModAsSideEffect;
8517 }
8518 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00008519 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
8520 MI != ME; ++MI) {
8521 UsageInfo &U = Self.UsageMap[MI->first];
8522 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
8523 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
8524 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00008525 }
8526 Self.ModAsSideEffect = OldModAsSideEffect;
8527 }
8528
8529 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008530 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
8531 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00008532 };
8533
Richard Smith40238f02013-06-20 22:21:56 +00008534 /// RAII object wrapping the visitation of a subexpression which we might
8535 /// choose to evaluate as a constant. If any subexpression is evaluated and
8536 /// found to be non-constant, this allows us to suppress the evaluation of
8537 /// the outer expression.
8538 class EvaluationTracker {
8539 public:
8540 EvaluationTracker(SequenceChecker &Self)
8541 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
8542 Self.EvalTracker = this;
8543 }
8544 ~EvaluationTracker() {
8545 Self.EvalTracker = Prev;
8546 if (Prev)
8547 Prev->EvalOK &= EvalOK;
8548 }
8549
8550 bool evaluate(const Expr *E, bool &Result) {
8551 if (!EvalOK || E->isValueDependent())
8552 return false;
8553 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
8554 return EvalOK;
8555 }
8556
8557 private:
8558 SequenceChecker &Self;
8559 EvaluationTracker *Prev;
8560 bool EvalOK;
8561 } *EvalTracker;
8562
Richard Smithc406cb72013-01-17 01:17:56 +00008563 /// \brief Find the object which is produced by the specified expression,
8564 /// if any.
8565 Object getObject(Expr *E, bool Mod) const {
8566 E = E->IgnoreParenCasts();
8567 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8568 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
8569 return getObject(UO->getSubExpr(), Mod);
8570 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8571 if (BO->getOpcode() == BO_Comma)
8572 return getObject(BO->getRHS(), Mod);
8573 if (Mod && BO->isAssignmentOp())
8574 return getObject(BO->getLHS(), Mod);
8575 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
8576 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
8577 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
8578 return ME->getMemberDecl();
8579 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8580 // FIXME: If this is a reference, map through to its value.
8581 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00008582 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00008583 }
8584
8585 /// \brief Note that an object was modified or used by an expression.
8586 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
8587 Usage &U = UI.Uses[UK];
8588 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
8589 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
8590 ModAsSideEffect->push_back(std::make_pair(O, U));
8591 U.Use = Ref;
8592 U.Seq = Region;
8593 }
8594 }
8595 /// \brief Check whether a modification or use conflicts with a prior usage.
8596 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
8597 bool IsModMod) {
8598 if (UI.Diagnosed)
8599 return;
8600
8601 const Usage &U = UI.Uses[OtherKind];
8602 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
8603 return;
8604
8605 Expr *Mod = U.Use;
8606 Expr *ModOrUse = Ref;
8607 if (OtherKind == UK_Use)
8608 std::swap(Mod, ModOrUse);
8609
8610 SemaRef.Diag(Mod->getExprLoc(),
8611 IsModMod ? diag::warn_unsequenced_mod_mod
8612 : diag::warn_unsequenced_mod_use)
8613 << O << SourceRange(ModOrUse->getExprLoc());
8614 UI.Diagnosed = true;
8615 }
8616
8617 void notePreUse(Object O, Expr *Use) {
8618 UsageInfo &U = UsageMap[O];
8619 // Uses conflict with other modifications.
8620 checkUsage(O, U, Use, UK_ModAsValue, false);
8621 }
8622 void notePostUse(Object O, Expr *Use) {
8623 UsageInfo &U = UsageMap[O];
8624 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
8625 addUsage(U, O, Use, UK_Use);
8626 }
8627
8628 void notePreMod(Object O, Expr *Mod) {
8629 UsageInfo &U = UsageMap[O];
8630 // Modifications conflict with other modifications and with uses.
8631 checkUsage(O, U, Mod, UK_ModAsValue, true);
8632 checkUsage(O, U, Mod, UK_Use, false);
8633 }
8634 void notePostMod(Object O, Expr *Use, UsageKind UK) {
8635 UsageInfo &U = UsageMap[O];
8636 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
8637 addUsage(U, O, Use, UK);
8638 }
8639
8640public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008641 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00008642 : Base(S.Context), SemaRef(S), Region(Tree.root()),
8643 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008644 Visit(E);
8645 }
8646
8647 void VisitStmt(Stmt *S) {
8648 // Skip all statements which aren't expressions for now.
8649 }
8650
8651 void VisitExpr(Expr *E) {
8652 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00008653 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008654 }
8655
8656 void VisitCastExpr(CastExpr *E) {
8657 Object O = Object();
8658 if (E->getCastKind() == CK_LValueToRValue)
8659 O = getObject(E->getSubExpr(), false);
8660
8661 if (O)
8662 notePreUse(O, E);
8663 VisitExpr(E);
8664 if (O)
8665 notePostUse(O, E);
8666 }
8667
8668 void VisitBinComma(BinaryOperator *BO) {
8669 // C++11 [expr.comma]p1:
8670 // Every value computation and side effect associated with the left
8671 // expression is sequenced before every value computation and side
8672 // effect associated with the right expression.
8673 SequenceTree::Seq LHS = Tree.allocate(Region);
8674 SequenceTree::Seq RHS = Tree.allocate(Region);
8675 SequenceTree::Seq OldRegion = Region;
8676
8677 {
8678 SequencedSubexpression SeqLHS(*this);
8679 Region = LHS;
8680 Visit(BO->getLHS());
8681 }
8682
8683 Region = RHS;
8684 Visit(BO->getRHS());
8685
8686 Region = OldRegion;
8687
8688 // Forget that LHS and RHS are sequenced. They are both unsequenced
8689 // with respect to other stuff.
8690 Tree.merge(LHS);
8691 Tree.merge(RHS);
8692 }
8693
8694 void VisitBinAssign(BinaryOperator *BO) {
8695 // The modification is sequenced after the value computation of the LHS
8696 // and RHS, so check it before inspecting the operands and update the
8697 // map afterwards.
8698 Object O = getObject(BO->getLHS(), true);
8699 if (!O)
8700 return VisitExpr(BO);
8701
8702 notePreMod(O, BO);
8703
8704 // C++11 [expr.ass]p7:
8705 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
8706 // only once.
8707 //
8708 // Therefore, for a compound assignment operator, O is considered used
8709 // everywhere except within the evaluation of E1 itself.
8710 if (isa<CompoundAssignOperator>(BO))
8711 notePreUse(O, BO);
8712
8713 Visit(BO->getLHS());
8714
8715 if (isa<CompoundAssignOperator>(BO))
8716 notePostUse(O, BO);
8717
8718 Visit(BO->getRHS());
8719
Richard Smith83e37bee2013-06-26 23:16:51 +00008720 // C++11 [expr.ass]p1:
8721 // the assignment is sequenced [...] before the value computation of the
8722 // assignment expression.
8723 // C11 6.5.16/3 has no such rule.
8724 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8725 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008726 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008727
Richard Smithc406cb72013-01-17 01:17:56 +00008728 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
8729 VisitBinAssign(CAO);
8730 }
8731
8732 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8733 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8734 void VisitUnaryPreIncDec(UnaryOperator *UO) {
8735 Object O = getObject(UO->getSubExpr(), true);
8736 if (!O)
8737 return VisitExpr(UO);
8738
8739 notePreMod(O, UO);
8740 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00008741 // C++11 [expr.pre.incr]p1:
8742 // the expression ++x is equivalent to x+=1
8743 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8744 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008745 }
8746
8747 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8748 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8749 void VisitUnaryPostIncDec(UnaryOperator *UO) {
8750 Object O = getObject(UO->getSubExpr(), true);
8751 if (!O)
8752 return VisitExpr(UO);
8753
8754 notePreMod(O, UO);
8755 Visit(UO->getSubExpr());
8756 notePostMod(O, UO, UK_ModAsSideEffect);
8757 }
8758
8759 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
8760 void VisitBinLOr(BinaryOperator *BO) {
8761 // The side-effects of the LHS of an '&&' are sequenced before the
8762 // value computation of the RHS, and hence before the value computation
8763 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
8764 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00008765 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008766 {
8767 SequencedSubexpression Sequenced(*this);
8768 Visit(BO->getLHS());
8769 }
8770
8771 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008772 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008773 if (!Result)
8774 Visit(BO->getRHS());
8775 } else {
8776 // Check for unsequenced operations in the RHS, treating it as an
8777 // entirely separate evaluation.
8778 //
8779 // FIXME: If there are operations in the RHS which are unsequenced
8780 // with respect to operations outside the RHS, and those operations
8781 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00008782 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008783 }
Richard Smithc406cb72013-01-17 01:17:56 +00008784 }
8785 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00008786 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008787 {
8788 SequencedSubexpression Sequenced(*this);
8789 Visit(BO->getLHS());
8790 }
8791
8792 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008793 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008794 if (Result)
8795 Visit(BO->getRHS());
8796 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00008797 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008798 }
Richard Smithc406cb72013-01-17 01:17:56 +00008799 }
8800
8801 // Only visit the condition, unless we can be sure which subexpression will
8802 // be chosen.
8803 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00008804 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00008805 {
8806 SequencedSubexpression Sequenced(*this);
8807 Visit(CO->getCond());
8808 }
Richard Smithc406cb72013-01-17 01:17:56 +00008809
8810 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008811 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00008812 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008813 else {
Richard Smithd33f5202013-01-17 23:18:09 +00008814 WorkList.push_back(CO->getTrueExpr());
8815 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008816 }
Richard Smithc406cb72013-01-17 01:17:56 +00008817 }
8818
Richard Smithe3dbfe02013-06-30 10:40:20 +00008819 void VisitCallExpr(CallExpr *CE) {
8820 // C++11 [intro.execution]p15:
8821 // When calling a function [...], every value computation and side effect
8822 // associated with any argument expression, or with the postfix expression
8823 // designating the called function, is sequenced before execution of every
8824 // expression or statement in the body of the function [and thus before
8825 // the value computation of its result].
8826 SequencedSubexpression Sequenced(*this);
8827 Base::VisitCallExpr(CE);
8828
8829 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
8830 }
8831
Richard Smithc406cb72013-01-17 01:17:56 +00008832 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008833 // This is a call, so all subexpressions are sequenced before the result.
8834 SequencedSubexpression Sequenced(*this);
8835
Richard Smithc406cb72013-01-17 01:17:56 +00008836 if (!CCE->isListInitialization())
8837 return VisitExpr(CCE);
8838
8839 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008840 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008841 SequenceTree::Seq Parent = Region;
8842 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
8843 E = CCE->arg_end();
8844 I != E; ++I) {
8845 Region = Tree.allocate(Parent);
8846 Elts.push_back(Region);
8847 Visit(*I);
8848 }
8849
8850 // Forget that the initializers are sequenced.
8851 Region = Parent;
8852 for (unsigned I = 0; I < Elts.size(); ++I)
8853 Tree.merge(Elts[I]);
8854 }
8855
8856 void VisitInitListExpr(InitListExpr *ILE) {
8857 if (!SemaRef.getLangOpts().CPlusPlus11)
8858 return VisitExpr(ILE);
8859
8860 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008861 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008862 SequenceTree::Seq Parent = Region;
8863 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
8864 Expr *E = ILE->getInit(I);
8865 if (!E) continue;
8866 Region = Tree.allocate(Parent);
8867 Elts.push_back(Region);
8868 Visit(E);
8869 }
8870
8871 // Forget that the initializers are sequenced.
8872 Region = Parent;
8873 for (unsigned I = 0; I < Elts.size(); ++I)
8874 Tree.merge(Elts[I]);
8875 }
8876};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008877} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +00008878
8879void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008880 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00008881 WorkList.push_back(E);
8882 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00008883 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00008884 SequenceChecker(*this, Item, WorkList);
8885 }
Richard Smithc406cb72013-01-17 01:17:56 +00008886}
8887
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008888void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
8889 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008890 CheckImplicitConversions(E, CheckLoc);
8891 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008892 if (!IsConstexpr && !E->isValueDependent())
8893 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008894}
8895
John McCall1f425642010-11-11 03:21:53 +00008896void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
8897 FieldDecl *BitField,
8898 Expr *Init) {
8899 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
8900}
8901
David Majnemer61a5bbf2015-04-07 22:08:51 +00008902static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
8903 SourceLocation Loc) {
8904 if (!PType->isVariablyModifiedType())
8905 return;
8906 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
8907 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
8908 return;
8909 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00008910 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
8911 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
8912 return;
8913 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00008914 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
8915 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
8916 return;
8917 }
8918
8919 const ArrayType *AT = S.Context.getAsArrayType(PType);
8920 if (!AT)
8921 return;
8922
8923 if (AT->getSizeModifier() != ArrayType::Star) {
8924 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
8925 return;
8926 }
8927
8928 S.Diag(Loc, diag::err_array_star_in_function_definition);
8929}
8930
Mike Stump0c2ec772010-01-21 03:59:47 +00008931/// CheckParmsForFunctionDef - Check that the parameters of the given
8932/// function are appropriate for the definition of a function. This
8933/// takes care of any checks that cannot be performed on the
8934/// declaration itself, e.g., that the types of each of the function
8935/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00008936bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
8937 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00008938 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008939 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00008940 for (; P != PEnd; ++P) {
8941 ParmVarDecl *Param = *P;
8942
Mike Stump0c2ec772010-01-21 03:59:47 +00008943 // C99 6.7.5.3p4: the parameters in a parameter type list in a
8944 // function declarator that is part of a function definition of
8945 // that function shall not have incomplete type.
8946 //
8947 // This is also C++ [dcl.fct]p6.
8948 if (!Param->isInvalidDecl() &&
8949 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008950 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008951 Param->setInvalidDecl();
8952 HasInvalidParm = true;
8953 }
8954
8955 // C99 6.9.1p5: If the declarator includes a parameter type list, the
8956 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00008957 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00008958 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00008959 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008960 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00008961 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00008962
8963 // C99 6.7.5.3p12:
8964 // If the function declarator is not part of a definition of that
8965 // function, parameters may have incomplete type and may use the [*]
8966 // notation in their sequences of declarator specifiers to specify
8967 // variable length array types.
8968 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00008969 // FIXME: This diagnostic should point the '[*]' if source-location
8970 // information is added for it.
8971 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008972
8973 // MSVC destroys objects passed by value in the callee. Therefore a
8974 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008975 // object's destructor. However, we don't perform any direct access check
8976 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00008977 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
8978 .getCXXABI()
8979 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00008980 if (!Param->isInvalidDecl()) {
8981 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
8982 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
8983 if (!ClassDecl->isInvalidDecl() &&
8984 !ClassDecl->hasIrrelevantDestructor() &&
8985 !ClassDecl->isDependentContext()) {
8986 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8987 MarkFunctionReferenced(Param->getLocation(), Destructor);
8988 DiagnoseUseOfDecl(Destructor, Param->getLocation());
8989 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008990 }
8991 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008992 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008993
8994 // Parameters with the pass_object_size attribute only need to be marked
8995 // constant at function definitions. Because we lack information about
8996 // whether we're on a declaration or definition when we're instantiating the
8997 // attribute, we need to check for constness here.
8998 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
8999 if (!Param->getType().isConstQualified())
9000 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
9001 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +00009002 }
9003
9004 return HasInvalidParm;
9005}
John McCall2b5c1b22010-08-12 21:44:57 +00009006
9007/// CheckCastAlign - Implements -Wcast-align, which warns when a
9008/// pointer cast increases the alignment requirements.
9009void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
9010 // This is actually a lot of work to potentially be doing on every
9011 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009012 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00009013 return;
9014
9015 // Ignore dependent types.
9016 if (T->isDependentType() || Op->getType()->isDependentType())
9017 return;
9018
9019 // Require that the destination be a pointer type.
9020 const PointerType *DestPtr = T->getAs<PointerType>();
9021 if (!DestPtr) return;
9022
9023 // If the destination has alignment 1, we're done.
9024 QualType DestPointee = DestPtr->getPointeeType();
9025 if (DestPointee->isIncompleteType()) return;
9026 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
9027 if (DestAlign.isOne()) return;
9028
9029 // Require that the source be a pointer type.
9030 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
9031 if (!SrcPtr) return;
9032 QualType SrcPointee = SrcPtr->getPointeeType();
9033
9034 // Whitelist casts from cv void*. We already implicitly
9035 // whitelisted casts to cv void*, since they have alignment 1.
9036 // Also whitelist casts involving incomplete types, which implicitly
9037 // includes 'void'.
9038 if (SrcPointee->isIncompleteType()) return;
9039
9040 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
9041 if (SrcAlign >= DestAlign) return;
9042
9043 Diag(TRange.getBegin(), diag::warn_cast_align)
9044 << Op->getType() << T
9045 << static_cast<unsigned>(SrcAlign.getQuantity())
9046 << static_cast<unsigned>(DestAlign.getQuantity())
9047 << TRange << Op->getSourceRange();
9048}
9049
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009050static const Type* getElementType(const Expr *BaseExpr) {
9051 const Type* EltType = BaseExpr->getType().getTypePtr();
9052 if (EltType->isAnyPointerType())
9053 return EltType->getPointeeType().getTypePtr();
9054 else if (EltType->isArrayType())
9055 return EltType->getBaseElementTypeUnsafe();
9056 return EltType;
9057}
9058
Chandler Carruth28389f02011-08-05 09:10:50 +00009059/// \brief Check whether this array fits the idiom of a size-one tail padded
9060/// array member of a struct.
9061///
9062/// We avoid emitting out-of-bounds access warnings for such arrays as they are
9063/// commonly used to emulate flexible arrays in C89 code.
9064static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
9065 const NamedDecl *ND) {
9066 if (Size != 1 || !ND) return false;
9067
9068 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
9069 if (!FD) return false;
9070
9071 // Don't consider sizes resulting from macro expansions or template argument
9072 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00009073
9074 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009075 while (TInfo) {
9076 TypeLoc TL = TInfo->getTypeLoc();
9077 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00009078 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
9079 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009080 TInfo = TDL->getTypeSourceInfo();
9081 continue;
9082 }
David Blaikie6adc78e2013-02-18 22:06:02 +00009083 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
9084 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00009085 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
9086 return false;
9087 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009088 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00009089 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009090
9091 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00009092 if (!RD) return false;
9093 if (RD->isUnion()) return false;
9094 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9095 if (!CRD->isStandardLayout()) return false;
9096 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009097
Benjamin Kramer8c543672011-08-06 03:04:42 +00009098 // See if this is the last field decl in the record.
9099 const Decl *D = FD;
9100 while ((D = D->getNextDeclInContext()))
9101 if (isa<FieldDecl>(D))
9102 return false;
9103 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00009104}
9105
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009106void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009107 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00009108 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009109 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009110 if (IndexExpr->isValueDependent())
9111 return;
9112
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00009113 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009114 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009115 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009116 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009117 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00009118 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00009119
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009120 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +00009121 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +00009122 return;
Richard Smith13f67182011-12-16 19:31:14 +00009123 if (IndexNegated)
9124 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00009125
Craig Topperc3ec1492014-05-26 06:22:03 +00009126 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00009127 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9128 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00009129 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00009130 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00009131
Ted Kremeneke4b316c2011-02-23 23:06:04 +00009132 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009133 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00009134 if (!size.isStrictlyPositive())
9135 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009136
9137 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00009138 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009139 // Make sure we're comparing apples to apples when comparing index to size
9140 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
9141 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00009142 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00009143 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009144 if (ptrarith_typesize != array_typesize) {
9145 // There's a cast to a different size type involved
9146 uint64_t ratio = array_typesize / ptrarith_typesize;
9147 // TODO: Be smarter about handling cases where array_typesize is not a
9148 // multiple of ptrarith_typesize
9149 if (ptrarith_typesize * ratio == array_typesize)
9150 size *= llvm::APInt(size.getBitWidth(), ratio);
9151 }
9152 }
9153
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009154 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009155 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009156 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009157 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009158
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009159 // For array subscripting the index must be less than size, but for pointer
9160 // arithmetic also allow the index (offset) to be equal to size since
9161 // computing the next address after the end of the array is legal and
9162 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009163 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00009164 return;
9165
9166 // Also don't warn for arrays of size 1 which are members of some
9167 // structure. These are often used to approximate flexible arrays in C89
9168 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009169 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00009170 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009171
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009172 // Suppress the warning if the subscript expression (as identified by the
9173 // ']' location) and the index expression are both from macro expansions
9174 // within a system header.
9175 if (ASE) {
9176 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
9177 ASE->getRBracketLoc());
9178 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
9179 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
9180 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00009181 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009182 return;
9183 }
9184 }
9185
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009186 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009187 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009188 DiagID = diag::warn_array_index_exceeds_bounds;
9189
9190 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9191 PDiag(DiagID) << index.toString(10, true)
9192 << size.toString(10, true)
9193 << (unsigned)size.getLimitedValue(~0U)
9194 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009195 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009196 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009197 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009198 DiagID = diag::warn_ptr_arith_precedes_bounds;
9199 if (index.isNegative()) index = -index;
9200 }
9201
9202 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9203 PDiag(DiagID) << index.toString(10, true)
9204 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00009205 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00009206
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00009207 if (!ND) {
9208 // Try harder to find a NamedDecl to point at in the note.
9209 while (const ArraySubscriptExpr *ASE =
9210 dyn_cast<ArraySubscriptExpr>(BaseExpr))
9211 BaseExpr = ASE->getBase()->IgnoreParenCasts();
9212 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9213 ND = dyn_cast<NamedDecl>(DRE->getDecl());
9214 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9215 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9216 }
9217
Chandler Carruth1af88f12011-02-17 21:10:52 +00009218 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009219 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
9220 PDiag(diag::note_array_index_out_of_bounds)
9221 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00009222}
9223
Ted Kremenekdf26df72011-03-01 18:41:00 +00009224void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009225 int AllowOnePastEnd = 0;
9226 while (expr) {
9227 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00009228 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009229 case Stmt::ArraySubscriptExprClass: {
9230 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009231 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009232 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00009233 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009234 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009235 case Stmt::OMPArraySectionExprClass: {
9236 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
9237 if (ASE->getLowerBound())
9238 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
9239 /*ASE=*/nullptr, AllowOnePastEnd > 0);
9240 return;
9241 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009242 case Stmt::UnaryOperatorClass: {
9243 // Only unwrap the * and & unary operators
9244 const UnaryOperator *UO = cast<UnaryOperator>(expr);
9245 expr = UO->getSubExpr();
9246 switch (UO->getOpcode()) {
9247 case UO_AddrOf:
9248 AllowOnePastEnd++;
9249 break;
9250 case UO_Deref:
9251 AllowOnePastEnd--;
9252 break;
9253 default:
9254 return;
9255 }
9256 break;
9257 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009258 case Stmt::ConditionalOperatorClass: {
9259 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
9260 if (const Expr *lhs = cond->getLHS())
9261 CheckArrayAccess(lhs);
9262 if (const Expr *rhs = cond->getRHS())
9263 CheckArrayAccess(rhs);
9264 return;
9265 }
9266 default:
9267 return;
9268 }
Peter Collingbourne91147592011-04-15 00:35:48 +00009269 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009270}
John McCall31168b02011-06-15 23:02:42 +00009271
9272//===--- CHECK: Objective-C retain cycles ----------------------------------//
9273
9274namespace {
9275 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00009276 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00009277 VarDecl *Variable;
9278 SourceRange Range;
9279 SourceLocation Loc;
9280 bool Indirect;
9281
9282 void setLocsFrom(Expr *e) {
9283 Loc = e->getExprLoc();
9284 Range = e->getSourceRange();
9285 }
9286 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009287} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009288
9289/// Consider whether capturing the given variable can possibly lead to
9290/// a retain cycle.
9291static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00009292 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00009293 // lifetime. In MRR, it's captured strongly if the variable is
9294 // __block and has an appropriate type.
9295 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9296 return false;
9297
9298 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009299 if (ref)
9300 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00009301 return true;
9302}
9303
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009304static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00009305 while (true) {
9306 e = e->IgnoreParens();
9307 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
9308 switch (cast->getCastKind()) {
9309 case CK_BitCast:
9310 case CK_LValueBitCast:
9311 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00009312 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00009313 e = cast->getSubExpr();
9314 continue;
9315
John McCall31168b02011-06-15 23:02:42 +00009316 default:
9317 return false;
9318 }
9319 }
9320
9321 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
9322 ObjCIvarDecl *ivar = ref->getDecl();
9323 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9324 return false;
9325
9326 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009327 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00009328 return false;
9329
9330 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
9331 owner.Indirect = true;
9332 return true;
9333 }
9334
9335 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9336 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
9337 if (!var) return false;
9338 return considerVariable(var, ref, owner);
9339 }
9340
John McCall31168b02011-06-15 23:02:42 +00009341 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
9342 if (member->isArrow()) return false;
9343
9344 // Don't count this as an indirect ownership.
9345 e = member->getBase();
9346 continue;
9347 }
9348
John McCallfe96e0b2011-11-06 09:01:30 +00009349 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
9350 // Only pay attention to pseudo-objects on property references.
9351 ObjCPropertyRefExpr *pre
9352 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
9353 ->IgnoreParens());
9354 if (!pre) return false;
9355 if (pre->isImplicitProperty()) return false;
9356 ObjCPropertyDecl *property = pre->getExplicitProperty();
9357 if (!property->isRetaining() &&
9358 !(property->getPropertyIvarDecl() &&
9359 property->getPropertyIvarDecl()->getType()
9360 .getObjCLifetime() == Qualifiers::OCL_Strong))
9361 return false;
9362
9363 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009364 if (pre->isSuperReceiver()) {
9365 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
9366 if (!owner.Variable)
9367 return false;
9368 owner.Loc = pre->getLocation();
9369 owner.Range = pre->getSourceRange();
9370 return true;
9371 }
John McCallfe96e0b2011-11-06 09:01:30 +00009372 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
9373 ->getSourceExpr());
9374 continue;
9375 }
9376
John McCall31168b02011-06-15 23:02:42 +00009377 // Array ivars?
9378
9379 return false;
9380 }
9381}
9382
9383namespace {
9384 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
9385 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
9386 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009387 Context(Context), Variable(variable), Capturer(nullptr),
9388 VarWillBeReased(false) {}
9389 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00009390 VarDecl *Variable;
9391 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009392 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00009393
9394 void VisitDeclRefExpr(DeclRefExpr *ref) {
9395 if (ref->getDecl() == Variable && !Capturer)
9396 Capturer = ref;
9397 }
9398
John McCall31168b02011-06-15 23:02:42 +00009399 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
9400 if (Capturer) return;
9401 Visit(ref->getBase());
9402 if (Capturer && ref->isFreeIvar())
9403 Capturer = ref;
9404 }
9405
9406 void VisitBlockExpr(BlockExpr *block) {
9407 // Look inside nested blocks
9408 if (block->getBlockDecl()->capturesVariable(Variable))
9409 Visit(block->getBlockDecl()->getBody());
9410 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00009411
9412 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
9413 if (Capturer) return;
9414 if (OVE->getSourceExpr())
9415 Visit(OVE->getSourceExpr());
9416 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009417 void VisitBinaryOperator(BinaryOperator *BinOp) {
9418 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
9419 return;
9420 Expr *LHS = BinOp->getLHS();
9421 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
9422 if (DRE->getDecl() != Variable)
9423 return;
9424 if (Expr *RHS = BinOp->getRHS()) {
9425 RHS = RHS->IgnoreParenCasts();
9426 llvm::APSInt Value;
9427 VarWillBeReased =
9428 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
9429 }
9430 }
9431 }
John McCall31168b02011-06-15 23:02:42 +00009432 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009433} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009434
9435/// Check whether the given argument is a block which captures a
9436/// variable.
9437static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
9438 assert(owner.Variable && owner.Loc.isValid());
9439
9440 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00009441
9442 // Look through [^{...} copy] and Block_copy(^{...}).
9443 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
9444 Selector Cmd = ME->getSelector();
9445 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
9446 e = ME->getInstanceReceiver();
9447 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00009448 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00009449 e = e->IgnoreParenCasts();
9450 }
9451 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
9452 if (CE->getNumArgs() == 1) {
9453 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00009454 if (Fn) {
9455 const IdentifierInfo *FnI = Fn->getIdentifier();
9456 if (FnI && FnI->isStr("_Block_copy")) {
9457 e = CE->getArg(0)->IgnoreParenCasts();
9458 }
9459 }
Jordan Rose67e887c2012-09-17 17:54:30 +00009460 }
9461 }
9462
John McCall31168b02011-06-15 23:02:42 +00009463 BlockExpr *block = dyn_cast<BlockExpr>(e);
9464 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00009465 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00009466
9467 FindCaptureVisitor visitor(S.Context, owner.Variable);
9468 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009469 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00009470}
9471
9472static void diagnoseRetainCycle(Sema &S, Expr *capturer,
9473 RetainCycleOwner &owner) {
9474 assert(capturer);
9475 assert(owner.Variable && owner.Loc.isValid());
9476
9477 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
9478 << owner.Variable << capturer->getSourceRange();
9479 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
9480 << owner.Indirect << owner.Range;
9481}
9482
9483/// Check for a keyword selector that starts with the word 'add' or
9484/// 'set'.
9485static bool isSetterLikeSelector(Selector sel) {
9486 if (sel.isUnarySelector()) return false;
9487
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009488 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00009489 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009490 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00009491 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009492 else if (str.startswith("add")) {
9493 // Specially whitelist 'addOperationWithBlock:'.
9494 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
9495 return false;
9496 str = str.substr(3);
9497 }
John McCall31168b02011-06-15 23:02:42 +00009498 else
9499 return false;
9500
9501 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00009502 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00009503}
9504
Benjamin Kramer3a743452015-03-09 15:03:32 +00009505static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
9506 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009507 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
9508 Message->getReceiverInterface(),
9509 NSAPI::ClassId_NSMutableArray);
9510 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009511 return None;
9512 }
9513
9514 Selector Sel = Message->getSelector();
9515
9516 Optional<NSAPI::NSArrayMethodKind> MKOpt =
9517 S.NSAPIObj->getNSArrayMethodKind(Sel);
9518 if (!MKOpt) {
9519 return None;
9520 }
9521
9522 NSAPI::NSArrayMethodKind MK = *MKOpt;
9523
9524 switch (MK) {
9525 case NSAPI::NSMutableArr_addObject:
9526 case NSAPI::NSMutableArr_insertObjectAtIndex:
9527 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
9528 return 0;
9529 case NSAPI::NSMutableArr_replaceObjectAtIndex:
9530 return 1;
9531
9532 default:
9533 return None;
9534 }
9535
9536 return None;
9537}
9538
9539static
9540Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
9541 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009542 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
9543 Message->getReceiverInterface(),
9544 NSAPI::ClassId_NSMutableDictionary);
9545 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009546 return None;
9547 }
9548
9549 Selector Sel = Message->getSelector();
9550
9551 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
9552 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
9553 if (!MKOpt) {
9554 return None;
9555 }
9556
9557 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
9558
9559 switch (MK) {
9560 case NSAPI::NSMutableDict_setObjectForKey:
9561 case NSAPI::NSMutableDict_setValueForKey:
9562 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
9563 return 0;
9564
9565 default:
9566 return None;
9567 }
9568
9569 return None;
9570}
9571
9572static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009573 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
9574 Message->getReceiverInterface(),
9575 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +00009576
Alex Denisov5dfac812015-08-06 04:51:14 +00009577 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
9578 Message->getReceiverInterface(),
9579 NSAPI::ClassId_NSMutableOrderedSet);
9580 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009581 return None;
9582 }
9583
9584 Selector Sel = Message->getSelector();
9585
9586 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
9587 if (!MKOpt) {
9588 return None;
9589 }
9590
9591 NSAPI::NSSetMethodKind MK = *MKOpt;
9592
9593 switch (MK) {
9594 case NSAPI::NSMutableSet_addObject:
9595 case NSAPI::NSOrderedSet_setObjectAtIndex:
9596 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
9597 case NSAPI::NSOrderedSet_insertObjectAtIndex:
9598 return 0;
9599 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
9600 return 1;
9601 }
9602
9603 return None;
9604}
9605
9606void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
9607 if (!Message->isInstanceMessage()) {
9608 return;
9609 }
9610
9611 Optional<int> ArgOpt;
9612
9613 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
9614 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
9615 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
9616 return;
9617 }
9618
9619 int ArgIndex = *ArgOpt;
9620
Alex Denisove1d882c2015-03-04 17:55:52 +00009621 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
9622 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
9623 Arg = OE->getSourceExpr()->IgnoreImpCasts();
9624 }
9625
Alex Denisov5dfac812015-08-06 04:51:14 +00009626 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009627 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009628 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009629 Diag(Message->getSourceRange().getBegin(),
9630 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +00009631 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +00009632 }
9633 }
Alex Denisov5dfac812015-08-06 04:51:14 +00009634 } else {
9635 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
9636
9637 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
9638 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
9639 }
9640
9641 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
9642 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9643 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
9644 ValueDecl *Decl = ReceiverRE->getDecl();
9645 Diag(Message->getSourceRange().getBegin(),
9646 diag::warn_objc_circular_container)
9647 << Decl->getName() << Decl->getName();
9648 if (!ArgRE->isObjCSelfExpr()) {
9649 Diag(Decl->getLocation(),
9650 diag::note_objc_circular_container_declared_here)
9651 << Decl->getName();
9652 }
9653 }
9654 }
9655 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
9656 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
9657 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
9658 ObjCIvarDecl *Decl = IvarRE->getDecl();
9659 Diag(Message->getSourceRange().getBegin(),
9660 diag::warn_objc_circular_container)
9661 << Decl->getName() << Decl->getName();
9662 Diag(Decl->getLocation(),
9663 diag::note_objc_circular_container_declared_here)
9664 << Decl->getName();
9665 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009666 }
9667 }
9668 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009669}
9670
John McCall31168b02011-06-15 23:02:42 +00009671/// Check a message send to see if it's likely to cause a retain cycle.
9672void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
9673 // Only check instance methods whose selector looks like a setter.
9674 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
9675 return;
9676
9677 // Try to find a variable that the receiver is strongly owned by.
9678 RetainCycleOwner owner;
9679 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009680 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00009681 return;
9682 } else {
9683 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
9684 owner.Variable = getCurMethodDecl()->getSelfDecl();
9685 owner.Loc = msg->getSuperLoc();
9686 owner.Range = msg->getSuperLoc();
9687 }
9688
9689 // Check whether the receiver is captured by any of the arguments.
9690 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
9691 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
9692 return diagnoseRetainCycle(*this, capturer, owner);
9693}
9694
9695/// Check a property assign to see if it's likely to cause a retain cycle.
9696void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
9697 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009698 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00009699 return;
9700
9701 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
9702 diagnoseRetainCycle(*this, capturer, owner);
9703}
9704
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009705void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
9706 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00009707 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009708 return;
9709
9710 // Because we don't have an expression for the variable, we have to set the
9711 // location explicitly here.
9712 Owner.Loc = Var->getLocation();
9713 Owner.Range = Var->getSourceRange();
9714
9715 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
9716 diagnoseRetainCycle(*this, Capturer, Owner);
9717}
9718
Ted Kremenek9304da92012-12-21 08:04:28 +00009719static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
9720 Expr *RHS, bool isProperty) {
9721 // Check if RHS is an Objective-C object literal, which also can get
9722 // immediately zapped in a weak reference. Note that we explicitly
9723 // allow ObjCStringLiterals, since those are designed to never really die.
9724 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009725
Ted Kremenek64873352012-12-21 22:46:35 +00009726 // This enum needs to match with the 'select' in
9727 // warn_objc_arc_literal_assign (off-by-1).
9728 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
9729 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
9730 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009731
9732 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00009733 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00009734 << (isProperty ? 0 : 1)
9735 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009736
9737 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00009738}
9739
Ted Kremenekc1f014a2012-12-21 19:45:30 +00009740static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
9741 Qualifiers::ObjCLifetime LT,
9742 Expr *RHS, bool isProperty) {
9743 // Strip off any implicit cast added to get to the one ARC-specific.
9744 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9745 if (cast->getCastKind() == CK_ARCConsumeObject) {
9746 S.Diag(Loc, diag::warn_arc_retained_assign)
9747 << (LT == Qualifiers::OCL_ExplicitNone)
9748 << (isProperty ? 0 : 1)
9749 << RHS->getSourceRange();
9750 return true;
9751 }
9752 RHS = cast->getSubExpr();
9753 }
9754
9755 if (LT == Qualifiers::OCL_Weak &&
9756 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
9757 return true;
9758
9759 return false;
9760}
9761
Ted Kremenekb36234d2012-12-21 08:04:20 +00009762bool Sema::checkUnsafeAssigns(SourceLocation Loc,
9763 QualType LHS, Expr *RHS) {
9764 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
9765
9766 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
9767 return false;
9768
9769 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
9770 return true;
9771
9772 return false;
9773}
9774
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009775void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
9776 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009777 QualType LHSType;
9778 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00009779 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009780 ObjCPropertyRefExpr *PRE
9781 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
9782 if (PRE && !PRE->isImplicitProperty()) {
9783 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9784 if (PD)
9785 LHSType = PD->getType();
9786 }
9787
9788 if (LHSType.isNull())
9789 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00009790
9791 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
9792
9793 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009794 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00009795 getCurFunction()->markSafeWeakUse(LHS);
9796 }
9797
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009798 if (checkUnsafeAssigns(Loc, LHSType, RHS))
9799 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00009800
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009801 // FIXME. Check for other life times.
9802 if (LT != Qualifiers::OCL_None)
9803 return;
9804
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009805 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009806 if (PRE->isImplicitProperty())
9807 return;
9808 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9809 if (!PD)
9810 return;
9811
Bill Wendling44426052012-12-20 19:22:21 +00009812 unsigned Attributes = PD->getPropertyAttributes();
9813 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009814 // when 'assign' attribute was not explicitly specified
9815 // by user, ignore it and rely on property type itself
9816 // for lifetime info.
9817 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
9818 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
9819 LHSType->isObjCRetainableType())
9820 return;
9821
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009822 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00009823 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009824 Diag(Loc, diag::warn_arc_retained_property_assign)
9825 << RHS->getSourceRange();
9826 return;
9827 }
9828 RHS = cast->getSubExpr();
9829 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009830 }
Bill Wendling44426052012-12-20 19:22:21 +00009831 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00009832 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
9833 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00009834 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009835 }
9836}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009837
9838//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
9839
9840namespace {
9841bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
9842 SourceLocation StmtLoc,
9843 const NullStmt *Body) {
9844 // Do not warn if the body is a macro that expands to nothing, e.g:
9845 //
9846 // #define CALL(x)
9847 // if (condition)
9848 // CALL(0);
9849 //
9850 if (Body->hasLeadingEmptyMacro())
9851 return false;
9852
9853 // Get line numbers of statement and body.
9854 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +00009855 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009856 &StmtLineInvalid);
9857 if (StmtLineInvalid)
9858 return false;
9859
9860 bool BodyLineInvalid;
9861 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
9862 &BodyLineInvalid);
9863 if (BodyLineInvalid)
9864 return false;
9865
9866 // Warn if null statement and body are on the same line.
9867 if (StmtLine != BodyLine)
9868 return false;
9869
9870 return true;
9871}
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009872} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009873
9874void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
9875 const Stmt *Body,
9876 unsigned DiagID) {
9877 // Since this is a syntactic check, don't emit diagnostic for template
9878 // instantiations, this just adds noise.
9879 if (CurrentInstantiationScope)
9880 return;
9881
9882 // The body should be a null statement.
9883 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9884 if (!NBody)
9885 return;
9886
9887 // Do the usual checks.
9888 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9889 return;
9890
9891 Diag(NBody->getSemiLoc(), DiagID);
9892 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9893}
9894
9895void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
9896 const Stmt *PossibleBody) {
9897 assert(!CurrentInstantiationScope); // Ensured by caller
9898
9899 SourceLocation StmtLoc;
9900 const Stmt *Body;
9901 unsigned DiagID;
9902 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
9903 StmtLoc = FS->getRParenLoc();
9904 Body = FS->getBody();
9905 DiagID = diag::warn_empty_for_body;
9906 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
9907 StmtLoc = WS->getCond()->getSourceRange().getEnd();
9908 Body = WS->getBody();
9909 DiagID = diag::warn_empty_while_body;
9910 } else
9911 return; // Neither `for' nor `while'.
9912
9913 // The body should be a null statement.
9914 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9915 if (!NBody)
9916 return;
9917
9918 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009919 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009920 return;
9921
9922 // Do the usual checks.
9923 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9924 return;
9925
9926 // `for(...);' and `while(...);' are popular idioms, so in order to keep
9927 // noise level low, emit diagnostics only if for/while is followed by a
9928 // CompoundStmt, e.g.:
9929 // for (int i = 0; i < n; i++);
9930 // {
9931 // a(i);
9932 // }
9933 // or if for/while is followed by a statement with more indentation
9934 // than for/while itself:
9935 // for (int i = 0; i < n; i++);
9936 // a(i);
9937 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
9938 if (!ProbableTypo) {
9939 bool BodyColInvalid;
9940 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
9941 PossibleBody->getLocStart(),
9942 &BodyColInvalid);
9943 if (BodyColInvalid)
9944 return;
9945
9946 bool StmtColInvalid;
9947 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
9948 S->getLocStart(),
9949 &StmtColInvalid);
9950 if (StmtColInvalid)
9951 return;
9952
9953 if (BodyCol > StmtCol)
9954 ProbableTypo = true;
9955 }
9956
9957 if (ProbableTypo) {
9958 Diag(NBody->getSemiLoc(), DiagID);
9959 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9960 }
9961}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009962
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009963//===--- CHECK: Warn on self move with std::move. -------------------------===//
9964
9965/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
9966void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
9967 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009968 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
9969 return;
9970
9971 if (!ActiveTemplateInstantiations.empty())
9972 return;
9973
9974 // Strip parens and casts away.
9975 LHSExpr = LHSExpr->IgnoreParenImpCasts();
9976 RHSExpr = RHSExpr->IgnoreParenImpCasts();
9977
9978 // Check for a call expression
9979 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
9980 if (!CE || CE->getNumArgs() != 1)
9981 return;
9982
9983 // Check for a call to std::move
9984 const FunctionDecl *FD = CE->getDirectCallee();
9985 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
9986 !FD->getIdentifier()->isStr("move"))
9987 return;
9988
9989 // Get argument from std::move
9990 RHSExpr = CE->getArg(0);
9991
9992 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9993 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9994
9995 // Two DeclRefExpr's, check that the decls are the same.
9996 if (LHSDeclRef && RHSDeclRef) {
9997 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9998 return;
9999 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10000 RHSDeclRef->getDecl()->getCanonicalDecl())
10001 return;
10002
10003 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10004 << LHSExpr->getSourceRange()
10005 << RHSExpr->getSourceRange();
10006 return;
10007 }
10008
10009 // Member variables require a different approach to check for self moves.
10010 // MemberExpr's are the same if every nested MemberExpr refers to the same
10011 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
10012 // the base Expr's are CXXThisExpr's.
10013 const Expr *LHSBase = LHSExpr;
10014 const Expr *RHSBase = RHSExpr;
10015 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
10016 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
10017 if (!LHSME || !RHSME)
10018 return;
10019
10020 while (LHSME && RHSME) {
10021 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
10022 RHSME->getMemberDecl()->getCanonicalDecl())
10023 return;
10024
10025 LHSBase = LHSME->getBase();
10026 RHSBase = RHSME->getBase();
10027 LHSME = dyn_cast<MemberExpr>(LHSBase);
10028 RHSME = dyn_cast<MemberExpr>(RHSBase);
10029 }
10030
10031 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
10032 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
10033 if (LHSDeclRef && RHSDeclRef) {
10034 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10035 return;
10036 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10037 RHSDeclRef->getDecl()->getCanonicalDecl())
10038 return;
10039
10040 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10041 << LHSExpr->getSourceRange()
10042 << RHSExpr->getSourceRange();
10043 return;
10044 }
10045
10046 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
10047 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10048 << LHSExpr->getSourceRange()
10049 << RHSExpr->getSourceRange();
10050}
10051
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010052//===--- Layout compatibility ----------------------------------------------//
10053
10054namespace {
10055
10056bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
10057
10058/// \brief Check if two enumeration types are layout-compatible.
10059bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
10060 // C++11 [dcl.enum] p8:
10061 // Two enumeration types are layout-compatible if they have the same
10062 // underlying type.
10063 return ED1->isComplete() && ED2->isComplete() &&
10064 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
10065}
10066
10067/// \brief Check if two fields are layout-compatible.
10068bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
10069 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
10070 return false;
10071
10072 if (Field1->isBitField() != Field2->isBitField())
10073 return false;
10074
10075 if (Field1->isBitField()) {
10076 // Make sure that the bit-fields are the same length.
10077 unsigned Bits1 = Field1->getBitWidthValue(C);
10078 unsigned Bits2 = Field2->getBitWidthValue(C);
10079
10080 if (Bits1 != Bits2)
10081 return false;
10082 }
10083
10084 return true;
10085}
10086
10087/// \brief Check if two standard-layout structs are layout-compatible.
10088/// (C++11 [class.mem] p17)
10089bool isLayoutCompatibleStruct(ASTContext &C,
10090 RecordDecl *RD1,
10091 RecordDecl *RD2) {
10092 // If both records are C++ classes, check that base classes match.
10093 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
10094 // If one of records is a CXXRecordDecl we are in C++ mode,
10095 // thus the other one is a CXXRecordDecl, too.
10096 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
10097 // Check number of base classes.
10098 if (D1CXX->getNumBases() != D2CXX->getNumBases())
10099 return false;
10100
10101 // Check the base classes.
10102 for (CXXRecordDecl::base_class_const_iterator
10103 Base1 = D1CXX->bases_begin(),
10104 BaseEnd1 = D1CXX->bases_end(),
10105 Base2 = D2CXX->bases_begin();
10106 Base1 != BaseEnd1;
10107 ++Base1, ++Base2) {
10108 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
10109 return false;
10110 }
10111 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
10112 // If only RD2 is a C++ class, it should have zero base classes.
10113 if (D2CXX->getNumBases() > 0)
10114 return false;
10115 }
10116
10117 // Check the fields.
10118 RecordDecl::field_iterator Field2 = RD2->field_begin(),
10119 Field2End = RD2->field_end(),
10120 Field1 = RD1->field_begin(),
10121 Field1End = RD1->field_end();
10122 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
10123 if (!isLayoutCompatible(C, *Field1, *Field2))
10124 return false;
10125 }
10126 if (Field1 != Field1End || Field2 != Field2End)
10127 return false;
10128
10129 return true;
10130}
10131
10132/// \brief Check if two standard-layout unions are layout-compatible.
10133/// (C++11 [class.mem] p18)
10134bool isLayoutCompatibleUnion(ASTContext &C,
10135 RecordDecl *RD1,
10136 RecordDecl *RD2) {
10137 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010138 for (auto *Field2 : RD2->fields())
10139 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010140
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010141 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010142 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
10143 I = UnmatchedFields.begin(),
10144 E = UnmatchedFields.end();
10145
10146 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010147 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010148 bool Result = UnmatchedFields.erase(*I);
10149 (void) Result;
10150 assert(Result);
10151 break;
10152 }
10153 }
10154 if (I == E)
10155 return false;
10156 }
10157
10158 return UnmatchedFields.empty();
10159}
10160
10161bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
10162 if (RD1->isUnion() != RD2->isUnion())
10163 return false;
10164
10165 if (RD1->isUnion())
10166 return isLayoutCompatibleUnion(C, RD1, RD2);
10167 else
10168 return isLayoutCompatibleStruct(C, RD1, RD2);
10169}
10170
10171/// \brief Check if two types are layout-compatible in C++11 sense.
10172bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
10173 if (T1.isNull() || T2.isNull())
10174 return false;
10175
10176 // C++11 [basic.types] p11:
10177 // If two types T1 and T2 are the same type, then T1 and T2 are
10178 // layout-compatible types.
10179 if (C.hasSameType(T1, T2))
10180 return true;
10181
10182 T1 = T1.getCanonicalType().getUnqualifiedType();
10183 T2 = T2.getCanonicalType().getUnqualifiedType();
10184
10185 const Type::TypeClass TC1 = T1->getTypeClass();
10186 const Type::TypeClass TC2 = T2->getTypeClass();
10187
10188 if (TC1 != TC2)
10189 return false;
10190
10191 if (TC1 == Type::Enum) {
10192 return isLayoutCompatible(C,
10193 cast<EnumType>(T1)->getDecl(),
10194 cast<EnumType>(T2)->getDecl());
10195 } else if (TC1 == Type::Record) {
10196 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
10197 return false;
10198
10199 return isLayoutCompatible(C,
10200 cast<RecordType>(T1)->getDecl(),
10201 cast<RecordType>(T2)->getDecl());
10202 }
10203
10204 return false;
10205}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010206} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010207
10208//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
10209
10210namespace {
10211/// \brief Given a type tag expression find the type tag itself.
10212///
10213/// \param TypeExpr Type tag expression, as it appears in user's code.
10214///
10215/// \param VD Declaration of an identifier that appears in a type tag.
10216///
10217/// \param MagicValue Type tag magic value.
10218bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
10219 const ValueDecl **VD, uint64_t *MagicValue) {
10220 while(true) {
10221 if (!TypeExpr)
10222 return false;
10223
10224 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
10225
10226 switch (TypeExpr->getStmtClass()) {
10227 case Stmt::UnaryOperatorClass: {
10228 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
10229 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
10230 TypeExpr = UO->getSubExpr();
10231 continue;
10232 }
10233 return false;
10234 }
10235
10236 case Stmt::DeclRefExprClass: {
10237 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
10238 *VD = DRE->getDecl();
10239 return true;
10240 }
10241
10242 case Stmt::IntegerLiteralClass: {
10243 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
10244 llvm::APInt MagicValueAPInt = IL->getValue();
10245 if (MagicValueAPInt.getActiveBits() <= 64) {
10246 *MagicValue = MagicValueAPInt.getZExtValue();
10247 return true;
10248 } else
10249 return false;
10250 }
10251
10252 case Stmt::BinaryConditionalOperatorClass:
10253 case Stmt::ConditionalOperatorClass: {
10254 const AbstractConditionalOperator *ACO =
10255 cast<AbstractConditionalOperator>(TypeExpr);
10256 bool Result;
10257 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
10258 if (Result)
10259 TypeExpr = ACO->getTrueExpr();
10260 else
10261 TypeExpr = ACO->getFalseExpr();
10262 continue;
10263 }
10264 return false;
10265 }
10266
10267 case Stmt::BinaryOperatorClass: {
10268 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
10269 if (BO->getOpcode() == BO_Comma) {
10270 TypeExpr = BO->getRHS();
10271 continue;
10272 }
10273 return false;
10274 }
10275
10276 default:
10277 return false;
10278 }
10279 }
10280}
10281
10282/// \brief Retrieve the C type corresponding to type tag TypeExpr.
10283///
10284/// \param TypeExpr Expression that specifies a type tag.
10285///
10286/// \param MagicValues Registered magic values.
10287///
10288/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
10289/// kind.
10290///
10291/// \param TypeInfo Information about the corresponding C type.
10292///
10293/// \returns true if the corresponding C type was found.
10294bool GetMatchingCType(
10295 const IdentifierInfo *ArgumentKind,
10296 const Expr *TypeExpr, const ASTContext &Ctx,
10297 const llvm::DenseMap<Sema::TypeTagMagicValue,
10298 Sema::TypeTagData> *MagicValues,
10299 bool &FoundWrongKind,
10300 Sema::TypeTagData &TypeInfo) {
10301 FoundWrongKind = false;
10302
10303 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000010304 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010305
10306 uint64_t MagicValue;
10307
10308 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
10309 return false;
10310
10311 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000010312 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010313 if (I->getArgumentKind() != ArgumentKind) {
10314 FoundWrongKind = true;
10315 return false;
10316 }
10317 TypeInfo.Type = I->getMatchingCType();
10318 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
10319 TypeInfo.MustBeNull = I->getMustBeNull();
10320 return true;
10321 }
10322 return false;
10323 }
10324
10325 if (!MagicValues)
10326 return false;
10327
10328 llvm::DenseMap<Sema::TypeTagMagicValue,
10329 Sema::TypeTagData>::const_iterator I =
10330 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
10331 if (I == MagicValues->end())
10332 return false;
10333
10334 TypeInfo = I->second;
10335 return true;
10336}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010337} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010338
10339void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10340 uint64_t MagicValue, QualType Type,
10341 bool LayoutCompatible,
10342 bool MustBeNull) {
10343 if (!TypeTagForDatatypeMagicValues)
10344 TypeTagForDatatypeMagicValues.reset(
10345 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
10346
10347 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
10348 (*TypeTagForDatatypeMagicValues)[Magic] =
10349 TypeTagData(Type, LayoutCompatible, MustBeNull);
10350}
10351
10352namespace {
10353bool IsSameCharType(QualType T1, QualType T2) {
10354 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
10355 if (!BT1)
10356 return false;
10357
10358 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
10359 if (!BT2)
10360 return false;
10361
10362 BuiltinType::Kind T1Kind = BT1->getKind();
10363 BuiltinType::Kind T2Kind = BT2->getKind();
10364
10365 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
10366 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
10367 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
10368 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
10369}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010370} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010371
10372void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10373 const Expr * const *ExprArgs) {
10374 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
10375 bool IsPointerAttr = Attr->getIsPointer();
10376
10377 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
10378 bool FoundWrongKind;
10379 TypeTagData TypeInfo;
10380 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
10381 TypeTagForDatatypeMagicValues.get(),
10382 FoundWrongKind, TypeInfo)) {
10383 if (FoundWrongKind)
10384 Diag(TypeTagExpr->getExprLoc(),
10385 diag::warn_type_tag_for_datatype_wrong_kind)
10386 << TypeTagExpr->getSourceRange();
10387 return;
10388 }
10389
10390 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
10391 if (IsPointerAttr) {
10392 // Skip implicit cast of pointer to `void *' (as a function argument).
10393 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000010394 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000010395 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010396 ArgumentExpr = ICE->getSubExpr();
10397 }
10398 QualType ArgumentType = ArgumentExpr->getType();
10399
10400 // Passing a `void*' pointer shouldn't trigger a warning.
10401 if (IsPointerAttr && ArgumentType->isVoidPointerType())
10402 return;
10403
10404 if (TypeInfo.MustBeNull) {
10405 // Type tag with matching void type requires a null pointer.
10406 if (!ArgumentExpr->isNullPointerConstant(Context,
10407 Expr::NPC_ValueDependentIsNotNull)) {
10408 Diag(ArgumentExpr->getExprLoc(),
10409 diag::warn_type_safety_null_pointer_required)
10410 << ArgumentKind->getName()
10411 << ArgumentExpr->getSourceRange()
10412 << TypeTagExpr->getSourceRange();
10413 }
10414 return;
10415 }
10416
10417 QualType RequiredType = TypeInfo.Type;
10418 if (IsPointerAttr)
10419 RequiredType = Context.getPointerType(RequiredType);
10420
10421 bool mismatch = false;
10422 if (!TypeInfo.LayoutCompatible) {
10423 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
10424
10425 // C++11 [basic.fundamental] p1:
10426 // Plain char, signed char, and unsigned char are three distinct types.
10427 //
10428 // But we treat plain `char' as equivalent to `signed char' or `unsigned
10429 // char' depending on the current char signedness mode.
10430 if (mismatch)
10431 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
10432 RequiredType->getPointeeType())) ||
10433 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
10434 mismatch = false;
10435 } else
10436 if (IsPointerAttr)
10437 mismatch = !isLayoutCompatible(Context,
10438 ArgumentType->getPointeeType(),
10439 RequiredType->getPointeeType());
10440 else
10441 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
10442
10443 if (mismatch)
10444 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000010445 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010446 << TypeInfo.LayoutCompatible << RequiredType
10447 << ArgumentExpr->getSourceRange()
10448 << TypeTagExpr->getSourceRange();
10449}