blob: d16921c6c706d883a101910b9d12bd93f6248a17 [file] [log] [blame]
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002//
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
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000015#include "clang/AST/APValue.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000017#include "clang/AST/Attr.h"
18#include "clang/AST/AttrIterator.h"
Ken Dyck40775002010-01-11 17:06:35 +000019#include "clang/AST/CharUnits.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000020#include "clang/AST/Decl.h"
21#include "clang/AST/DeclBase.h"
John McCall28a0cf72010-08-25 07:42:41 +000022#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000023#include "clang/AST/DeclObjC.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000024#include "clang/AST/DeclarationName.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000026#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000027#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000028#include "clang/AST/ExprObjC.h"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000029#include "clang/AST/ExprOpenMP.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000030#include "clang/AST/NSAPI.h"
Akira Hatanaka2be04412018-04-17 19:13:41 +000031#include "clang/AST/NonTrivialTypeVisitor.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000032#include "clang/AST/OperationKinds.h"
33#include "clang/AST/Stmt.h"
34#include "clang/AST/TemplateBase.h"
35#include "clang/AST/Type.h"
36#include "clang/AST/TypeLoc.h"
37#include "clang/AST/UnresolvedSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "clang/Analysis/Analyses/FormatString.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000039#include "clang/Basic/AddressSpaces.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000040#include "clang/Basic/CharInfo.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000041#include "clang/Basic/Diagnostic.h"
42#include "clang/Basic/IdentifierTable.h"
43#include "clang/Basic/LLVM.h"
44#include "clang/Basic/LangOptions.h"
45#include "clang/Basic/OpenCLOptions.h"
46#include "clang/Basic/OperatorKinds.h"
47#include "clang/Basic/PartialDiagnostic.h"
48#include "clang/Basic/SourceLocation.h"
49#include "clang/Basic/SourceManager.h"
50#include "clang/Basic/Specifiers.h"
Yaxun Liu39195062017-08-04 18:16:31 +000051#include "clang/Basic/SyncScope.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000052#include "clang/Basic/TargetBuiltins.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000053#include "clang/Basic/TargetCXXABI.h"
Nate Begeman4904e322010-06-08 02:47:44 +000054#include "clang/Basic/TargetInfo.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000055#include "clang/Basic/TypeTraits.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000056#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000057#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000058#include "clang/Sema/Lookup.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000059#include "clang/Sema/Ownership.h"
60#include "clang/Sema/Scope.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000061#include "clang/Sema/ScopeInfo.h"
62#include "clang/Sema/Sema.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000063#include "clang/Sema/SemaInternal.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000064#include "llvm/ADT/APFloat.h"
65#include "llvm/ADT/APInt.h"
66#include "llvm/ADT/APSInt.h"
67#include "llvm/ADT/ArrayRef.h"
68#include "llvm/ADT/DenseMap.h"
69#include "llvm/ADT/FoldingSet.h"
70#include "llvm/ADT/None.h"
71#include "llvm/ADT/Optional.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000072#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000073#include "llvm/ADT/SmallBitVector.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000074#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000075#include "llvm/ADT/SmallString.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000076#include "llvm/ADT/SmallVector.h"
77#include "llvm/ADT/StringRef.h"
78#include "llvm/ADT/StringSwitch.h"
79#include "llvm/ADT/Triple.h"
80#include "llvm/Support/AtomicOrdering.h"
81#include "llvm/Support/Casting.h"
82#include "llvm/Support/Compiler.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000083#include "llvm/Support/ConvertUTF.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000084#include "llvm/Support/ErrorHandling.h"
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +000085#include "llvm/Support/Format.h"
86#include "llvm/Support/Locale.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000087#include "llvm/Support/MathExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000088#include "llvm/Support/raw_ostream.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000089#include <algorithm>
90#include <cassert>
91#include <cstddef>
92#include <cstdint>
93#include <functional>
94#include <limits>
95#include <string>
96#include <tuple>
97#include <utility>
Eugene Zelenko1ced5092016-02-12 22:53:10 +000098
Chris Lattnerb87b1b32007-08-10 20:18:51 +000099using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +0000100using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000101
Chris Lattnera26fb342009-02-18 17:49:48 +0000102SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
103 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +0000104 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
105 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +0000106}
107
John McCallbebede42011-02-26 05:39:39 +0000108/// Checks that a call expression's argument count is the desired number.
109/// This is useful when doing custom type-checking. Returns true on error.
110static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
111 unsigned argCount = call->getNumArgs();
112 if (argCount == desiredArgCount) return false;
113
114 if (argCount < desiredArgCount)
115 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
116 << 0 /*function call*/ << desiredArgCount << argCount
117 << call->getSourceRange();
118
119 // Highlight all the excess arguments.
120 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
121 call->getArg(argCount - 1)->getLocEnd());
Nico Weberade321e2018-04-10 18:53:28 +0000122
John McCallbebede42011-02-26 05:39:39 +0000123 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
124 << 0 /*function call*/ << desiredArgCount << argCount
125 << call->getArg(1)->getSourceRange();
126}
127
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000128/// Check that the first argument to __builtin_annotation is an integer
129/// and the second argument is a non-wide string literal.
130static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
131 if (checkArgCount(S, TheCall, 2))
132 return true;
133
134 // First argument should be an integer.
135 Expr *ValArg = TheCall->getArg(0);
136 QualType Ty = ValArg->getType();
137 if (!Ty->isIntegerType()) {
138 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
139 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000140 return true;
141 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000142
143 // Second argument should be a constant string.
144 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
145 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
146 if (!Literal || !Literal->isAscii()) {
147 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
148 << StrArg->getSourceRange();
149 return true;
150 }
151
152 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000153 return false;
154}
155
Reid Kleckner30701ed2017-09-05 20:27:35 +0000156static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
157 // We need at least one argument.
158 if (TheCall->getNumArgs() < 1) {
159 S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
160 << 0 << 1 << TheCall->getNumArgs()
161 << TheCall->getCallee()->getSourceRange();
162 return true;
163 }
164
165 // All arguments should be wide string literals.
166 for (Expr *Arg : TheCall->arguments()) {
167 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
168 if (!Literal || !Literal->isWide()) {
169 S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str)
170 << Arg->getSourceRange();
171 return true;
172 }
173 }
174
175 return false;
176}
177
Richard Smith6cbd65d2013-07-11 02:27:57 +0000178/// Check that the argument to __builtin_addressof is a glvalue, and set the
179/// result type to the corresponding pointer type.
180static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
181 if (checkArgCount(S, TheCall, 1))
182 return true;
183
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000184 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000185 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
186 if (ResultType.isNull())
187 return true;
188
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000189 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000190 TheCall->setType(ResultType);
191 return false;
192}
193
John McCall03107a42015-10-29 20:48:01 +0000194static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
195 if (checkArgCount(S, TheCall, 3))
196 return true;
197
198 // First two arguments should be integers.
199 for (unsigned I = 0; I < 2; ++I) {
200 Expr *Arg = TheCall->getArg(I);
201 QualType Ty = Arg->getType();
202 if (!Ty->isIntegerType()) {
203 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
204 << Ty << Arg->getSourceRange();
205 return true;
206 }
207 }
208
209 // Third argument should be a pointer to a non-const integer.
210 // IRGen correctly handles volatile, restrict, and address spaces, and
211 // the other qualifiers aren't possible.
212 {
213 Expr *Arg = TheCall->getArg(2);
214 QualType Ty = Arg->getType();
215 const auto *PtrTy = Ty->getAs<PointerType>();
216 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
217 !PtrTy->getPointeeType().isConstQualified())) {
218 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
219 << Ty << Arg->getSourceRange();
220 return true;
221 }
222 }
223
224 return false;
225}
226
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000227static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
Nico Weberade321e2018-04-10 18:53:28 +0000228 CallExpr *TheCall, unsigned SizeIdx,
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000229 unsigned DstSizeIdx) {
230 if (TheCall->getNumArgs() <= SizeIdx ||
231 TheCall->getNumArgs() <= DstSizeIdx)
232 return;
233
234 const Expr *SizeArg = TheCall->getArg(SizeIdx);
235 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
236
237 llvm::APSInt Size, DstSize;
238
239 // find out if both sizes are known at compile time
240 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
241 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
242 return;
243
244 if (Size.ule(DstSize))
245 return;
246
247 // confirmed overflow so generate the diagnostic.
248 IdentifierInfo *FnName = FDecl->getIdentifier();
249 SourceLocation SL = TheCall->getLocStart();
250 SourceRange SR = TheCall->getSourceRange();
251
252 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
253}
254
Peter Collingbournef7706832014-12-12 23:41:25 +0000255static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
256 if (checkArgCount(S, BuiltinCall, 2))
257 return true;
258
259 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
260 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
261 Expr *Call = BuiltinCall->getArg(0);
262 Expr *Chain = BuiltinCall->getArg(1);
263
264 if (Call->getStmtClass() != Stmt::CallExprClass) {
265 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
266 << Call->getSourceRange();
267 return true;
268 }
269
270 auto CE = cast<CallExpr>(Call);
271 if (CE->getCallee()->getType()->isBlockPointerType()) {
272 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
273 << Call->getSourceRange();
274 return true;
275 }
276
277 const Decl *TargetDecl = CE->getCalleeDecl();
278 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
279 if (FD->getBuiltinID()) {
280 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
281 << Call->getSourceRange();
282 return true;
283 }
284
285 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
286 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
287 << Call->getSourceRange();
288 return true;
289 }
290
291 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
292 if (ChainResult.isInvalid())
293 return true;
294 if (!ChainResult.get()->getType()->isPointerType()) {
295 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
296 << Chain->getSourceRange();
297 return true;
298 }
299
David Majnemerced8bdf2015-02-25 17:36:15 +0000300 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000301 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
302 QualType BuiltinTy = S.Context.getFunctionType(
303 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
304 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
305
306 Builtin =
307 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
308
309 BuiltinCall->setType(CE->getType());
310 BuiltinCall->setValueKind(CE->getValueKind());
311 BuiltinCall->setObjectKind(CE->getObjectKind());
312 BuiltinCall->setCallee(Builtin);
313 BuiltinCall->setArg(1, ChainResult.get());
314
315 return false;
316}
317
Reid Kleckner1d59f992015-01-22 01:36:17 +0000318static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
319 Scope::ScopeFlags NeededScopeFlags,
320 unsigned DiagID) {
321 // Scopes aren't available during instantiation. Fortunately, builtin
322 // functions cannot be template args so they cannot be formed through template
323 // instantiation. Therefore checking once during the parse is sufficient.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000324 if (SemaRef.inTemplateInstantiation())
Reid Kleckner1d59f992015-01-22 01:36:17 +0000325 return false;
326
327 Scope *S = SemaRef.getCurScope();
328 while (S && !S->isSEHExceptScope())
329 S = S->getParent();
330 if (!S || !(S->getFlags() & NeededScopeFlags)) {
331 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
332 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
333 << DRE->getDecl()->getIdentifier();
334 return true;
335 }
336
337 return false;
338}
339
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000340static inline bool isBlockPointer(Expr *Arg) {
341 return Arg->getType()->isBlockPointerType();
342}
343
344/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
345/// void*, which is a requirement of device side enqueue.
346static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
347 const BlockPointerType *BPT =
348 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
349 ArrayRef<QualType> Params =
350 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
351 unsigned ArgCounter = 0;
352 bool IllegalParams = false;
353 // Iterate through the block parameters until either one is found that is not
354 // a local void*, or the block is valid.
355 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
356 I != E; ++I, ++ArgCounter) {
357 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
358 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
359 LangAS::opencl_local) {
360 // Get the location of the error. If a block literal has been passed
361 // (BlockExpr) then we can point straight to the offending argument,
362 // else we just point to the variable reference.
363 SourceLocation ErrorLoc;
364 if (isa<BlockExpr>(BlockArg)) {
365 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
366 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
367 } else if (isa<DeclRefExpr>(BlockArg)) {
368 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
369 }
370 S.Diag(ErrorLoc,
371 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
372 IllegalParams = true;
373 }
374 }
375
376 return IllegalParams;
377}
378
Joey Gouly84ae3362017-07-31 15:15:59 +0000379static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
380 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
381 S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
382 << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
383 return true;
384 }
385 return false;
386}
387
Joey Goulyfa76b492017-08-01 13:27:09 +0000388static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
389 if (checkArgCount(S, TheCall, 2))
390 return true;
391
392 if (checkOpenCLSubgroupExt(S, TheCall))
393 return true;
394
395 // First argument is an ndrange_t type.
396 Expr *NDRangeArg = TheCall->getArg(0);
Yaxun Liub7318e02017-10-13 03:37:48 +0000397 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Joey Goulyfa76b492017-08-01 13:27:09 +0000398 S.Diag(NDRangeArg->getLocStart(),
399 diag::err_opencl_builtin_expected_type)
400 << TheCall->getDirectCallee() << "'ndrange_t'";
401 return true;
402 }
403
404 Expr *BlockArg = TheCall->getArg(1);
405 if (!isBlockPointer(BlockArg)) {
406 S.Diag(BlockArg->getLocStart(),
407 diag::err_opencl_builtin_expected_type)
408 << TheCall->getDirectCallee() << "block";
409 return true;
410 }
411 return checkOpenCLBlockArgs(S, BlockArg);
412}
413
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000414/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
415/// get_kernel_work_group_size
416/// and get_kernel_preferred_work_group_size_multiple builtin functions.
417static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
418 if (checkArgCount(S, TheCall, 1))
419 return true;
420
421 Expr *BlockArg = TheCall->getArg(0);
422 if (!isBlockPointer(BlockArg)) {
423 S.Diag(BlockArg->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000424 diag::err_opencl_builtin_expected_type)
425 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000426 return true;
427 }
428 return checkOpenCLBlockArgs(S, BlockArg);
429}
430
Simon Pilgrim2c518802017-03-30 14:13:19 +0000431/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000432static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
433 const QualType &IntType);
434
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000435static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000436 unsigned Start, unsigned End) {
437 bool IllegalParams = false;
438 for (unsigned I = Start; I <= End; ++I)
439 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
440 S.Context.getSizeType());
441 return IllegalParams;
442}
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000443
444/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
445/// 'local void*' parameter of passed block.
446static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
447 Expr *BlockArg,
448 unsigned NumNonVarArgs) {
449 const BlockPointerType *BPT =
450 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
451 unsigned NumBlockParams =
452 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
453 unsigned TotalNumArgs = TheCall->getNumArgs();
454
455 // For each argument passed to the block, a corresponding uint needs to
456 // be passed to describe the size of the local memory.
457 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
458 S.Diag(TheCall->getLocStart(),
459 diag::err_opencl_enqueue_kernel_local_size_args);
460 return true;
461 }
462
463 // Check that the sizes of the local memory are specified by integers.
464 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
465 TotalNumArgs - 1);
466}
467
468/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
469/// overload formats specified in Table 6.13.17.1.
470/// int enqueue_kernel(queue_t queue,
471/// kernel_enqueue_flags_t flags,
472/// const ndrange_t ndrange,
473/// void (^block)(void))
474/// int enqueue_kernel(queue_t queue,
475/// kernel_enqueue_flags_t flags,
476/// const ndrange_t ndrange,
477/// uint num_events_in_wait_list,
478/// clk_event_t *event_wait_list,
479/// clk_event_t *event_ret,
480/// void (^block)(void))
481/// int enqueue_kernel(queue_t queue,
482/// kernel_enqueue_flags_t flags,
483/// const ndrange_t ndrange,
484/// void (^block)(local void*, ...),
485/// uint size0, ...)
486/// int enqueue_kernel(queue_t queue,
487/// kernel_enqueue_flags_t flags,
488/// const ndrange_t ndrange,
489/// uint num_events_in_wait_list,
490/// clk_event_t *event_wait_list,
491/// clk_event_t *event_ret,
492/// void (^block)(local void*, ...),
493/// uint size0, ...)
494static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
495 unsigned NumArgs = TheCall->getNumArgs();
496
497 if (NumArgs < 4) {
498 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
499 return true;
500 }
501
502 Expr *Arg0 = TheCall->getArg(0);
503 Expr *Arg1 = TheCall->getArg(1);
504 Expr *Arg2 = TheCall->getArg(2);
505 Expr *Arg3 = TheCall->getArg(3);
506
507 // First argument always needs to be a queue_t type.
508 if (!Arg0->getType()->isQueueT()) {
509 S.Diag(TheCall->getArg(0)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000510 diag::err_opencl_builtin_expected_type)
511 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000512 return true;
513 }
514
515 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
516 if (!Arg1->getType()->isIntegerType()) {
517 S.Diag(TheCall->getArg(1)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000518 diag::err_opencl_builtin_expected_type)
519 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000520 return true;
521 }
522
523 // Third argument is always an ndrange_t type.
Anastasia Stulovab42f3c02017-04-21 15:13:24 +0000524 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000525 S.Diag(TheCall->getArg(2)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000526 diag::err_opencl_builtin_expected_type)
527 << TheCall->getDirectCallee() << "'ndrange_t'";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000528 return true;
529 }
530
531 // With four arguments, there is only one form that the function could be
532 // called in: no events and no variable arguments.
533 if (NumArgs == 4) {
534 // check that the last argument is the right block type.
535 if (!isBlockPointer(Arg3)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000536 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
537 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000538 return true;
539 }
540 // we have a block type, check the prototype
541 const BlockPointerType *BPT =
542 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
543 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
544 S.Diag(Arg3->getLocStart(),
545 diag::err_opencl_enqueue_kernel_blocks_no_args);
546 return true;
547 }
548 return false;
549 }
550 // we can have block + varargs.
551 if (isBlockPointer(Arg3))
552 return (checkOpenCLBlockArgs(S, Arg3) ||
553 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
554 // last two cases with either exactly 7 args or 7 args and varargs.
555 if (NumArgs >= 7) {
556 // check common block argument.
557 Expr *Arg6 = TheCall->getArg(6);
558 if (!isBlockPointer(Arg6)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000559 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
560 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000561 return true;
562 }
563 if (checkOpenCLBlockArgs(S, Arg6))
564 return true;
565
566 // Forth argument has to be any integer type.
567 if (!Arg3->getType()->isIntegerType()) {
568 S.Diag(TheCall->getArg(3)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000569 diag::err_opencl_builtin_expected_type)
570 << TheCall->getDirectCallee() << "integer";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000571 return true;
572 }
573 // check remaining common arguments.
574 Expr *Arg4 = TheCall->getArg(4);
575 Expr *Arg5 = TheCall->getArg(5);
576
Anastasia Stulova2b461202016-11-14 15:34:01 +0000577 // Fifth argument is always passed as a pointer to clk_event_t.
578 if (!Arg4->isNullPointerConstant(S.Context,
579 Expr::NPC_ValueDependentIsNotNull) &&
580 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000581 S.Diag(TheCall->getArg(4)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000582 diag::err_opencl_builtin_expected_type)
583 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000584 << S.Context.getPointerType(S.Context.OCLClkEventTy);
585 return true;
586 }
587
Anastasia Stulova2b461202016-11-14 15:34:01 +0000588 // Sixth argument is always passed as a pointer to clk_event_t.
589 if (!Arg5->isNullPointerConstant(S.Context,
590 Expr::NPC_ValueDependentIsNotNull) &&
591 !(Arg5->getType()->isPointerType() &&
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000592 Arg5->getType()->getPointeeType()->isClkEventT())) {
593 S.Diag(TheCall->getArg(5)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000594 diag::err_opencl_builtin_expected_type)
595 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000596 << S.Context.getPointerType(S.Context.OCLClkEventTy);
597 return true;
598 }
599
600 if (NumArgs == 7)
601 return false;
602
603 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
604 }
605
606 // None of the specific case has been detected, give generic error
607 S.Diag(TheCall->getLocStart(),
608 diag::err_opencl_enqueue_kernel_incorrect_args);
609 return true;
610}
611
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000612/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000613static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000614 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000615}
616
617/// Returns true if pipe element type is different from the pointer.
618static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
619 const Expr *Arg0 = Call->getArg(0);
620 // First argument type should always be pipe.
621 if (!Arg0->getType()->isPipeType()) {
622 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000623 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000624 return true;
625 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000626 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000627 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
628 // Validates the access qualifier is compatible with the call.
629 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
630 // read_only and write_only, and assumed to be read_only if no qualifier is
631 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000632 switch (Call->getDirectCallee()->getBuiltinID()) {
633 case Builtin::BIread_pipe:
634 case Builtin::BIreserve_read_pipe:
635 case Builtin::BIcommit_read_pipe:
636 case Builtin::BIwork_group_reserve_read_pipe:
637 case Builtin::BIsub_group_reserve_read_pipe:
638 case Builtin::BIwork_group_commit_read_pipe:
639 case Builtin::BIsub_group_commit_read_pipe:
640 if (!(!AccessQual || AccessQual->isReadOnly())) {
641 S.Diag(Arg0->getLocStart(),
642 diag::err_opencl_builtin_pipe_invalid_access_modifier)
643 << "read_only" << Arg0->getSourceRange();
644 return true;
645 }
646 break;
647 case Builtin::BIwrite_pipe:
648 case Builtin::BIreserve_write_pipe:
649 case Builtin::BIcommit_write_pipe:
650 case Builtin::BIwork_group_reserve_write_pipe:
651 case Builtin::BIsub_group_reserve_write_pipe:
652 case Builtin::BIwork_group_commit_write_pipe:
653 case Builtin::BIsub_group_commit_write_pipe:
654 if (!(AccessQual && AccessQual->isWriteOnly())) {
655 S.Diag(Arg0->getLocStart(),
656 diag::err_opencl_builtin_pipe_invalid_access_modifier)
657 << "write_only" << Arg0->getSourceRange();
658 return true;
659 }
660 break;
661 default:
662 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000663 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000664 return false;
665}
666
667/// Returns true if pipe element type is different from the pointer.
668static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
669 const Expr *Arg0 = Call->getArg(0);
670 const Expr *ArgIdx = Call->getArg(Idx);
671 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000672 const QualType EltTy = PipeTy->getElementType();
673 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000674 // The Idx argument should be a pointer and the type of the pointer and
675 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000676 if (!ArgTy ||
677 !S.Context.hasSameType(
678 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000679 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000680 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000681 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000682 return true;
683 }
684 return false;
685}
686
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000687// Performs semantic analysis for the read/write_pipe call.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000688// \param S Reference to the semantic analyzer.
689// \param Call A pointer to the builtin call.
690// \return True if a semantic error has been found, false otherwise.
691static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000692 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
693 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000694 switch (Call->getNumArgs()) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000695 case 2:
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000696 if (checkOpenCLPipeArg(S, Call))
697 return true;
698 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000699 // read/write_pipe(pipe T, T*).
700 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000701 if (checkOpenCLPipePacketType(S, Call, 1))
702 return true;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000703 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000704
705 case 4: {
706 if (checkOpenCLPipeArg(S, Call))
707 return true;
708 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000709 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
710 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000711 if (!Call->getArg(1)->getType()->isReserveIDT()) {
712 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000713 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000714 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000715 return true;
716 }
717
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000718 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000719 const Expr *Arg2 = Call->getArg(2);
720 if (!Arg2->getType()->isIntegerType() &&
721 !Arg2->getType()->isUnsignedIntegerType()) {
722 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000723 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000724 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000725 return true;
726 }
727
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000728 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000729 if (checkOpenCLPipePacketType(S, Call, 3))
730 return true;
731 } break;
732 default:
733 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000734 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000735 return true;
736 }
737
738 return false;
739}
740
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000741// Performs a semantic analysis on the {work_group_/sub_group_
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000742// /_}reserve_{read/write}_pipe
743// \param S Reference to the semantic analyzer.
744// \param Call The call to the builtin function to be analyzed.
745// \return True if a semantic error was found, false otherwise.
746static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
747 if (checkArgCount(S, Call, 2))
748 return true;
749
750 if (checkOpenCLPipeArg(S, Call))
751 return true;
752
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000753 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000754 if (!Call->getArg(1)->getType()->isIntegerType() &&
755 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
756 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000757 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000758 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000759 return true;
760 }
761
Joey Gouly922ca232017-08-09 14:52:47 +0000762 // Since return type of reserve_read/write_pipe built-in function is
763 // reserve_id_t, which is not defined in the builtin def file , we used int
764 // as return type and need to override the return type of these functions.
765 Call->setType(S.Context.OCLReserveIDTy);
766
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000767 return false;
768}
769
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000770// Performs a semantic analysis on {work_group_/sub_group_
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000771// /_}commit_{read/write}_pipe
772// \param S Reference to the semantic analyzer.
773// \param Call The call to the builtin function to be analyzed.
774// \return True if a semantic error was found, false otherwise.
775static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
776 if (checkArgCount(S, Call, 2))
777 return true;
778
779 if (checkOpenCLPipeArg(S, Call))
780 return true;
781
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000782 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000783 if (!Call->getArg(1)->getType()->isReserveIDT()) {
784 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000785 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000786 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000787 return true;
788 }
789
790 return false;
791}
792
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000793// Performs a semantic analysis on the call to built-in Pipe
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000794// Query Functions.
795// \param S Reference to the semantic analyzer.
796// \param Call The call to the builtin function to be analyzed.
797// \return True if a semantic error was found, false otherwise.
798static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
799 if (checkArgCount(S, Call, 1))
800 return true;
801
802 if (!Call->getArg(0)->getType()->isPipeType()) {
803 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000804 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000805 return true;
806 }
807
808 return false;
809}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000810
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000811// OpenCL v2.0 s6.13.9 - Address space qualifier functions.
812// Performs semantic analysis for the to_global/local/private call.
Yaxun Liuf7449a12016-05-20 19:54:38 +0000813// \param S Reference to the semantic analyzer.
814// \param BuiltinID ID of the builtin function.
815// \param Call A pointer to the builtin call.
816// \return True if a semantic error has been found, false otherwise.
817static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
818 CallExpr *Call) {
Yaxun Liuf7449a12016-05-20 19:54:38 +0000819 if (Call->getNumArgs() != 1) {
820 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
821 << Call->getDirectCallee() << Call->getSourceRange();
822 return true;
823 }
824
825 auto RT = Call->getArg(0)->getType();
826 if (!RT->isPointerType() || RT->getPointeeType()
827 .getAddressSpace() == LangAS::opencl_constant) {
828 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
829 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
830 return true;
831 }
832
833 RT = RT->getPointeeType();
834 auto Qual = RT.getQualifiers();
835 switch (BuiltinID) {
836 case Builtin::BIto_global:
837 Qual.setAddressSpace(LangAS::opencl_global);
838 break;
839 case Builtin::BIto_local:
840 Qual.setAddressSpace(LangAS::opencl_local);
841 break;
Yaxun Liub7318e02017-10-13 03:37:48 +0000842 case Builtin::BIto_private:
843 Qual.setAddressSpace(LangAS::opencl_private);
844 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +0000845 default:
Yaxun Liub7318e02017-10-13 03:37:48 +0000846 llvm_unreachable("Invalid builtin function");
Yaxun Liuf7449a12016-05-20 19:54:38 +0000847 }
848 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
849 RT.getUnqualifiedType(), Qual)));
850
851 return false;
852}
853
Reid Kleckneraa46ed92018-06-07 21:39:04 +0000854// Emit an error and return true if the current architecture is not in the list
855// of supported architectures.
856static bool
857CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
858 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
859 llvm::Triple::ArchType CurArch =
860 S.getASTContext().getTargetInfo().getTriple().getArch();
861 if (llvm::is_contained(SupportedArchs, CurArch))
862 return false;
863 S.Diag(TheCall->getLocStart(), diag::err_builtin_target_unsupported)
864 << TheCall->getSourceRange();
865 return true;
866}
867
John McCalldadc5752010-08-24 06:29:42 +0000868ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000869Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
870 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000871 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000872
Chris Lattner3be167f2010-10-01 23:23:24 +0000873 // Find out if any arguments are required to be integer constant expressions.
874 unsigned ICEArguments = 0;
875 ASTContext::GetBuiltinTypeError Error;
876 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
877 if (Error != ASTContext::GE_None)
878 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
879
880 // If any arguments are required to be ICE's, check and diagnose.
881 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
882 // Skip arguments not required to be ICE's.
883 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
884
885 llvm::APSInt Result;
886 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
887 return true;
888 ICEArguments &= ~(1 << ArgNo);
889 }
890
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000891 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000892 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000893 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000894 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000895 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000896 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000897 break;
Martin Storsjo022e7822017-07-17 20:49:45 +0000898 case Builtin::BI__builtin_ms_va_start:
Ted Kremeneka174c522008-07-09 17:58:53 +0000899 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000900 case Builtin::BI__builtin_va_start:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000901 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000902 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000903 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000904 case Builtin::BI__va_start: {
905 switch (Context.getTargetInfo().getTriple().getArch()) {
906 case llvm::Triple::arm:
907 case llvm::Triple::thumb:
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +0000908 if (SemaBuiltinVAStartARMMicrosoft(TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000909 return ExprError();
910 break;
911 default:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000912 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000913 return ExprError();
914 break;
915 }
916 break;
917 }
Reid Kleckneraa46ed92018-06-07 21:39:04 +0000918
919 // The acquire, release, and no fence variants are ARM and AArch64 only.
920 case Builtin::BI_interlockedbittestandset_acq:
921 case Builtin::BI_interlockedbittestandset_rel:
922 case Builtin::BI_interlockedbittestandset_nf:
923 case Builtin::BI_interlockedbittestandreset_acq:
924 case Builtin::BI_interlockedbittestandreset_rel:
925 case Builtin::BI_interlockedbittestandreset_nf:
926 if (CheckBuiltinTargetSupport(
927 *this, BuiltinID, TheCall,
928 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
929 return ExprError();
930 break;
931
932 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
933 case Builtin::BI_bittest64:
934 case Builtin::BI_bittestandcomplement64:
935 case Builtin::BI_bittestandreset64:
936 case Builtin::BI_bittestandset64:
937 case Builtin::BI_interlockedbittestandreset64:
938 case Builtin::BI_interlockedbittestandset64:
939 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
940 {llvm::Triple::x86_64, llvm::Triple::arm,
941 llvm::Triple::thumb, llvm::Triple::aarch64}))
942 return ExprError();
943 break;
944
Chris Lattner2da14fb2007-12-20 00:26:33 +0000945 case Builtin::BI__builtin_isgreater:
946 case Builtin::BI__builtin_isgreaterequal:
947 case Builtin::BI__builtin_isless:
948 case Builtin::BI__builtin_islessequal:
949 case Builtin::BI__builtin_islessgreater:
950 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000951 if (SemaBuiltinUnorderedCompare(TheCall))
952 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000953 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000954 case Builtin::BI__builtin_fpclassify:
955 if (SemaBuiltinFPClassification(TheCall, 6))
956 return ExprError();
957 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000958 case Builtin::BI__builtin_isfinite:
959 case Builtin::BI__builtin_isinf:
960 case Builtin::BI__builtin_isinf_sign:
961 case Builtin::BI__builtin_isnan:
962 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000963 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000964 return ExprError();
965 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000966 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000967 return SemaBuiltinShuffleVector(TheCall);
968 // TheCall will be freed by the smart pointer here, but that's fine, since
969 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000970 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000971 if (SemaBuiltinPrefetch(TheCall))
972 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000973 break;
David Majnemer51169932016-10-31 05:37:48 +0000974 case Builtin::BI__builtin_alloca_with_align:
975 if (SemaBuiltinAllocaWithAlign(TheCall))
976 return ExprError();
977 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000978 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000979 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000980 if (SemaBuiltinAssume(TheCall))
981 return ExprError();
982 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000983 case Builtin::BI__builtin_assume_aligned:
984 if (SemaBuiltinAssumeAligned(TheCall))
985 return ExprError();
986 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000987 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000988 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000989 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000990 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000991 case Builtin::BI__builtin_longjmp:
992 if (SemaBuiltinLongjmp(TheCall))
993 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000994 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000995 case Builtin::BI__builtin_setjmp:
996 if (SemaBuiltinSetjmp(TheCall))
997 return ExprError();
998 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000999 case Builtin::BI_setjmp:
1000 case Builtin::BI_setjmpex:
1001 if (checkArgCount(*this, TheCall, 1))
1002 return true;
1003 break;
John McCallbebede42011-02-26 05:39:39 +00001004 case Builtin::BI__builtin_classify_type:
1005 if (checkArgCount(*this, TheCall, 1)) return true;
1006 TheCall->setType(Context.IntTy);
1007 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +00001008 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +00001009 if (checkArgCount(*this, TheCall, 1)) return true;
1010 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +00001011 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001012 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +00001013 case Builtin::BI__sync_fetch_and_add_1:
1014 case Builtin::BI__sync_fetch_and_add_2:
1015 case Builtin::BI__sync_fetch_and_add_4:
1016 case Builtin::BI__sync_fetch_and_add_8:
1017 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001018 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +00001019 case Builtin::BI__sync_fetch_and_sub_1:
1020 case Builtin::BI__sync_fetch_and_sub_2:
1021 case Builtin::BI__sync_fetch_and_sub_4:
1022 case Builtin::BI__sync_fetch_and_sub_8:
1023 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001024 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +00001025 case Builtin::BI__sync_fetch_and_or_1:
1026 case Builtin::BI__sync_fetch_and_or_2:
1027 case Builtin::BI__sync_fetch_and_or_4:
1028 case Builtin::BI__sync_fetch_and_or_8:
1029 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001030 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +00001031 case Builtin::BI__sync_fetch_and_and_1:
1032 case Builtin::BI__sync_fetch_and_and_2:
1033 case Builtin::BI__sync_fetch_and_and_4:
1034 case Builtin::BI__sync_fetch_and_and_8:
1035 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001036 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +00001037 case Builtin::BI__sync_fetch_and_xor_1:
1038 case Builtin::BI__sync_fetch_and_xor_2:
1039 case Builtin::BI__sync_fetch_and_xor_4:
1040 case Builtin::BI__sync_fetch_and_xor_8:
1041 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001042 case Builtin::BI__sync_fetch_and_nand:
1043 case Builtin::BI__sync_fetch_and_nand_1:
1044 case Builtin::BI__sync_fetch_and_nand_2:
1045 case Builtin::BI__sync_fetch_and_nand_4:
1046 case Builtin::BI__sync_fetch_and_nand_8:
1047 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001048 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001049 case Builtin::BI__sync_add_and_fetch_1:
1050 case Builtin::BI__sync_add_and_fetch_2:
1051 case Builtin::BI__sync_add_and_fetch_4:
1052 case Builtin::BI__sync_add_and_fetch_8:
1053 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001054 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001055 case Builtin::BI__sync_sub_and_fetch_1:
1056 case Builtin::BI__sync_sub_and_fetch_2:
1057 case Builtin::BI__sync_sub_and_fetch_4:
1058 case Builtin::BI__sync_sub_and_fetch_8:
1059 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001060 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001061 case Builtin::BI__sync_and_and_fetch_1:
1062 case Builtin::BI__sync_and_and_fetch_2:
1063 case Builtin::BI__sync_and_and_fetch_4:
1064 case Builtin::BI__sync_and_and_fetch_8:
1065 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001066 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001067 case Builtin::BI__sync_or_and_fetch_1:
1068 case Builtin::BI__sync_or_and_fetch_2:
1069 case Builtin::BI__sync_or_and_fetch_4:
1070 case Builtin::BI__sync_or_and_fetch_8:
1071 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001072 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001073 case Builtin::BI__sync_xor_and_fetch_1:
1074 case Builtin::BI__sync_xor_and_fetch_2:
1075 case Builtin::BI__sync_xor_and_fetch_4:
1076 case Builtin::BI__sync_xor_and_fetch_8:
1077 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001078 case Builtin::BI__sync_nand_and_fetch:
1079 case Builtin::BI__sync_nand_and_fetch_1:
1080 case Builtin::BI__sync_nand_and_fetch_2:
1081 case Builtin::BI__sync_nand_and_fetch_4:
1082 case Builtin::BI__sync_nand_and_fetch_8:
1083 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001084 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001085 case Builtin::BI__sync_val_compare_and_swap_1:
1086 case Builtin::BI__sync_val_compare_and_swap_2:
1087 case Builtin::BI__sync_val_compare_and_swap_4:
1088 case Builtin::BI__sync_val_compare_and_swap_8:
1089 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001090 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001091 case Builtin::BI__sync_bool_compare_and_swap_1:
1092 case Builtin::BI__sync_bool_compare_and_swap_2:
1093 case Builtin::BI__sync_bool_compare_and_swap_4:
1094 case Builtin::BI__sync_bool_compare_and_swap_8:
1095 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001096 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +00001097 case Builtin::BI__sync_lock_test_and_set_1:
1098 case Builtin::BI__sync_lock_test_and_set_2:
1099 case Builtin::BI__sync_lock_test_and_set_4:
1100 case Builtin::BI__sync_lock_test_and_set_8:
1101 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001102 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001103 case Builtin::BI__sync_lock_release_1:
1104 case Builtin::BI__sync_lock_release_2:
1105 case Builtin::BI__sync_lock_release_4:
1106 case Builtin::BI__sync_lock_release_8:
1107 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001108 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001109 case Builtin::BI__sync_swap_1:
1110 case Builtin::BI__sync_swap_2:
1111 case Builtin::BI__sync_swap_4:
1112 case Builtin::BI__sync_swap_8:
1113 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001114 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001115 case Builtin::BI__builtin_nontemporal_load:
1116 case Builtin::BI__builtin_nontemporal_store:
1117 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +00001118#define BUILTIN(ID, TYPE, ATTRS)
1119#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1120 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001121 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +00001122#include "clang/Basic/Builtins.def"
Reid Kleckner30701ed2017-09-05 20:27:35 +00001123 case Builtin::BI__annotation:
1124 if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1125 return ExprError();
1126 break;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001127 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +00001128 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001129 return ExprError();
1130 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +00001131 case Builtin::BI__builtin_addressof:
1132 if (SemaBuiltinAddressof(*this, TheCall))
1133 return ExprError();
1134 break;
John McCall03107a42015-10-29 20:48:01 +00001135 case Builtin::BI__builtin_add_overflow:
1136 case Builtin::BI__builtin_sub_overflow:
1137 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +00001138 if (SemaBuiltinOverflow(*this, TheCall))
1139 return ExprError();
1140 break;
Richard Smith760520b2014-06-03 23:27:44 +00001141 case Builtin::BI__builtin_operator_new:
Eric Fiselierfa752f22018-03-21 19:19:48 +00001142 case Builtin::BI__builtin_operator_delete: {
1143 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1144 ExprResult Res =
1145 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1146 if (Res.isInvalid())
1147 CorrectDelayedTyposInExpr(TheCallResult.get());
1148 return Res;
1149 }
Aaron Ballman06525342018-04-10 21:58:13 +00001150 case Builtin::BI__builtin_dump_struct: {
1151 // We first want to ensure we are called with 2 arguments
1152 if (checkArgCount(*this, TheCall, 2))
1153 return ExprError();
1154 // Ensure that the first argument is of type 'struct XX *'
1155 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1156 const QualType PtrArgType = PtrArg->getType();
1157 if (!PtrArgType->isPointerType() ||
1158 !PtrArgType->getPointeeType()->isRecordType()) {
1159 Diag(PtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1160 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1161 << "structure pointer";
1162 return ExprError();
1163 }
1164
1165 // Ensure that the second argument is of type 'FunctionType'
1166 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1167 const QualType FnPtrArgType = FnPtrArg->getType();
1168 if (!FnPtrArgType->isPointerType()) {
1169 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1170 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1171 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1172 return ExprError();
1173 }
1174
1175 const auto *FuncType =
1176 FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1177
1178 if (!FuncType) {
1179 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1180 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1181 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1182 return ExprError();
1183 }
1184
1185 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1186 if (!FT->getNumParams()) {
1187 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1188 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1189 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1190 return ExprError();
1191 }
1192 QualType PT = FT->getParamType(0);
1193 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1194 !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1195 !PT->getPointeeType().isConstQualified()) {
1196 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1197 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1198 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1199 return ExprError();
1200 }
1201 }
1202
1203 TheCall->setType(Context.IntTy);
1204 break;
1205 }
1206
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001207 // check secure string manipulation functions where overflows
1208 // are detectable at compile time
1209 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001210 case Builtin::BI__builtin___memmove_chk:
1211 case Builtin::BI__builtin___memset_chk:
1212 case Builtin::BI__builtin___strlcat_chk:
1213 case Builtin::BI__builtin___strlcpy_chk:
1214 case Builtin::BI__builtin___strncat_chk:
1215 case Builtin::BI__builtin___strncpy_chk:
1216 case Builtin::BI__builtin___stpncpy_chk:
1217 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1218 break;
Steven Wu566c14e2014-09-24 04:37:33 +00001219 case Builtin::BI__builtin___memccpy_chk:
1220 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1221 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001222 case Builtin::BI__builtin___snprintf_chk:
1223 case Builtin::BI__builtin___vsnprintf_chk:
1224 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1225 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001226 case Builtin::BI__builtin_call_with_static_chain:
1227 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1228 return ExprError();
1229 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001230 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001231 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001232 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1233 diag::err_seh___except_block))
1234 return ExprError();
1235 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001236 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001237 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001238 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1239 diag::err_seh___except_filter))
1240 return ExprError();
1241 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001242 case Builtin::BI__GetExceptionInfo:
1243 if (checkArgCount(*this, TheCall, 1))
1244 return ExprError();
1245
1246 if (CheckCXXThrowOperand(
1247 TheCall->getLocStart(),
1248 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1249 TheCall))
1250 return ExprError();
1251
1252 TheCall->setType(Context.VoidPtrTy);
1253 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001254 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001255 case Builtin::BIread_pipe:
1256 case Builtin::BIwrite_pipe:
1257 // Since those two functions are declared with var args, we need a semantic
1258 // check for the argument.
1259 if (SemaBuiltinRWPipe(*this, TheCall))
1260 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001261 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001262 break;
1263 case Builtin::BIreserve_read_pipe:
1264 case Builtin::BIreserve_write_pipe:
1265 case Builtin::BIwork_group_reserve_read_pipe:
1266 case Builtin::BIwork_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001267 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1268 return ExprError();
Joey Gouly84ae3362017-07-31 15:15:59 +00001269 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001270 case Builtin::BIsub_group_reserve_read_pipe:
1271 case Builtin::BIsub_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001272 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1273 SemaBuiltinReserveRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001274 return ExprError();
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001275 break;
1276 case Builtin::BIcommit_read_pipe:
1277 case Builtin::BIcommit_write_pipe:
1278 case Builtin::BIwork_group_commit_read_pipe:
1279 case Builtin::BIwork_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001280 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1281 return ExprError();
1282 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001283 case Builtin::BIsub_group_commit_read_pipe:
1284 case Builtin::BIsub_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001285 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1286 SemaBuiltinCommitRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001287 return ExprError();
1288 break;
1289 case Builtin::BIget_pipe_num_packets:
1290 case Builtin::BIget_pipe_max_packets:
1291 if (SemaBuiltinPipePackets(*this, TheCall))
1292 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001293 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001294 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001295 case Builtin::BIto_global:
1296 case Builtin::BIto_local:
1297 case Builtin::BIto_private:
1298 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1299 return ExprError();
1300 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001301 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1302 case Builtin::BIenqueue_kernel:
1303 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1304 return ExprError();
1305 break;
1306 case Builtin::BIget_kernel_work_group_size:
1307 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1308 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1309 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001310 break;
Joey Goulyfa76b492017-08-01 13:27:09 +00001311 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1312 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1313 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1314 return ExprError();
1315 break;
Mehdi Amini06d367c2016-10-24 20:39:34 +00001316 case Builtin::BI__builtin_os_log_format:
1317 case Builtin::BI__builtin_os_log_format_buffer_size:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001318 if (SemaBuiltinOSLogFormat(TheCall))
Mehdi Amini06d367c2016-10-24 20:39:34 +00001319 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001320 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001321 }
Richard Smith760520b2014-06-03 23:27:44 +00001322
Nate Begeman4904e322010-06-08 02:47:44 +00001323 // Since the target specific builtins for each arch overlap, only check those
1324 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001325 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001326 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001327 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001328 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001329 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001330 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001331 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1332 return ExprError();
1333 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001334 case llvm::Triple::aarch64:
1335 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001336 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001337 return ExprError();
1338 break;
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00001339 case llvm::Triple::hexagon:
1340 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1341 return ExprError();
1342 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001343 case llvm::Triple::mips:
1344 case llvm::Triple::mipsel:
1345 case llvm::Triple::mips64:
1346 case llvm::Triple::mips64el:
1347 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1348 return ExprError();
1349 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001350 case llvm::Triple::systemz:
1351 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1352 return ExprError();
1353 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001354 case llvm::Triple::x86:
1355 case llvm::Triple::x86_64:
1356 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1357 return ExprError();
1358 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001359 case llvm::Triple::ppc:
1360 case llvm::Triple::ppc64:
1361 case llvm::Triple::ppc64le:
1362 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1363 return ExprError();
1364 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001365 default:
1366 break;
1367 }
1368 }
1369
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001370 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001371}
1372
Nate Begeman91e1fea2010-06-14 05:21:25 +00001373// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001374static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001375 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001376 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001377 switch (Type.getEltType()) {
1378 case NeonTypeFlags::Int8:
1379 case NeonTypeFlags::Poly8:
1380 return shift ? 7 : (8 << IsQuad) - 1;
1381 case NeonTypeFlags::Int16:
1382 case NeonTypeFlags::Poly16:
1383 return shift ? 15 : (4 << IsQuad) - 1;
1384 case NeonTypeFlags::Int32:
1385 return shift ? 31 : (2 << IsQuad) - 1;
1386 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001387 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001388 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001389 case NeonTypeFlags::Poly128:
1390 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001391 case NeonTypeFlags::Float16:
1392 assert(!shift && "cannot shift float types!");
1393 return (4 << IsQuad) - 1;
1394 case NeonTypeFlags::Float32:
1395 assert(!shift && "cannot shift float types!");
1396 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001397 case NeonTypeFlags::Float64:
1398 assert(!shift && "cannot shift float types!");
1399 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001400 }
David Blaikie8a40f702012-01-17 06:56:22 +00001401 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001402}
1403
Bob Wilsone4d77232011-11-08 05:04:11 +00001404/// getNeonEltType - Return the QualType corresponding to the elements of
1405/// the vector type specified by the NeonTypeFlags. This is used to check
1406/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001407static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001408 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001409 switch (Flags.getEltType()) {
1410 case NeonTypeFlags::Int8:
1411 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1412 case NeonTypeFlags::Int16:
1413 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1414 case NeonTypeFlags::Int32:
1415 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1416 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001417 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001418 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1419 else
1420 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1421 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001422 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001423 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001424 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001425 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001426 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001427 if (IsInt64Long)
1428 return Context.UnsignedLongTy;
1429 else
1430 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001431 case NeonTypeFlags::Poly128:
1432 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001433 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001434 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001435 case NeonTypeFlags::Float32:
1436 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001437 case NeonTypeFlags::Float64:
1438 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001439 }
David Blaikie8a40f702012-01-17 06:56:22 +00001440 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001441}
1442
Tim Northover12670412014-02-19 10:37:05 +00001443bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001444 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001445 uint64_t mask = 0;
1446 unsigned TV = 0;
1447 int PtrArgNum = -1;
1448 bool HasConstPtr = false;
1449 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001450#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001451#include "clang/Basic/arm_neon.inc"
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00001452#include "clang/Basic/arm_fp16.inc"
Tim Northover12670412014-02-19 10:37:05 +00001453#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001454 }
1455
1456 // For NEON intrinsics which are overloaded on vector element type, validate
1457 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001458 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001459 if (mask) {
1460 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1461 return true;
1462
1463 TV = Result.getLimitedValue(64);
1464 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1465 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001466 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001467 }
1468
1469 if (PtrArgNum >= 0) {
1470 // Check that pointer arguments have the specified type.
1471 Expr *Arg = TheCall->getArg(PtrArgNum);
1472 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1473 Arg = ICE->getSubExpr();
1474 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1475 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001476
Tim Northovera2ee4332014-03-29 15:09:45 +00001477 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001478 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1479 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001480 bool IsInt64Long =
1481 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1482 QualType EltTy =
1483 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001484 if (HasConstPtr)
1485 EltTy = EltTy.withConst();
1486 QualType LHSTy = Context.getPointerType(EltTy);
1487 AssignConvertType ConvTy;
1488 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1489 if (RHS.isInvalid())
1490 return true;
1491 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1492 RHS.get(), AA_Assigning))
1493 return true;
1494 }
1495
1496 // For NEON intrinsics which take an immediate value as part of the
1497 // instruction, range check them here.
1498 unsigned i = 0, l = 0, u = 0;
1499 switch (BuiltinID) {
1500 default:
1501 return false;
Tim Northover12670412014-02-19 10:37:05 +00001502#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001503#include "clang/Basic/arm_neon.inc"
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00001504#include "clang/Basic/arm_fp16.inc"
Tim Northover12670412014-02-19 10:37:05 +00001505#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001506 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001507
Richard Sandiford28940af2014-04-16 08:47:51 +00001508 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001509}
1510
Tim Northovera2ee4332014-03-29 15:09:45 +00001511bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1512 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001513 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001514 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001515 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001516 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001517 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001518 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1519 BuiltinID == AArch64::BI__builtin_arm_strex ||
1520 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001521 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001522 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001523 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1524 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1525 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001526
1527 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1528
1529 // Ensure that we have the proper number of arguments.
1530 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1531 return true;
1532
1533 // Inspect the pointer argument of the atomic builtin. This should always be
1534 // a pointer type, whose element is an integral scalar or pointer type.
1535 // Because it is a pointer type, we don't have to worry about any implicit
1536 // casts here.
1537 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1538 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1539 if (PointerArgRes.isInvalid())
1540 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001541 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001542
1543 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1544 if (!pointerType) {
1545 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1546 << PointerArg->getType() << PointerArg->getSourceRange();
1547 return true;
1548 }
1549
1550 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1551 // task is to insert the appropriate casts into the AST. First work out just
1552 // what the appropriate type is.
1553 QualType ValType = pointerType->getPointeeType();
1554 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1555 if (IsLdrex)
1556 AddrType.addConst();
1557
1558 // Issue a warning if the cast is dodgy.
1559 CastKind CastNeeded = CK_NoOp;
1560 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1561 CastNeeded = CK_BitCast;
1562 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1563 << PointerArg->getType()
1564 << Context.getPointerType(AddrType)
1565 << AA_Passing << PointerArg->getSourceRange();
1566 }
1567
1568 // Finally, do the cast and replace the argument with the corrected version.
1569 AddrType = Context.getPointerType(AddrType);
1570 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1571 if (PointerArgRes.isInvalid())
1572 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001573 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001574
1575 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1576
1577 // In general, we allow ints, floats and pointers to be loaded and stored.
1578 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1579 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1580 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1581 << PointerArg->getType() << PointerArg->getSourceRange();
1582 return true;
1583 }
1584
1585 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001586 if (Context.getTypeSize(ValType) > MaxWidth) {
1587 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001588 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1589 << PointerArg->getType() << PointerArg->getSourceRange();
1590 return true;
1591 }
1592
1593 switch (ValType.getObjCLifetime()) {
1594 case Qualifiers::OCL_None:
1595 case Qualifiers::OCL_ExplicitNone:
1596 // okay
1597 break;
1598
1599 case Qualifiers::OCL_Weak:
1600 case Qualifiers::OCL_Strong:
1601 case Qualifiers::OCL_Autoreleasing:
1602 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1603 << ValType << PointerArg->getSourceRange();
1604 return true;
1605 }
1606
Tim Northover6aacd492013-07-16 09:47:53 +00001607 if (IsLdrex) {
1608 TheCall->setType(ValType);
1609 return false;
1610 }
1611
1612 // Initialize the argument to be stored.
1613 ExprResult ValArg = TheCall->getArg(0);
1614 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1615 Context, ValType, /*consume*/ false);
1616 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1617 if (ValArg.isInvalid())
1618 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001619 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001620
1621 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1622 // but the custom checker bypasses all default analysis.
1623 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001624 return false;
1625}
1626
Nate Begeman4904e322010-06-08 02:47:44 +00001627bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001628 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001629 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1630 BuiltinID == ARM::BI__builtin_arm_strex ||
1631 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001632 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001633 }
1634
Yi Kong26d104a2014-08-13 19:18:14 +00001635 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1636 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1637 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1638 }
1639
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001640 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1641 BuiltinID == ARM::BI__builtin_arm_wsr64)
1642 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1643
1644 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1645 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1646 BuiltinID == ARM::BI__builtin_arm_wsr ||
1647 BuiltinID == ARM::BI__builtin_arm_wsrp)
1648 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1649
Tim Northover12670412014-02-19 10:37:05 +00001650 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1651 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001652
Yi Kong4efadfb2014-07-03 16:01:25 +00001653 // For intrinsics which take an immediate value as part of the instruction,
1654 // range check them here.
Sjoerd Meijer293da702017-12-07 09:54:39 +00001655 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begemand773fe62010-06-13 04:47:52 +00001656 switch (BuiltinID) {
1657 default: return false;
Sjoerd Meijer293da702017-12-07 09:54:39 +00001658 case ARM::BI__builtin_arm_ssat:
1659 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1660 case ARM::BI__builtin_arm_usat:
1661 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1662 case ARM::BI__builtin_arm_ssat16:
1663 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1664 case ARM::BI__builtin_arm_usat16:
1665 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
Nate Begemanf568b072010-08-03 21:32:34 +00001666 case ARM::BI__builtin_arm_vcvtr_f:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001667 case ARM::BI__builtin_arm_vcvtr_d:
1668 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
Weiming Zhao87bb4922013-11-12 21:42:50 +00001669 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001670 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001671 case ARM::BI__builtin_arm_isb:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001672 case ARM::BI__builtin_arm_dbg:
1673 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
Richard Sandiford28940af2014-04-16 08:47:51 +00001674 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001675}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001676
Tim Northover573cbee2014-05-24 12:52:07 +00001677bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001678 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001679 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001680 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1681 BuiltinID == AArch64::BI__builtin_arm_strex ||
1682 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001683 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1684 }
1685
Yi Konga5548432014-08-13 19:18:20 +00001686 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1687 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1688 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1689 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1690 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1691 }
1692
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001693 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1694 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001695 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001696
1697 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1698 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1699 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1700 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1701 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1702
Tim Northovera2ee4332014-03-29 15:09:45 +00001703 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1704 return true;
1705
Yi Kong19a29ac2014-07-17 10:52:06 +00001706 // For intrinsics which take an immediate value as part of the instruction,
1707 // range check them here.
1708 unsigned i = 0, l = 0, u = 0;
1709 switch (BuiltinID) {
1710 default: return false;
1711 case AArch64::BI__builtin_arm_dmb:
1712 case AArch64::BI__builtin_arm_dsb:
1713 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1714 }
1715
Yi Kong19a29ac2014-07-17 10:52:06 +00001716 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001717}
1718
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00001719bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
1720 CallExpr *TheCall) {
1721 struct ArgInfo {
1722 ArgInfo(unsigned O, bool S, unsigned W, unsigned A)
1723 : OpNum(O), IsSigned(S), BitWidth(W), Align(A) {}
1724 unsigned OpNum = 0;
1725 bool IsSigned = false;
1726 unsigned BitWidth = 0;
1727 unsigned Align = 0;
1728 };
1729
1730 static const std::map<unsigned, std::vector<ArgInfo>> Infos = {
1731 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
1732 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
1733 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
1734 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} },
1735 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
1736 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
1737 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
1738 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
1739 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
1740 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
1741 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
1742
1743 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
1744 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
1745 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
1746 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
1747 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
1748 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
1749 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
1750 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
1751 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
1752 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
1753 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
1754
1755 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
1756 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
1757 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
1758 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
1759 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
1760 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
1761 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
1762 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
1763 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
1764 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
1765 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
1766 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
1767 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
1768 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
1769 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
1770 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
1771 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
1772 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
1773 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
1774 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
1775 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
1776 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
1777 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
1778 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
1779 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
1780 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
1781 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
1782 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
1783 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
1784 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
1785 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
1786 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
1787 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
1788 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
1789 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
1790 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
1791 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
1792 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
1793 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
1794 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
1795 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
1796 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
1797 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
1798 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
1799 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
1800 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
1801 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
1802 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
1803 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
1804 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
1805 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
1806 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
1807 {{ 1, false, 6, 0 }} },
1808 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
1809 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
1810 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
1811 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
1812 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
1813 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
1814 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
1815 {{ 1, false, 5, 0 }} },
1816 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
1817 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
1818 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
1819 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
1820 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
1821 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
1822 { 2, false, 5, 0 }} },
1823 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
1824 { 2, false, 6, 0 }} },
1825 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
1826 { 3, false, 5, 0 }} },
1827 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
1828 { 3, false, 6, 0 }} },
1829 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
1830 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
1831 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
1832 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
1833 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
1834 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
1835 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
1836 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
1837 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
1838 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
1839 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
1840 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
1841 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
1842 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
1843 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
1844 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
1845 {{ 2, false, 4, 0 },
1846 { 3, false, 5, 0 }} },
1847 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
1848 {{ 2, false, 4, 0 },
1849 { 3, false, 5, 0 }} },
1850 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
1851 {{ 2, false, 4, 0 },
1852 { 3, false, 5, 0 }} },
1853 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
1854 {{ 2, false, 4, 0 },
1855 { 3, false, 5, 0 }} },
1856 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
1857 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
1858 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
1859 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
1860 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
1861 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
1862 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
1863 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
1864 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
1865 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
1866 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
1867 { 2, false, 5, 0 }} },
1868 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
1869 { 2, false, 6, 0 }} },
1870 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
1871 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
1872 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
1873 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
1874 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
1875 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
1876 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
1877 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
1878 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
1879 {{ 1, false, 4, 0 }} },
1880 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
1881 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
1882 {{ 1, false, 4, 0 }} },
1883 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
1884 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
1885 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
1886 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
1887 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
1888 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
1889 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
1890 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
1891 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
1892 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
1893 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
1894 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
1895 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
1896 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
1897 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
1898 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
1899 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
1900 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
1901 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
1902 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
1903 {{ 3, false, 1, 0 }} },
1904 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
1905 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
1906 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
1907 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
1908 {{ 3, false, 1, 0 }} },
1909 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
1910 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
1911 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
1912 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
1913 {{ 3, false, 1, 0 }} },
1914 };
1915
1916 auto F = Infos.find(BuiltinID);
1917 if (F == Infos.end())
1918 return false;
1919
1920 bool Error = false;
1921
1922 for (const ArgInfo &A : F->second) {
1923 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth-1)) : 0;
1924 int32_t Max = (1 << (A.IsSigned ? A.BitWidth-1 : A.BitWidth)) - 1;
1925 if (!A.Align) {
1926 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
1927 } else {
1928 unsigned M = 1 << A.Align;
1929 Min *= M;
1930 Max *= M;
1931 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
1932 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
1933 }
1934 }
1935 return Error;
1936}
1937
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001938// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1939// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1940// ordering for DSP is unspecified. MSA is ordered by the data format used
1941// by the underlying instruction i.e., df/m, df/n and then by size.
1942//
1943// FIXME: The size tests here should instead be tablegen'd along with the
1944// definitions from include/clang/Basic/BuiltinsMips.def.
1945// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1946// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001947bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001948 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001949 switch (BuiltinID) {
1950 default: return false;
1951 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1952 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001953 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1954 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1955 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1956 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1957 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001958 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1959 // df/m field.
1960 // These intrinsics take an unsigned 3 bit immediate.
1961 case Mips::BI__builtin_msa_bclri_b:
1962 case Mips::BI__builtin_msa_bnegi_b:
1963 case Mips::BI__builtin_msa_bseti_b:
1964 case Mips::BI__builtin_msa_sat_s_b:
1965 case Mips::BI__builtin_msa_sat_u_b:
1966 case Mips::BI__builtin_msa_slli_b:
1967 case Mips::BI__builtin_msa_srai_b:
1968 case Mips::BI__builtin_msa_srari_b:
1969 case Mips::BI__builtin_msa_srli_b:
1970 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1971 case Mips::BI__builtin_msa_binsli_b:
1972 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1973 // These intrinsics take an unsigned 4 bit immediate.
1974 case Mips::BI__builtin_msa_bclri_h:
1975 case Mips::BI__builtin_msa_bnegi_h:
1976 case Mips::BI__builtin_msa_bseti_h:
1977 case Mips::BI__builtin_msa_sat_s_h:
1978 case Mips::BI__builtin_msa_sat_u_h:
1979 case Mips::BI__builtin_msa_slli_h:
1980 case Mips::BI__builtin_msa_srai_h:
1981 case Mips::BI__builtin_msa_srari_h:
1982 case Mips::BI__builtin_msa_srli_h:
1983 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1984 case Mips::BI__builtin_msa_binsli_h:
1985 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001986 // These intrinsics take an unsigned 5 bit immediate.
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001987 // The first block of intrinsics actually have an unsigned 5 bit field,
1988 // not a df/n field.
1989 case Mips::BI__builtin_msa_clei_u_b:
1990 case Mips::BI__builtin_msa_clei_u_h:
1991 case Mips::BI__builtin_msa_clei_u_w:
1992 case Mips::BI__builtin_msa_clei_u_d:
1993 case Mips::BI__builtin_msa_clti_u_b:
1994 case Mips::BI__builtin_msa_clti_u_h:
1995 case Mips::BI__builtin_msa_clti_u_w:
1996 case Mips::BI__builtin_msa_clti_u_d:
1997 case Mips::BI__builtin_msa_maxi_u_b:
1998 case Mips::BI__builtin_msa_maxi_u_h:
1999 case Mips::BI__builtin_msa_maxi_u_w:
2000 case Mips::BI__builtin_msa_maxi_u_d:
2001 case Mips::BI__builtin_msa_mini_u_b:
2002 case Mips::BI__builtin_msa_mini_u_h:
2003 case Mips::BI__builtin_msa_mini_u_w:
2004 case Mips::BI__builtin_msa_mini_u_d:
2005 case Mips::BI__builtin_msa_addvi_b:
2006 case Mips::BI__builtin_msa_addvi_h:
2007 case Mips::BI__builtin_msa_addvi_w:
2008 case Mips::BI__builtin_msa_addvi_d:
2009 case Mips::BI__builtin_msa_bclri_w:
2010 case Mips::BI__builtin_msa_bnegi_w:
2011 case Mips::BI__builtin_msa_bseti_w:
2012 case Mips::BI__builtin_msa_sat_s_w:
2013 case Mips::BI__builtin_msa_sat_u_w:
2014 case Mips::BI__builtin_msa_slli_w:
2015 case Mips::BI__builtin_msa_srai_w:
2016 case Mips::BI__builtin_msa_srari_w:
2017 case Mips::BI__builtin_msa_srli_w:
2018 case Mips::BI__builtin_msa_srlri_w:
2019 case Mips::BI__builtin_msa_subvi_b:
2020 case Mips::BI__builtin_msa_subvi_h:
2021 case Mips::BI__builtin_msa_subvi_w:
2022 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2023 case Mips::BI__builtin_msa_binsli_w:
2024 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2025 // These intrinsics take an unsigned 6 bit immediate.
2026 case Mips::BI__builtin_msa_bclri_d:
2027 case Mips::BI__builtin_msa_bnegi_d:
2028 case Mips::BI__builtin_msa_bseti_d:
2029 case Mips::BI__builtin_msa_sat_s_d:
2030 case Mips::BI__builtin_msa_sat_u_d:
2031 case Mips::BI__builtin_msa_slli_d:
2032 case Mips::BI__builtin_msa_srai_d:
2033 case Mips::BI__builtin_msa_srari_d:
2034 case Mips::BI__builtin_msa_srli_d:
2035 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
2036 case Mips::BI__builtin_msa_binsli_d:
2037 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
2038 // These intrinsics take a signed 5 bit immediate.
2039 case Mips::BI__builtin_msa_ceqi_b:
2040 case Mips::BI__builtin_msa_ceqi_h:
2041 case Mips::BI__builtin_msa_ceqi_w:
2042 case Mips::BI__builtin_msa_ceqi_d:
2043 case Mips::BI__builtin_msa_clti_s_b:
2044 case Mips::BI__builtin_msa_clti_s_h:
2045 case Mips::BI__builtin_msa_clti_s_w:
2046 case Mips::BI__builtin_msa_clti_s_d:
2047 case Mips::BI__builtin_msa_clei_s_b:
2048 case Mips::BI__builtin_msa_clei_s_h:
2049 case Mips::BI__builtin_msa_clei_s_w:
2050 case Mips::BI__builtin_msa_clei_s_d:
2051 case Mips::BI__builtin_msa_maxi_s_b:
2052 case Mips::BI__builtin_msa_maxi_s_h:
2053 case Mips::BI__builtin_msa_maxi_s_w:
2054 case Mips::BI__builtin_msa_maxi_s_d:
2055 case Mips::BI__builtin_msa_mini_s_b:
2056 case Mips::BI__builtin_msa_mini_s_h:
2057 case Mips::BI__builtin_msa_mini_s_w:
2058 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
2059 // These intrinsics take an unsigned 8 bit immediate.
2060 case Mips::BI__builtin_msa_andi_b:
2061 case Mips::BI__builtin_msa_nori_b:
2062 case Mips::BI__builtin_msa_ori_b:
2063 case Mips::BI__builtin_msa_shf_b:
2064 case Mips::BI__builtin_msa_shf_h:
2065 case Mips::BI__builtin_msa_shf_w:
2066 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
2067 case Mips::BI__builtin_msa_bseli_b:
2068 case Mips::BI__builtin_msa_bmnzi_b:
2069 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
2070 // df/n format
2071 // These intrinsics take an unsigned 4 bit immediate.
2072 case Mips::BI__builtin_msa_copy_s_b:
2073 case Mips::BI__builtin_msa_copy_u_b:
2074 case Mips::BI__builtin_msa_insve_b:
2075 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002076 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
2077 // These intrinsics take an unsigned 3 bit immediate.
2078 case Mips::BI__builtin_msa_copy_s_h:
2079 case Mips::BI__builtin_msa_copy_u_h:
2080 case Mips::BI__builtin_msa_insve_h:
2081 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002082 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
2083 // These intrinsics take an unsigned 2 bit immediate.
2084 case Mips::BI__builtin_msa_copy_s_w:
2085 case Mips::BI__builtin_msa_copy_u_w:
2086 case Mips::BI__builtin_msa_insve_w:
2087 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002088 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
2089 // These intrinsics take an unsigned 1 bit immediate.
2090 case Mips::BI__builtin_msa_copy_s_d:
2091 case Mips::BI__builtin_msa_copy_u_d:
2092 case Mips::BI__builtin_msa_insve_d:
2093 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002094 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
2095 // Memory offsets and immediate loads.
2096 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00002097 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002098 case Mips::BI__builtin_msa_ldi_h:
2099 case Mips::BI__builtin_msa_ldi_w:
2100 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
2101 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
2102 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
2103 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
2104 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
2105 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
2106 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
2107 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
2108 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00002109 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00002110
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002111 if (!m)
2112 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2113
2114 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
2115 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00002116}
2117
Kit Bartone50adcb2015-03-30 19:40:59 +00002118bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2119 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00002120 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
2121 BuiltinID == PPC::BI__builtin_divdeu ||
2122 BuiltinID == PPC::BI__builtin_bpermd;
2123 bool IsTarget64Bit = Context.getTargetInfo()
2124 .getTypeWidth(Context
2125 .getTargetInfo()
2126 .getIntPtrType()) == 64;
2127 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
2128 BuiltinID == PPC::BI__builtin_divweu ||
2129 BuiltinID == PPC::BI__builtin_divde ||
2130 BuiltinID == PPC::BI__builtin_divdeu;
2131
2132 if (Is64BitBltin && !IsTarget64Bit)
2133 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
2134 << TheCall->getSourceRange();
2135
2136 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
2137 (BuiltinID == PPC::BI__builtin_bpermd &&
2138 !Context.getTargetInfo().hasFeature("bpermd")))
2139 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
2140 << TheCall->getSourceRange();
2141
Kit Bartone50adcb2015-03-30 19:40:59 +00002142 switch (BuiltinID) {
2143 default: return false;
2144 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
2145 case PPC::BI__builtin_altivec_crypto_vshasigmad:
2146 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2147 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
2148 case PPC::BI__builtin_tbegin:
2149 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
2150 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
2151 case PPC::BI__builtin_tabortwc:
2152 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
2153 case PPC::BI__builtin_tabortwci:
2154 case PPC::BI__builtin_tabortdci:
2155 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
2156 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Tony Jiangbbc48e92017-05-24 15:13:32 +00002157 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00002158 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00002159 return SemaBuiltinVSX(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00002160 }
2161 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2162}
2163
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00002164bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
2165 CallExpr *TheCall) {
2166 if (BuiltinID == SystemZ::BI__builtin_tabort) {
2167 Expr *Arg = TheCall->getArg(0);
2168 llvm::APSInt AbortCode(32);
2169 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
2170 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
2171 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
2172 << Arg->getSourceRange();
2173 }
2174
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002175 // For intrinsics which take an immediate value as part of the instruction,
2176 // range check them here.
2177 unsigned i = 0, l = 0, u = 0;
2178 switch (BuiltinID) {
2179 default: return false;
2180 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
2181 case SystemZ::BI__builtin_s390_verimb:
2182 case SystemZ::BI__builtin_s390_verimh:
2183 case SystemZ::BI__builtin_s390_verimf:
2184 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
2185 case SystemZ::BI__builtin_s390_vfaeb:
2186 case SystemZ::BI__builtin_s390_vfaeh:
2187 case SystemZ::BI__builtin_s390_vfaef:
2188 case SystemZ::BI__builtin_s390_vfaebs:
2189 case SystemZ::BI__builtin_s390_vfaehs:
2190 case SystemZ::BI__builtin_s390_vfaefs:
2191 case SystemZ::BI__builtin_s390_vfaezb:
2192 case SystemZ::BI__builtin_s390_vfaezh:
2193 case SystemZ::BI__builtin_s390_vfaezf:
2194 case SystemZ::BI__builtin_s390_vfaezbs:
2195 case SystemZ::BI__builtin_s390_vfaezhs:
2196 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00002197 case SystemZ::BI__builtin_s390_vfisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002198 case SystemZ::BI__builtin_s390_vfidb:
2199 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
2200 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00002201 case SystemZ::BI__builtin_s390_vftcisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002202 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
2203 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
2204 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
2205 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
2206 case SystemZ::BI__builtin_s390_vstrcb:
2207 case SystemZ::BI__builtin_s390_vstrch:
2208 case SystemZ::BI__builtin_s390_vstrcf:
2209 case SystemZ::BI__builtin_s390_vstrczb:
2210 case SystemZ::BI__builtin_s390_vstrczh:
2211 case SystemZ::BI__builtin_s390_vstrczf:
2212 case SystemZ::BI__builtin_s390_vstrcbs:
2213 case SystemZ::BI__builtin_s390_vstrchs:
2214 case SystemZ::BI__builtin_s390_vstrcfs:
2215 case SystemZ::BI__builtin_s390_vstrczbs:
2216 case SystemZ::BI__builtin_s390_vstrczhs:
2217 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00002218 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
2219 case SystemZ::BI__builtin_s390_vfminsb:
2220 case SystemZ::BI__builtin_s390_vfmaxsb:
2221 case SystemZ::BI__builtin_s390_vfmindb:
2222 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002223 }
2224 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00002225}
2226
Craig Topper5ba2c502015-11-07 08:08:31 +00002227/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
2228/// This checks that the target supports __builtin_cpu_supports and
2229/// that the string argument is constant and valid.
2230static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
2231 Expr *Arg = TheCall->getArg(0);
2232
2233 // Check if the argument is a string literal.
2234 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2235 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2236 << Arg->getSourceRange();
2237
2238 // Check the contents of the string.
2239 StringRef Feature =
2240 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2241 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
2242 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
2243 << Arg->getSourceRange();
2244 return false;
2245}
2246
Craig Topper699ae0c2017-08-10 20:28:30 +00002247/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
2248/// This checks that the target supports __builtin_cpu_is and
2249/// that the string argument is constant and valid.
2250static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
2251 Expr *Arg = TheCall->getArg(0);
2252
2253 // Check if the argument is a string literal.
2254 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2255 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2256 << Arg->getSourceRange();
2257
2258 // Check the contents of the string.
2259 StringRef Feature =
2260 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2261 if (!S.Context.getTargetInfo().validateCpuIs(Feature))
2262 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
2263 << Arg->getSourceRange();
2264 return false;
2265}
2266
Craig Toppera7e253e2016-09-23 04:48:31 +00002267// Check if the rounding mode is legal.
2268bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
2269 // Indicates if this instruction has rounding control or just SAE.
2270 bool HasRC = false;
2271
2272 unsigned ArgNum = 0;
2273 switch (BuiltinID) {
2274 default:
2275 return false;
2276 case X86::BI__builtin_ia32_vcvttsd2si32:
2277 case X86::BI__builtin_ia32_vcvttsd2si64:
2278 case X86::BI__builtin_ia32_vcvttsd2usi32:
2279 case X86::BI__builtin_ia32_vcvttsd2usi64:
2280 case X86::BI__builtin_ia32_vcvttss2si32:
2281 case X86::BI__builtin_ia32_vcvttss2si64:
2282 case X86::BI__builtin_ia32_vcvttss2usi32:
2283 case X86::BI__builtin_ia32_vcvttss2usi64:
2284 ArgNum = 1;
2285 break;
2286 case X86::BI__builtin_ia32_cvtps2pd512_mask:
2287 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
2288 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
2289 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
2290 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
2291 case X86::BI__builtin_ia32_cvttps2dq512_mask:
2292 case X86::BI__builtin_ia32_cvttps2qq512_mask:
2293 case X86::BI__builtin_ia32_cvttps2udq512_mask:
2294 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
2295 case X86::BI__builtin_ia32_exp2pd_mask:
2296 case X86::BI__builtin_ia32_exp2ps_mask:
2297 case X86::BI__builtin_ia32_getexppd512_mask:
2298 case X86::BI__builtin_ia32_getexpps512_mask:
2299 case X86::BI__builtin_ia32_rcp28pd_mask:
2300 case X86::BI__builtin_ia32_rcp28ps_mask:
2301 case X86::BI__builtin_ia32_rsqrt28pd_mask:
2302 case X86::BI__builtin_ia32_rsqrt28ps_mask:
2303 case X86::BI__builtin_ia32_vcomisd:
2304 case X86::BI__builtin_ia32_vcomiss:
2305 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
2306 ArgNum = 3;
2307 break;
2308 case X86::BI__builtin_ia32_cmppd512_mask:
2309 case X86::BI__builtin_ia32_cmpps512_mask:
2310 case X86::BI__builtin_ia32_cmpsd_mask:
2311 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002312 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00002313 case X86::BI__builtin_ia32_getexpsd128_round_mask:
2314 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002315 case X86::BI__builtin_ia32_maxpd512_mask:
2316 case X86::BI__builtin_ia32_maxps512_mask:
2317 case X86::BI__builtin_ia32_maxsd_round_mask:
2318 case X86::BI__builtin_ia32_maxss_round_mask:
2319 case X86::BI__builtin_ia32_minpd512_mask:
2320 case X86::BI__builtin_ia32_minps512_mask:
2321 case X86::BI__builtin_ia32_minsd_round_mask:
2322 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00002323 case X86::BI__builtin_ia32_rcp28sd_round_mask:
2324 case X86::BI__builtin_ia32_rcp28ss_round_mask:
2325 case X86::BI__builtin_ia32_reducepd512_mask:
2326 case X86::BI__builtin_ia32_reduceps512_mask:
2327 case X86::BI__builtin_ia32_rndscalepd_mask:
2328 case X86::BI__builtin_ia32_rndscaleps_mask:
2329 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2330 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2331 ArgNum = 4;
2332 break;
2333 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002334 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002335 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002336 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002337 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002338 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002339 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002340 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002341 case X86::BI__builtin_ia32_rangepd512_mask:
2342 case X86::BI__builtin_ia32_rangeps512_mask:
2343 case X86::BI__builtin_ia32_rangesd128_round_mask:
2344 case X86::BI__builtin_ia32_rangess128_round_mask:
2345 case X86::BI__builtin_ia32_reducesd_mask:
2346 case X86::BI__builtin_ia32_reducess_mask:
2347 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2348 case X86::BI__builtin_ia32_rndscaless_round_mask:
2349 ArgNum = 5;
2350 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00002351 case X86::BI__builtin_ia32_vcvtsd2si64:
2352 case X86::BI__builtin_ia32_vcvtsd2si32:
2353 case X86::BI__builtin_ia32_vcvtsd2usi32:
2354 case X86::BI__builtin_ia32_vcvtsd2usi64:
2355 case X86::BI__builtin_ia32_vcvtss2si32:
2356 case X86::BI__builtin_ia32_vcvtss2si64:
2357 case X86::BI__builtin_ia32_vcvtss2usi32:
2358 case X86::BI__builtin_ia32_vcvtss2usi64:
2359 ArgNum = 1;
2360 HasRC = true;
2361 break;
Craig Topper8e066312016-11-07 07:01:09 +00002362 case X86::BI__builtin_ia32_cvtsi2sd64:
2363 case X86::BI__builtin_ia32_cvtsi2ss32:
2364 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00002365 case X86::BI__builtin_ia32_cvtusi2sd64:
2366 case X86::BI__builtin_ia32_cvtusi2ss32:
2367 case X86::BI__builtin_ia32_cvtusi2ss64:
2368 ArgNum = 2;
2369 HasRC = true;
2370 break;
2371 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2372 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2373 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2374 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2375 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2376 case X86::BI__builtin_ia32_cvtps2qq512_mask:
2377 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2378 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2379 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2380 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2381 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002382 case X86::BI__builtin_ia32_sqrtpd512_mask:
2383 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002384 ArgNum = 3;
2385 HasRC = true;
2386 break;
2387 case X86::BI__builtin_ia32_addpd512_mask:
2388 case X86::BI__builtin_ia32_addps512_mask:
2389 case X86::BI__builtin_ia32_divpd512_mask:
2390 case X86::BI__builtin_ia32_divps512_mask:
2391 case X86::BI__builtin_ia32_mulpd512_mask:
2392 case X86::BI__builtin_ia32_mulps512_mask:
2393 case X86::BI__builtin_ia32_subpd512_mask:
2394 case X86::BI__builtin_ia32_subps512_mask:
2395 case X86::BI__builtin_ia32_addss_round_mask:
2396 case X86::BI__builtin_ia32_addsd_round_mask:
2397 case X86::BI__builtin_ia32_divss_round_mask:
2398 case X86::BI__builtin_ia32_divsd_round_mask:
2399 case X86::BI__builtin_ia32_mulss_round_mask:
2400 case X86::BI__builtin_ia32_mulsd_round_mask:
2401 case X86::BI__builtin_ia32_subss_round_mask:
2402 case X86::BI__builtin_ia32_subsd_round_mask:
2403 case X86::BI__builtin_ia32_scalefpd512_mask:
2404 case X86::BI__builtin_ia32_scalefps512_mask:
2405 case X86::BI__builtin_ia32_scalefsd_round_mask:
2406 case X86::BI__builtin_ia32_scalefss_round_mask:
2407 case X86::BI__builtin_ia32_getmantpd512_mask:
2408 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002409 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2410 case X86::BI__builtin_ia32_sqrtsd_round_mask:
2411 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002412 case X86::BI__builtin_ia32_vfmaddsd3_mask:
2413 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2414 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2415 case X86::BI__builtin_ia32_vfmaddss3_mask:
2416 case X86::BI__builtin_ia32_vfmaddss3_maskz:
2417 case X86::BI__builtin_ia32_vfmaddss3_mask3:
Craig Topperb92c77d2018-06-07 02:46:02 +00002418 case X86::BI__builtin_ia32_vfmaddpd512_mask:
2419 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2420 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2421 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2422 case X86::BI__builtin_ia32_vfmaddps512_mask:
2423 case X86::BI__builtin_ia32_vfmaddps512_maskz:
2424 case X86::BI__builtin_ia32_vfmaddps512_mask3:
2425 case X86::BI__builtin_ia32_vfmsubps512_mask3:
2426 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2427 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2428 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2429 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2430 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2431 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2432 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2433 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
Craig Topper7609f1c2016-10-01 21:03:50 +00002434 ArgNum = 4;
2435 HasRC = true;
2436 break;
2437 case X86::BI__builtin_ia32_getmantsd_round_mask:
2438 case X86::BI__builtin_ia32_getmantss_round_mask:
2439 ArgNum = 5;
2440 HasRC = true;
2441 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00002442 }
2443
2444 llvm::APSInt Result;
2445
2446 // We can't check the value of a dependent argument.
2447 Expr *Arg = TheCall->getArg(ArgNum);
2448 if (Arg->isTypeDependent() || Arg->isValueDependent())
2449 return false;
2450
2451 // Check constant-ness first.
2452 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2453 return true;
2454
2455 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2456 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2457 // combined with ROUND_NO_EXC.
2458 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2459 Result == 8/*ROUND_NO_EXC*/ ||
2460 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2461 return false;
2462
2463 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2464 << Arg->getSourceRange();
2465}
2466
Craig Topperdf5beb22017-03-13 17:16:50 +00002467// Check if the gather/scatter scale is legal.
2468bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2469 CallExpr *TheCall) {
2470 unsigned ArgNum = 0;
2471 switch (BuiltinID) {
2472 default:
2473 return false;
2474 case X86::BI__builtin_ia32_gatherpfdpd:
2475 case X86::BI__builtin_ia32_gatherpfdps:
2476 case X86::BI__builtin_ia32_gatherpfqpd:
2477 case X86::BI__builtin_ia32_gatherpfqps:
2478 case X86::BI__builtin_ia32_scatterpfdpd:
2479 case X86::BI__builtin_ia32_scatterpfdps:
2480 case X86::BI__builtin_ia32_scatterpfqpd:
2481 case X86::BI__builtin_ia32_scatterpfqps:
2482 ArgNum = 3;
2483 break;
2484 case X86::BI__builtin_ia32_gatherd_pd:
2485 case X86::BI__builtin_ia32_gatherd_pd256:
2486 case X86::BI__builtin_ia32_gatherq_pd:
2487 case X86::BI__builtin_ia32_gatherq_pd256:
2488 case X86::BI__builtin_ia32_gatherd_ps:
2489 case X86::BI__builtin_ia32_gatherd_ps256:
2490 case X86::BI__builtin_ia32_gatherq_ps:
2491 case X86::BI__builtin_ia32_gatherq_ps256:
2492 case X86::BI__builtin_ia32_gatherd_q:
2493 case X86::BI__builtin_ia32_gatherd_q256:
2494 case X86::BI__builtin_ia32_gatherq_q:
2495 case X86::BI__builtin_ia32_gatherq_q256:
2496 case X86::BI__builtin_ia32_gatherd_d:
2497 case X86::BI__builtin_ia32_gatherd_d256:
2498 case X86::BI__builtin_ia32_gatherq_d:
2499 case X86::BI__builtin_ia32_gatherq_d256:
2500 case X86::BI__builtin_ia32_gather3div2df:
2501 case X86::BI__builtin_ia32_gather3div2di:
2502 case X86::BI__builtin_ia32_gather3div4df:
2503 case X86::BI__builtin_ia32_gather3div4di:
2504 case X86::BI__builtin_ia32_gather3div4sf:
2505 case X86::BI__builtin_ia32_gather3div4si:
2506 case X86::BI__builtin_ia32_gather3div8sf:
2507 case X86::BI__builtin_ia32_gather3div8si:
2508 case X86::BI__builtin_ia32_gather3siv2df:
2509 case X86::BI__builtin_ia32_gather3siv2di:
2510 case X86::BI__builtin_ia32_gather3siv4df:
2511 case X86::BI__builtin_ia32_gather3siv4di:
2512 case X86::BI__builtin_ia32_gather3siv4sf:
2513 case X86::BI__builtin_ia32_gather3siv4si:
2514 case X86::BI__builtin_ia32_gather3siv8sf:
2515 case X86::BI__builtin_ia32_gather3siv8si:
2516 case X86::BI__builtin_ia32_gathersiv8df:
2517 case X86::BI__builtin_ia32_gathersiv16sf:
2518 case X86::BI__builtin_ia32_gatherdiv8df:
2519 case X86::BI__builtin_ia32_gatherdiv16sf:
2520 case X86::BI__builtin_ia32_gathersiv8di:
2521 case X86::BI__builtin_ia32_gathersiv16si:
2522 case X86::BI__builtin_ia32_gatherdiv8di:
2523 case X86::BI__builtin_ia32_gatherdiv16si:
2524 case X86::BI__builtin_ia32_scatterdiv2df:
2525 case X86::BI__builtin_ia32_scatterdiv2di:
2526 case X86::BI__builtin_ia32_scatterdiv4df:
2527 case X86::BI__builtin_ia32_scatterdiv4di:
2528 case X86::BI__builtin_ia32_scatterdiv4sf:
2529 case X86::BI__builtin_ia32_scatterdiv4si:
2530 case X86::BI__builtin_ia32_scatterdiv8sf:
2531 case X86::BI__builtin_ia32_scatterdiv8si:
2532 case X86::BI__builtin_ia32_scattersiv2df:
2533 case X86::BI__builtin_ia32_scattersiv2di:
2534 case X86::BI__builtin_ia32_scattersiv4df:
2535 case X86::BI__builtin_ia32_scattersiv4di:
2536 case X86::BI__builtin_ia32_scattersiv4sf:
2537 case X86::BI__builtin_ia32_scattersiv4si:
2538 case X86::BI__builtin_ia32_scattersiv8sf:
2539 case X86::BI__builtin_ia32_scattersiv8si:
2540 case X86::BI__builtin_ia32_scattersiv8df:
2541 case X86::BI__builtin_ia32_scattersiv16sf:
2542 case X86::BI__builtin_ia32_scatterdiv8df:
2543 case X86::BI__builtin_ia32_scatterdiv16sf:
2544 case X86::BI__builtin_ia32_scattersiv8di:
2545 case X86::BI__builtin_ia32_scattersiv16si:
2546 case X86::BI__builtin_ia32_scatterdiv8di:
2547 case X86::BI__builtin_ia32_scatterdiv16si:
2548 ArgNum = 4;
2549 break;
2550 }
2551
2552 llvm::APSInt Result;
2553
2554 // We can't check the value of a dependent argument.
2555 Expr *Arg = TheCall->getArg(ArgNum);
2556 if (Arg->isTypeDependent() || Arg->isValueDependent())
2557 return false;
2558
2559 // Check constant-ness first.
2560 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2561 return true;
2562
2563 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2564 return false;
2565
2566 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2567 << Arg->getSourceRange();
2568}
2569
Craig Topper51738f82018-04-26 20:14:46 +00002570static bool isX86_32Builtin(unsigned BuiltinID) {
2571 // These builtins only work on x86-32 targets.
2572 switch (BuiltinID) {
2573 case X86::BI__builtin_ia32_readeflags_u32:
2574 case X86::BI__builtin_ia32_writeeflags_u32:
2575 return true;
2576 }
2577
2578 return false;
2579}
2580
Craig Topperf0ddc892016-09-23 04:48:27 +00002581bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2582 if (BuiltinID == X86::BI__builtin_cpu_supports)
2583 return SemaBuiltinCpuSupports(*this, TheCall);
2584
Craig Topper699ae0c2017-08-10 20:28:30 +00002585 if (BuiltinID == X86::BI__builtin_cpu_is)
2586 return SemaBuiltinCpuIs(*this, TheCall);
2587
Craig Topper51738f82018-04-26 20:14:46 +00002588 // Check for 32-bit only builtins on a 64-bit target.
2589 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2590 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
2591 return Diag(TheCall->getCallee()->getLocStart(),
2592 diag::err_32_bit_builtin_64_bit_tgt);
2593
Craig Toppera7e253e2016-09-23 04:48:31 +00002594 // If the intrinsic has rounding or SAE make sure its valid.
2595 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2596 return true;
2597
Craig Topperdf5beb22017-03-13 17:16:50 +00002598 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2599 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2600 return true;
2601
Craig Topperf0ddc892016-09-23 04:48:27 +00002602 // For intrinsics which take an immediate value as part of the instruction,
2603 // range check them here.
2604 int i = 0, l = 0, u = 0;
2605 switch (BuiltinID) {
2606 default:
2607 return false;
Craig Topper11899b02018-06-05 21:54:35 +00002608 case X86::BI__builtin_ia32_vec_ext_v2si:
Craig Topperf3914b72018-06-06 00:24:55 +00002609 case X86::BI__builtin_ia32_vec_ext_v2di:
Craig Topper11899b02018-06-05 21:54:35 +00002610 i = 1; l = 0; u = 1;
2611 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002612 case X86::BI__builtin_ia32_vec_set_v2di:
2613 i = 2; l = 0; u = 1;
2614 break;
Craig Topperacf56012018-06-08 00:59:27 +00002615 case X86::BI__builtin_ia32_vpermilpd:
Craig Topper11899b02018-06-05 21:54:35 +00002616 case X86::BI__builtin_ia32_vec_ext_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00002617 case X86::BI__builtin_ia32_vec_ext_v4si:
2618 case X86::BI__builtin_ia32_vec_ext_v4sf:
2619 case X86::BI__builtin_ia32_vec_ext_v4di:
Craig Topper11899b02018-06-05 21:54:35 +00002620 i = 1; l = 0; u = 3;
2621 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002622 case X86::BI_mm_prefetch:
2623 case X86::BI__builtin_ia32_vec_ext_v8hi:
2624 case X86::BI__builtin_ia32_vec_ext_v8si:
2625 i = 1; l = 0; u = 7;
2626 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002627 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper7d17d722018-06-08 00:00:21 +00002628 case X86::BI__builtin_ia32_blendpd:
Craig Topper11899b02018-06-05 21:54:35 +00002629 case X86::BI__builtin_ia32_vec_set_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00002630 case X86::BI__builtin_ia32_vec_set_v4si:
2631 case X86::BI__builtin_ia32_vec_set_v4di:
Craig Topper93921362018-06-07 23:03:08 +00002632 case X86::BI__builtin_ia32_shuf_f32x4_256:
2633 case X86::BI__builtin_ia32_shuf_f64x2_256:
2634 case X86::BI__builtin_ia32_shuf_i32x4_256:
2635 case X86::BI__builtin_ia32_shuf_i64x2_256:
Craig Topper39c87102016-05-18 03:18:12 +00002636 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002637 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002638 case X86::BI__builtin_ia32_vpermil2pd:
2639 case X86::BI__builtin_ia32_vpermil2pd256:
2640 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002641 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002642 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002643 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002644 case X86::BI__builtin_ia32_cmpb128_mask:
2645 case X86::BI__builtin_ia32_cmpw128_mask:
2646 case X86::BI__builtin_ia32_cmpd128_mask:
2647 case X86::BI__builtin_ia32_cmpq128_mask:
2648 case X86::BI__builtin_ia32_cmpb256_mask:
2649 case X86::BI__builtin_ia32_cmpw256_mask:
2650 case X86::BI__builtin_ia32_cmpd256_mask:
2651 case X86::BI__builtin_ia32_cmpq256_mask:
2652 case X86::BI__builtin_ia32_cmpb512_mask:
2653 case X86::BI__builtin_ia32_cmpw512_mask:
2654 case X86::BI__builtin_ia32_cmpd512_mask:
2655 case X86::BI__builtin_ia32_cmpq512_mask:
2656 case X86::BI__builtin_ia32_ucmpb128_mask:
2657 case X86::BI__builtin_ia32_ucmpw128_mask:
2658 case X86::BI__builtin_ia32_ucmpd128_mask:
2659 case X86::BI__builtin_ia32_ucmpq128_mask:
2660 case X86::BI__builtin_ia32_ucmpb256_mask:
2661 case X86::BI__builtin_ia32_ucmpw256_mask:
2662 case X86::BI__builtin_ia32_ucmpd256_mask:
2663 case X86::BI__builtin_ia32_ucmpq256_mask:
2664 case X86::BI__builtin_ia32_ucmpb512_mask:
2665 case X86::BI__builtin_ia32_ucmpw512_mask:
2666 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002667 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002668 case X86::BI__builtin_ia32_vpcomub:
2669 case X86::BI__builtin_ia32_vpcomuw:
2670 case X86::BI__builtin_ia32_vpcomud:
2671 case X86::BI__builtin_ia32_vpcomuq:
2672 case X86::BI__builtin_ia32_vpcomb:
2673 case X86::BI__builtin_ia32_vpcomw:
2674 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002675 case X86::BI__builtin_ia32_vpcomq:
Craig Topperf3914b72018-06-06 00:24:55 +00002676 case X86::BI__builtin_ia32_vec_set_v8hi:
2677 case X86::BI__builtin_ia32_vec_set_v8si:
Craig Topper39c87102016-05-18 03:18:12 +00002678 i = 2; l = 0; u = 7;
2679 break;
Craig Topperacf56012018-06-08 00:59:27 +00002680 case X86::BI__builtin_ia32_vpermilpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002681 case X86::BI__builtin_ia32_roundps:
2682 case X86::BI__builtin_ia32_roundpd:
2683 case X86::BI__builtin_ia32_roundps256:
2684 case X86::BI__builtin_ia32_roundpd256:
Craig Topperf3914b72018-06-06 00:24:55 +00002685 case X86::BI__builtin_ia32_vec_ext_v16qi:
2686 case X86::BI__builtin_ia32_vec_ext_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00002687 i = 1; l = 0; u = 15;
2688 break;
Craig Topper7d17d722018-06-08 00:00:21 +00002689 case X86::BI__builtin_ia32_pblendd128:
2690 case X86::BI__builtin_ia32_blendps:
2691 case X86::BI__builtin_ia32_blendpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002692 case X86::BI__builtin_ia32_roundss:
2693 case X86::BI__builtin_ia32_roundsd:
2694 case X86::BI__builtin_ia32_rangepd128_mask:
2695 case X86::BI__builtin_ia32_rangepd256_mask:
2696 case X86::BI__builtin_ia32_rangepd512_mask:
2697 case X86::BI__builtin_ia32_rangeps128_mask:
2698 case X86::BI__builtin_ia32_rangeps256_mask:
2699 case X86::BI__builtin_ia32_rangeps512_mask:
2700 case X86::BI__builtin_ia32_getmantsd_round_mask:
2701 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00002702 case X86::BI__builtin_ia32_vec_set_v16qi:
2703 case X86::BI__builtin_ia32_vec_set_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00002704 i = 2; l = 0; u = 15;
2705 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002706 case X86::BI__builtin_ia32_vec_ext_v32qi:
2707 i = 1; l = 0; u = 31;
2708 break;
Craig Topper39c87102016-05-18 03:18:12 +00002709 case X86::BI__builtin_ia32_cmpps:
2710 case X86::BI__builtin_ia32_cmpss:
2711 case X86::BI__builtin_ia32_cmppd:
2712 case X86::BI__builtin_ia32_cmpsd:
2713 case X86::BI__builtin_ia32_cmpps256:
2714 case X86::BI__builtin_ia32_cmppd256:
2715 case X86::BI__builtin_ia32_cmpps128_mask:
2716 case X86::BI__builtin_ia32_cmppd128_mask:
2717 case X86::BI__builtin_ia32_cmpps256_mask:
2718 case X86::BI__builtin_ia32_cmppd256_mask:
2719 case X86::BI__builtin_ia32_cmpps512_mask:
2720 case X86::BI__builtin_ia32_cmppd512_mask:
2721 case X86::BI__builtin_ia32_cmpsd_mask:
2722 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00002723 case X86::BI__builtin_ia32_vec_set_v32qi:
Craig Topper39c87102016-05-18 03:18:12 +00002724 i = 2; l = 0; u = 31;
2725 break;
Craig Topperacf56012018-06-08 00:59:27 +00002726 case X86::BI__builtin_ia32_vpermilps:
2727 case X86::BI__builtin_ia32_vpermilps256:
2728 case X86::BI__builtin_ia32_vpermilpd512:
2729 case X86::BI__builtin_ia32_vpermilps512:
Craig Topper39c87102016-05-18 03:18:12 +00002730 case X86::BI__builtin_ia32_vcvtps2ph:
Craig Topper23a30222017-11-08 04:54:26 +00002731 case X86::BI__builtin_ia32_vcvtps2ph_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002732 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper23a30222017-11-08 04:54:26 +00002733 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2734 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002735 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2736 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2737 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2738 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2739 case X86::BI__builtin_ia32_rndscaleps_mask:
2740 case X86::BI__builtin_ia32_rndscalepd_mask:
2741 case X86::BI__builtin_ia32_reducepd128_mask:
2742 case X86::BI__builtin_ia32_reducepd256_mask:
2743 case X86::BI__builtin_ia32_reducepd512_mask:
2744 case X86::BI__builtin_ia32_reduceps128_mask:
2745 case X86::BI__builtin_ia32_reduceps256_mask:
2746 case X86::BI__builtin_ia32_reduceps512_mask:
2747 case X86::BI__builtin_ia32_prold512_mask:
2748 case X86::BI__builtin_ia32_prolq512_mask:
2749 case X86::BI__builtin_ia32_prold128_mask:
2750 case X86::BI__builtin_ia32_prold256_mask:
2751 case X86::BI__builtin_ia32_prolq128_mask:
2752 case X86::BI__builtin_ia32_prolq256_mask:
2753 case X86::BI__builtin_ia32_prord128_mask:
2754 case X86::BI__builtin_ia32_prord256_mask:
2755 case X86::BI__builtin_ia32_prorq128_mask:
2756 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002757 case X86::BI__builtin_ia32_fpclasspd128_mask:
2758 case X86::BI__builtin_ia32_fpclasspd256_mask:
2759 case X86::BI__builtin_ia32_fpclassps128_mask:
2760 case X86::BI__builtin_ia32_fpclassps256_mask:
2761 case X86::BI__builtin_ia32_fpclassps512_mask:
2762 case X86::BI__builtin_ia32_fpclasspd512_mask:
2763 case X86::BI__builtin_ia32_fpclasssd_mask:
2764 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002765 i = 1; l = 0; u = 255;
2766 break;
Craig Topper7d17d722018-06-08 00:00:21 +00002767 case X86::BI__builtin_ia32_pblendw128:
2768 case X86::BI__builtin_ia32_pblendw256:
2769 case X86::BI__builtin_ia32_blendps256:
2770 case X86::BI__builtin_ia32_pblendd256:
Craig Topper39c87102016-05-18 03:18:12 +00002771 case X86::BI__builtin_ia32_palignr128:
2772 case X86::BI__builtin_ia32_palignr256:
Craig Topper8e3689c2018-05-22 20:48:24 +00002773 case X86::BI__builtin_ia32_palignr512:
Craig Toppere56819e2018-06-07 21:27:41 +00002774 case X86::BI__builtin_ia32_alignq512:
2775 case X86::BI__builtin_ia32_alignd512:
2776 case X86::BI__builtin_ia32_alignd128:
2777 case X86::BI__builtin_ia32_alignd256:
2778 case X86::BI__builtin_ia32_alignq128:
2779 case X86::BI__builtin_ia32_alignq256:
Craig Topper39c87102016-05-18 03:18:12 +00002780 case X86::BI__builtin_ia32_vcomisd:
2781 case X86::BI__builtin_ia32_vcomiss:
Craig Topper93921362018-06-07 23:03:08 +00002782 case X86::BI__builtin_ia32_shuf_f32x4:
2783 case X86::BI__builtin_ia32_shuf_f64x2:
2784 case X86::BI__builtin_ia32_shuf_i32x4:
2785 case X86::BI__builtin_ia32_shuf_i64x2:
Craig Topper39c87102016-05-18 03:18:12 +00002786 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2787 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2788 case X86::BI__builtin_ia32_dbpsadbw512_mask:
Craig Topper91926432018-01-11 01:38:02 +00002789 case X86::BI__builtin_ia32_vpshldd128_mask:
2790 case X86::BI__builtin_ia32_vpshldd256_mask:
2791 case X86::BI__builtin_ia32_vpshldd512_mask:
2792 case X86::BI__builtin_ia32_vpshldq128_mask:
2793 case X86::BI__builtin_ia32_vpshldq256_mask:
2794 case X86::BI__builtin_ia32_vpshldq512_mask:
2795 case X86::BI__builtin_ia32_vpshldw128_mask:
2796 case X86::BI__builtin_ia32_vpshldw256_mask:
2797 case X86::BI__builtin_ia32_vpshldw512_mask:
2798 case X86::BI__builtin_ia32_vpshrdd128_mask:
2799 case X86::BI__builtin_ia32_vpshrdd256_mask:
2800 case X86::BI__builtin_ia32_vpshrdd512_mask:
2801 case X86::BI__builtin_ia32_vpshrdq128_mask:
2802 case X86::BI__builtin_ia32_vpshrdq256_mask:
2803 case X86::BI__builtin_ia32_vpshrdq512_mask:
2804 case X86::BI__builtin_ia32_vpshrdw128_mask:
2805 case X86::BI__builtin_ia32_vpshrdw256_mask:
2806 case X86::BI__builtin_ia32_vpshrdw512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002807 i = 2; l = 0; u = 255;
2808 break;
2809 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2810 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2811 case X86::BI__builtin_ia32_fixupimmps512_mask:
2812 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2813 case X86::BI__builtin_ia32_fixupimmsd_mask:
2814 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2815 case X86::BI__builtin_ia32_fixupimmss_mask:
2816 case X86::BI__builtin_ia32_fixupimmss_maskz:
2817 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2818 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2819 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2820 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2821 case X86::BI__builtin_ia32_fixupimmps128_mask:
2822 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2823 case X86::BI__builtin_ia32_fixupimmps256_mask:
2824 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2825 case X86::BI__builtin_ia32_pternlogd512_mask:
2826 case X86::BI__builtin_ia32_pternlogd512_maskz:
2827 case X86::BI__builtin_ia32_pternlogq512_mask:
2828 case X86::BI__builtin_ia32_pternlogq512_maskz:
2829 case X86::BI__builtin_ia32_pternlogd128_mask:
2830 case X86::BI__builtin_ia32_pternlogd128_maskz:
2831 case X86::BI__builtin_ia32_pternlogd256_mask:
2832 case X86::BI__builtin_ia32_pternlogd256_maskz:
2833 case X86::BI__builtin_ia32_pternlogq128_mask:
2834 case X86::BI__builtin_ia32_pternlogq128_maskz:
2835 case X86::BI__builtin_ia32_pternlogq256_mask:
2836 case X86::BI__builtin_ia32_pternlogq256_maskz:
2837 i = 3; l = 0; u = 255;
2838 break;
Craig Topper9625db02017-03-12 22:19:10 +00002839 case X86::BI__builtin_ia32_gatherpfdpd:
2840 case X86::BI__builtin_ia32_gatherpfdps:
2841 case X86::BI__builtin_ia32_gatherpfqpd:
2842 case X86::BI__builtin_ia32_gatherpfqps:
2843 case X86::BI__builtin_ia32_scatterpfdpd:
2844 case X86::BI__builtin_ia32_scatterpfdps:
2845 case X86::BI__builtin_ia32_scatterpfqpd:
2846 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00002847 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00002848 break;
Craig Topper39c87102016-05-18 03:18:12 +00002849 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2850 case X86::BI__builtin_ia32_rndscaless_round_mask:
2851 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002852 break;
Craig Topperd3623152018-06-07 17:28:03 +00002853 case X86::BI__builtin_ia32_pslldqi128:
2854 case X86::BI__builtin_ia32_pslldqi256:
2855 case X86::BI__builtin_ia32_pslldqi512:
2856 case X86::BI__builtin_ia32_psrldqi128:
2857 case X86::BI__builtin_ia32_psrldqi256:
2858 case X86::BI__builtin_ia32_psrldqi512:
2859 i = 1; l = 0; u = 1023;
2860 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002861 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002862 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002863}
2864
Richard Smith55ce3522012-06-25 20:30:08 +00002865/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2866/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2867/// Returns true when the format fits the function and the FormatStringInfo has
2868/// been populated.
2869bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2870 FormatStringInfo *FSI) {
2871 FSI->HasVAListArg = Format->getFirstArg() == 0;
2872 FSI->FormatIdx = Format->getFormatIdx() - 1;
2873 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002874
Richard Smith55ce3522012-06-25 20:30:08 +00002875 // The way the format attribute works in GCC, the implicit this argument
2876 // of member functions is counted. However, it doesn't appear in our own
2877 // lists, so decrement format_idx in that case.
2878 if (IsCXXMember) {
2879 if(FSI->FormatIdx == 0)
2880 return false;
2881 --FSI->FormatIdx;
2882 if (FSI->FirstDataArg != 0)
2883 --FSI->FirstDataArg;
2884 }
2885 return true;
2886}
Mike Stump11289f42009-09-09 15:08:12 +00002887
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002888/// Checks if a the given expression evaluates to null.
2889///
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002890/// Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002891static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002892 // If the expression has non-null type, it doesn't evaluate to null.
2893 if (auto nullability
2894 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2895 if (*nullability == NullabilityKind::NonNull)
2896 return false;
2897 }
2898
Ted Kremeneka146db32014-01-17 06:24:47 +00002899 // As a special case, transparent unions initialized with zero are
2900 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002901 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002902 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2903 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002904 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002905 if (const InitListExpr *ILE =
2906 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002907 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002908 }
2909
2910 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002911 return (!Expr->isValueDependent() &&
2912 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2913 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002914}
2915
2916static void CheckNonNullArgument(Sema &S,
2917 const Expr *ArgExpr,
2918 SourceLocation CallSiteLoc) {
2919 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002920 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2921 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002922}
2923
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002924bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2925 FormatStringInfo FSI;
2926 if ((GetFormatStringType(Format) == FST_NSString) &&
2927 getFormatStringInfo(Format, false, &FSI)) {
2928 Idx = FSI.FormatIdx;
2929 return true;
2930 }
2931 return false;
2932}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002933
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002934/// Diagnose use of %s directive in an NSString which is being passed
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002935/// as formatting string to formatting method.
2936static void
2937DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2938 const NamedDecl *FDecl,
2939 Expr **Args,
2940 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002941 unsigned Idx = 0;
2942 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002943 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2944 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002945 Idx = 2;
2946 Format = true;
2947 }
2948 else
2949 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2950 if (S.GetFormatNSStringIdx(I, Idx)) {
2951 Format = true;
2952 break;
2953 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002954 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002955 if (!Format || NumArgs <= Idx)
2956 return;
2957 const Expr *FormatExpr = Args[Idx];
2958 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2959 FormatExpr = CSCE->getSubExpr();
2960 const StringLiteral *FormatString;
2961 if (const ObjCStringLiteral *OSL =
2962 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2963 FormatString = OSL->getString();
2964 else
2965 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2966 if (!FormatString)
2967 return;
2968 if (S.FormatStringHasSArg(FormatString)) {
2969 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2970 << "%s" << 1 << 1;
2971 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2972 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002973 }
2974}
2975
Douglas Gregorb4866e82015-06-19 18:13:19 +00002976/// Determine whether the given type has a non-null nullability annotation.
2977static bool isNonNullType(ASTContext &ctx, QualType type) {
2978 if (auto nullability = type->getNullability(ctx))
2979 return *nullability == NullabilityKind::NonNull;
2980
2981 return false;
2982}
2983
Ted Kremenek2bc73332014-01-17 06:24:43 +00002984static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002985 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002986 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002987 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002988 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002989 assert((FDecl || Proto) && "Need a function declaration or prototype");
2990
Ted Kremenek9aedc152014-01-17 06:24:56 +00002991 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002992 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002993 if (FDecl) {
2994 // Handle the nonnull attribute on the function/method declaration itself.
2995 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2996 if (!NonNull->args_size()) {
2997 // Easy case: all pointer arguments are nonnull.
2998 for (const auto *Arg : Args)
2999 if (S.isValidPointerAttrType(Arg->getType()))
3000 CheckNonNullArgument(S, Arg, CallSiteLoc);
3001 return;
3002 }
Richard Smith588bd9b2014-08-27 04:59:42 +00003003
Joel E. Denny81508102018-03-13 14:51:22 +00003004 for (const ParamIdx &Idx : NonNull->args()) {
3005 unsigned IdxAST = Idx.getASTIndex();
3006 if (IdxAST >= Args.size())
Douglas Gregorb4866e82015-06-19 18:13:19 +00003007 continue;
3008 if (NonNullArgs.empty())
3009 NonNullArgs.resize(Args.size());
Joel E. Denny81508102018-03-13 14:51:22 +00003010 NonNullArgs.set(IdxAST);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003011 }
Richard Smith588bd9b2014-08-27 04:59:42 +00003012 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00003013 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00003014
Douglas Gregorb4866e82015-06-19 18:13:19 +00003015 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3016 // Handle the nonnull attribute on the parameters of the
3017 // function/method.
3018 ArrayRef<ParmVarDecl*> parms;
3019 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3020 parms = FD->parameters();
3021 else
3022 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3023
3024 unsigned ParamIndex = 0;
3025 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3026 I != E; ++I, ++ParamIndex) {
3027 const ParmVarDecl *PVD = *I;
3028 if (PVD->hasAttr<NonNullAttr>() ||
3029 isNonNullType(S.Context, PVD->getType())) {
3030 if (NonNullArgs.empty())
3031 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00003032
Douglas Gregorb4866e82015-06-19 18:13:19 +00003033 NonNullArgs.set(ParamIndex);
3034 }
3035 }
3036 } else {
3037 // If we have a non-function, non-method declaration but no
3038 // function prototype, try to dig out the function prototype.
3039 if (!Proto) {
3040 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3041 QualType type = VD->getType().getNonReferenceType();
3042 if (auto pointerType = type->getAs<PointerType>())
3043 type = pointerType->getPointeeType();
3044 else if (auto blockType = type->getAs<BlockPointerType>())
3045 type = blockType->getPointeeType();
3046 // FIXME: data member pointers?
3047
3048 // Dig out the function prototype, if there is one.
3049 Proto = type->getAs<FunctionProtoType>();
3050 }
3051 }
3052
3053 // Fill in non-null argument information from the nullability
3054 // information on the parameter types (if we have them).
3055 if (Proto) {
3056 unsigned Index = 0;
3057 for (auto paramType : Proto->getParamTypes()) {
3058 if (isNonNullType(S.Context, paramType)) {
3059 if (NonNullArgs.empty())
3060 NonNullArgs.resize(Args.size());
3061
3062 NonNullArgs.set(Index);
3063 }
3064
3065 ++Index;
3066 }
3067 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00003068 }
Richard Smith588bd9b2014-08-27 04:59:42 +00003069
Douglas Gregorb4866e82015-06-19 18:13:19 +00003070 // Check for non-null arguments.
3071 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3072 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00003073 if (NonNullArgs[ArgIndex])
3074 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003075 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00003076}
3077
Richard Smith55ce3522012-06-25 20:30:08 +00003078/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00003079/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
3080/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00003081void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00003082 const Expr *ThisArg, ArrayRef<const Expr *> Args,
3083 bool IsMemberFunction, SourceLocation Loc,
3084 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00003085 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00003086 if (CurContext->isDependentContext())
3087 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00003088
Ted Kremenekb8176da2010-09-09 04:33:05 +00003089 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00003090 llvm::SmallBitVector CheckedVarArgs;
3091 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003092 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00003093 // Only create vector if there are format attributes.
3094 CheckedVarArgs.resize(Args.size());
3095
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003096 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00003097 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00003098 }
Richard Smithd7293d72013-08-05 18:49:43 +00003099 }
Richard Smith55ce3522012-06-25 20:30:08 +00003100
3101 // Refuse POD arguments that weren't caught by the format string
3102 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00003103 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3104 if (CallType != VariadicDoesNotApply &&
3105 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00003106 unsigned NumParams = Proto ? Proto->getNumParams()
3107 : FDecl && isa<FunctionDecl>(FDecl)
3108 ? cast<FunctionDecl>(FDecl)->getNumParams()
3109 : FDecl && isa<ObjCMethodDecl>(FDecl)
3110 ? cast<ObjCMethodDecl>(FDecl)->param_size()
3111 : 0;
3112
Alp Toker9cacbab2014-01-20 20:26:09 +00003113 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00003114 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00003115 if (const Expr *Arg = Args[ArgIdx]) {
3116 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3117 checkVariadicArgument(Arg, CallType);
3118 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00003119 }
Richard Smithd7293d72013-08-05 18:49:43 +00003120 }
Mike Stump11289f42009-09-09 15:08:12 +00003121
Douglas Gregorb4866e82015-06-19 18:13:19 +00003122 if (FDecl || Proto) {
3123 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00003124
Richard Trieu41bc0992013-06-22 00:20:41 +00003125 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00003126 if (FDecl) {
3127 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +00003128 CheckArgumentWithTypeTag(I, Args, Loc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003129 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00003130 }
George Burgess IVce6284b2017-01-28 02:19:40 +00003131
3132 if (FD)
3133 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00003134}
3135
3136/// CheckConstructorCall - Check a constructor call for correctness and safety
3137/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003138void Sema::CheckConstructorCall(FunctionDecl *FDecl,
3139 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003140 const FunctionProtoType *Proto,
3141 SourceLocation Loc) {
3142 VariadicCallType CallType =
3143 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00003144 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
3145 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00003146}
3147
3148/// CheckFunctionCall - Check a direct function call for various correctness
3149/// and safety properties not strictly enforced by the C type system.
3150bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
3151 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00003152 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
3153 isa<CXXMethodDecl>(FDecl);
3154 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
3155 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00003156 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
3157 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00003158 Expr** Args = TheCall->getArgs();
3159 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00003160
3161 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00003162 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00003163 // If this is a call to a member operator, hide the first argument
3164 // from checkCall.
3165 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00003166 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00003167 ++Args;
3168 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00003169 } else if (IsMemberFunction)
3170 ImplicitThis =
3171 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
3172
3173 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00003174 IsMemberFunction, TheCall->getRParenLoc(),
3175 TheCall->getCallee()->getSourceRange(), CallType);
3176
3177 IdentifierInfo *FnInfo = FDecl->getIdentifier();
3178 // None of the checks below are needed for functions that don't have
3179 // simple names (e.g., C++ conversion functions).
3180 if (!FnInfo)
3181 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003182
Richard Trieua7f30b12016-12-06 01:42:28 +00003183 CheckAbsoluteValueFunction(TheCall, FDecl);
3184 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00003185
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003186 if (getLangOpts().ObjC1)
3187 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003188
Anna Zaks22122702012-01-17 00:37:07 +00003189 unsigned CMId = FDecl->getMemoryFunctionKind();
3190 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00003191 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00003192
Anna Zaks201d4892012-01-13 21:52:01 +00003193 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00003194 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00003195 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00003196 else if (CMId == Builtin::BIstrncat)
3197 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00003198 else
Anna Zaks22122702012-01-17 00:37:07 +00003199 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003200
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003201 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00003202}
3203
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003204bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00003205 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00003206 VariadicCallType CallType =
3207 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003208
George Burgess IVce6284b2017-01-28 02:19:40 +00003209 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
3210 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00003211 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003212
3213 return false;
3214}
3215
Richard Trieu664c4c62013-06-20 21:03:13 +00003216bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
3217 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00003218 QualType Ty;
3219 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00003220 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00003221 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00003222 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00003223 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003224 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003225
Douglas Gregorb4866e82015-06-19 18:13:19 +00003226 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
3227 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003228 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003229
Richard Trieu664c4c62013-06-20 21:03:13 +00003230 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00003231 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00003232 CallType = VariadicDoesNotApply;
3233 } else if (Ty->isBlockPointerType()) {
3234 CallType = VariadicBlock;
3235 } else { // Ty->isFunctionPointerType()
3236 CallType = VariadicFunction;
3237 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003238
George Burgess IVce6284b2017-01-28 02:19:40 +00003239 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00003240 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3241 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00003242 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00003243
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003244 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00003245}
3246
Richard Trieu41bc0992013-06-22 00:20:41 +00003247/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
3248/// such as function pointers returned from functions.
3249bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003250 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00003251 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00003252 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00003253 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00003254 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00003255 TheCall->getCallee()->getSourceRange(), CallType);
3256
3257 return false;
3258}
3259
Tim Northovere94a34c2014-03-11 10:49:14 +00003260static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00003261 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00003262 return false;
3263
JF Bastiendda2cb12016-04-18 18:01:49 +00003264 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00003265 switch (Op) {
3266 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00003267 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00003268 llvm_unreachable("There is no ordering argument for an init");
3269
3270 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00003271 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00003272 case AtomicExpr::AO__atomic_load_n:
3273 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00003274 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
3275 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00003276
3277 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00003278 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00003279 case AtomicExpr::AO__atomic_store:
3280 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00003281 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
3282 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
3283 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00003284
3285 default:
3286 return true;
3287 }
3288}
3289
Richard Smithfeea8832012-04-12 05:08:17 +00003290ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
3291 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003292 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3293 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003294
Yaxun Liu39195062017-08-04 18:16:31 +00003295 // All the non-OpenCL operations take one of the following forms.
3296 // The OpenCL operations take the __c11 forms with one extra argument for
3297 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00003298 enum {
3299 // C __c11_atomic_init(A *, C)
3300 Init,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003301
Richard Smithfeea8832012-04-12 05:08:17 +00003302 // C __c11_atomic_load(A *, int)
3303 Load,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003304
Richard Smithfeea8832012-04-12 05:08:17 +00003305 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00003306 LoadCopy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003307
Eric Fiselier8d662442016-03-30 23:39:56 +00003308 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00003309 Copy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003310
Richard Smithfeea8832012-04-12 05:08:17 +00003311 // C __c11_atomic_add(A *, M, int)
3312 Arithmetic,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003313
Richard Smithfeea8832012-04-12 05:08:17 +00003314 // C __atomic_exchange_n(A *, CP, int)
3315 Xchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003316
Richard Smithfeea8832012-04-12 05:08:17 +00003317 // void __atomic_exchange(A *, C *, CP, int)
3318 GNUXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003319
Richard Smithfeea8832012-04-12 05:08:17 +00003320 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
3321 C11CmpXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003322
Richard Smithfeea8832012-04-12 05:08:17 +00003323 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
3324 GNUCmpXchg
3325 } Form = Init;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003326
Yaxun Liu39195062017-08-04 18:16:31 +00003327 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00003328 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
3329 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00003330 // where:
3331 // C is an appropriate type,
3332 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
3333 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
3334 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
3335 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003336
Yaxun Liu39195062017-08-04 18:16:31 +00003337 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
3338 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
3339 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00003340 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
3341 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
3342 AtomicExpr::AO__atomic_load,
3343 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00003344 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
3345 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
3346 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
3347 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
3348 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00003349 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
3350 Op == AtomicExpr::AO__atomic_store_n ||
3351 Op == AtomicExpr::AO__atomic_exchange_n ||
3352 Op == AtomicExpr::AO__atomic_compare_exchange_n;
3353 bool IsAddSub = false;
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003354 bool IsMinMax = false;
Richard Smithfeea8832012-04-12 05:08:17 +00003355
3356 switch (Op) {
3357 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00003358 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00003359 Form = Init;
3360 break;
3361
3362 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00003363 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00003364 case AtomicExpr::AO__atomic_load_n:
3365 Form = Load;
3366 break;
3367
Richard Smithfeea8832012-04-12 05:08:17 +00003368 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00003369 Form = LoadCopy;
3370 break;
3371
3372 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00003373 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00003374 case AtomicExpr::AO__atomic_store:
3375 case AtomicExpr::AO__atomic_store_n:
3376 Form = Copy;
3377 break;
3378
3379 case AtomicExpr::AO__c11_atomic_fetch_add:
3380 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00003381 case AtomicExpr::AO__opencl_atomic_fetch_add:
3382 case AtomicExpr::AO__opencl_atomic_fetch_sub:
3383 case AtomicExpr::AO__opencl_atomic_fetch_min:
3384 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00003385 case AtomicExpr::AO__atomic_fetch_add:
3386 case AtomicExpr::AO__atomic_fetch_sub:
3387 case AtomicExpr::AO__atomic_add_fetch:
3388 case AtomicExpr::AO__atomic_sub_fetch:
3389 IsAddSub = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003390 LLVM_FALLTHROUGH;
Richard Smithfeea8832012-04-12 05:08:17 +00003391 case AtomicExpr::AO__c11_atomic_fetch_and:
3392 case AtomicExpr::AO__c11_atomic_fetch_or:
3393 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00003394 case AtomicExpr::AO__opencl_atomic_fetch_and:
3395 case AtomicExpr::AO__opencl_atomic_fetch_or:
3396 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00003397 case AtomicExpr::AO__atomic_fetch_and:
3398 case AtomicExpr::AO__atomic_fetch_or:
3399 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00003400 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00003401 case AtomicExpr::AO__atomic_and_fetch:
3402 case AtomicExpr::AO__atomic_or_fetch:
3403 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00003404 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00003405 Form = Arithmetic;
3406 break;
3407
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003408 case AtomicExpr::AO__atomic_fetch_min:
3409 case AtomicExpr::AO__atomic_fetch_max:
3410 IsMinMax = true;
3411 Form = Arithmetic;
3412 break;
3413
Richard Smithfeea8832012-04-12 05:08:17 +00003414 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00003415 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00003416 case AtomicExpr::AO__atomic_exchange_n:
3417 Form = Xchg;
3418 break;
3419
3420 case AtomicExpr::AO__atomic_exchange:
3421 Form = GNUXchg;
3422 break;
3423
3424 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3425 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00003426 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3427 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00003428 Form = C11CmpXchg;
3429 break;
3430
3431 case AtomicExpr::AO__atomic_compare_exchange:
3432 case AtomicExpr::AO__atomic_compare_exchange_n:
3433 Form = GNUCmpXchg;
3434 break;
3435 }
3436
Yaxun Liu39195062017-08-04 18:16:31 +00003437 unsigned AdjustedNumArgs = NumArgs[Form];
3438 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3439 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00003440 // Check we have the right number of arguments.
Yaxun Liu39195062017-08-04 18:16:31 +00003441 if (TheCall->getNumArgs() < AdjustedNumArgs) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003442 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003443 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003444 << TheCall->getCallee()->getSourceRange();
3445 return ExprError();
Yaxun Liu39195062017-08-04 18:16:31 +00003446 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3447 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003448 diag::err_typecheck_call_too_many_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003449 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003450 << TheCall->getCallee()->getSourceRange();
3451 return ExprError();
3452 }
3453
Richard Smithfeea8832012-04-12 05:08:17 +00003454 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003455 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00003456 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3457 if (ConvertedPtr.isInvalid())
3458 return ExprError();
3459
3460 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003461 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3462 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00003463 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003464 << Ptr->getType() << Ptr->getSourceRange();
3465 return ExprError();
3466 }
3467
Richard Smithfeea8832012-04-12 05:08:17 +00003468 // For a __c11 builtin, this should be a pointer to an _Atomic type.
3469 QualType AtomTy = pointerType->getPointeeType(); // 'A'
3470 QualType ValType = AtomTy; // 'C'
3471 if (IsC11) {
3472 if (!AtomTy->isAtomicType()) {
3473 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3474 << Ptr->getType() << Ptr->getSourceRange();
3475 return ExprError();
3476 }
Yaxun Liu39195062017-08-04 18:16:31 +00003477 if (AtomTy.isConstQualified() ||
3478 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Richard Smithe00921a2012-09-15 06:09:58 +00003479 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00003480 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3481 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00003482 return ExprError();
3483 }
Richard Smithfeea8832012-04-12 05:08:17 +00003484 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00003485 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00003486 if (ValType.isConstQualified()) {
3487 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3488 << Ptr->getType() << Ptr->getSourceRange();
3489 return ExprError();
3490 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003491 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003492
Richard Smithfeea8832012-04-12 05:08:17 +00003493 // For an arithmetic operation, the implied arithmetic must be well-formed.
3494 if (Form == Arithmetic) {
3495 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003496 if (IsAddSub && !ValType->isIntegerType()
3497 && !ValType->isPointerType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003498 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3499 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3500 return ExprError();
3501 }
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003502 if (IsMinMax) {
3503 const BuiltinType *BT = ValType->getAs<BuiltinType>();
3504 if (!BT || (BT->getKind() != BuiltinType::Int &&
3505 BT->getKind() != BuiltinType::UInt)) {
3506 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_int32_or_ptr);
3507 return ExprError();
3508 }
3509 }
3510 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003511 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3512 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3513 return ExprError();
3514 }
David Majnemere85cff82015-01-28 05:48:06 +00003515 if (IsC11 && ValType->isPointerType() &&
3516 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3517 diag::err_incomplete_type)) {
3518 return ExprError();
3519 }
Richard Smithfeea8832012-04-12 05:08:17 +00003520 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3521 // For __atomic_*_n operations, the value type must be a scalar integral or
3522 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003523 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00003524 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3525 return ExprError();
3526 }
3527
Eli Friedmanaa769812013-09-11 03:49:34 +00003528 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3529 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003530 // For GNU atomics, require a trivially-copyable type. This is not part of
3531 // the GNU atomics specification, but we enforce it for sanity.
3532 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003533 << Ptr->getType() << Ptr->getSourceRange();
3534 return ExprError();
3535 }
3536
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003537 switch (ValType.getObjCLifetime()) {
3538 case Qualifiers::OCL_None:
3539 case Qualifiers::OCL_ExplicitNone:
3540 // okay
3541 break;
3542
3543 case Qualifiers::OCL_Weak:
3544 case Qualifiers::OCL_Strong:
3545 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00003546 // FIXME: Can this happen? By this point, ValType should be known
3547 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003548 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3549 << ValType << Ptr->getSourceRange();
3550 return ExprError();
3551 }
3552
JF Bastien7f0a05a2018-05-25 00:07:09 +00003553 // All atomic operations have an overload which takes a pointer to a volatile
3554 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
3555 // into the result or the other operands. Similarly atomic_load takes a
3556 // pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00003557 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00003558 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003559 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00003560 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3561 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003562 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00003563 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003564 ResultType = Context.BoolTy;
3565
Richard Smithfeea8832012-04-12 05:08:17 +00003566 // The type of a parameter passed 'by value'. In the GNU atomics, such
3567 // arguments are actually passed as pointers.
3568 QualType ByValType = ValType; // 'CP'
JF Bastien7f0a05a2018-05-25 00:07:09 +00003569 bool IsPassedByAddress = false;
3570 if (!IsC11 && !IsN) {
Richard Smithfeea8832012-04-12 05:08:17 +00003571 ByValType = Ptr->getType();
JF Bastien7f0a05a2018-05-25 00:07:09 +00003572 IsPassedByAddress = true;
3573 }
Richard Smithfeea8832012-04-12 05:08:17 +00003574
JF Bastien7f0a05a2018-05-25 00:07:09 +00003575 // The first argument's non-CV pointer type is used to deduce the type of
3576 // subsequent arguments, except for:
3577 // - weak flag (always converted to bool)
3578 // - memory order (always converted to int)
3579 // - scope (always converted to int)
3580 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003581 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00003582 if (i < NumVals[Form] + 1) {
3583 switch (i) {
JF Bastien7f0a05a2018-05-25 00:07:09 +00003584 case 0:
3585 // The first argument is always a pointer. It has a fixed type.
3586 // It is always dereferenced, a nullptr is undefined.
3587 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
3588 // Nothing else to do: we already know all we want about this pointer.
3589 continue;
Richard Smithfeea8832012-04-12 05:08:17 +00003590 case 1:
3591 // The second argument is the non-atomic operand. For arithmetic, this
3592 // is always passed by value, and for a compare_exchange it is always
3593 // passed by address. For the rest, GNU uses by-address and C11 uses
3594 // by-value.
3595 assert(Form != Load);
3596 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3597 Ty = ValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00003598 else if (Form == Copy || Form == Xchg) {
3599 if (IsPassedByAddress)
3600 // The value pointer is always dereferenced, a nullptr is undefined.
3601 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
Richard Smithfeea8832012-04-12 05:08:17 +00003602 Ty = ByValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00003603 } else if (Form == Arithmetic)
Richard Smithfeea8832012-04-12 05:08:17 +00003604 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003605 else {
3606 Expr *ValArg = TheCall->getArg(i);
JF Bastien7f0a05a2018-05-25 00:07:09 +00003607 // The value pointer is always dereferenced, a nullptr is undefined.
Alex Lorenz67522152016-11-23 16:57:03 +00003608 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Alexander Richardson6d989432017-10-15 18:48:14 +00003609 LangAS AS = LangAS::Default;
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003610 // Keep address space of non-atomic pointer type.
3611 if (const PointerType *PtrTy =
3612 ValArg->getType()->getAs<PointerType>()) {
3613 AS = PtrTy->getPointeeType().getAddressSpace();
3614 }
3615 Ty = Context.getPointerType(
3616 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3617 }
Richard Smithfeea8832012-04-12 05:08:17 +00003618 break;
3619 case 2:
JF Bastien7f0a05a2018-05-25 00:07:09 +00003620 // The third argument to compare_exchange / GNU exchange is the desired
JF Bastien7853d5f2018-05-25 17:36:49 +00003621 // value, either by-value (for the C11 and *_n variant) or as a pointer.
3622 if (IsPassedByAddress)
JF Bastien7f0a05a2018-05-25 00:07:09 +00003623 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
Richard Smithfeea8832012-04-12 05:08:17 +00003624 Ty = ByValType;
3625 break;
3626 case 3:
3627 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3628 Ty = Context.BoolTy;
3629 break;
3630 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003631 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00003632 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003633 Ty = Context.IntTy;
3634 }
Richard Smithfeea8832012-04-12 05:08:17 +00003635
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003636 InitializedEntity Entity =
3637 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003638 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003639 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3640 if (Arg.isInvalid())
3641 return true;
3642 TheCall->setArg(i, Arg.get());
3643 }
3644
Richard Smithfeea8832012-04-12 05:08:17 +00003645 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003646 SmallVector<Expr*, 5> SubExprs;
3647 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003648 switch (Form) {
3649 case Init:
3650 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003651 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003652 break;
3653 case Load:
3654 SubExprs.push_back(TheCall->getArg(1)); // Order
3655 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003656 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003657 case Copy:
3658 case Arithmetic:
3659 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003660 SubExprs.push_back(TheCall->getArg(2)); // Order
3661 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003662 break;
3663 case GNUXchg:
3664 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3665 SubExprs.push_back(TheCall->getArg(3)); // Order
3666 SubExprs.push_back(TheCall->getArg(1)); // Val1
3667 SubExprs.push_back(TheCall->getArg(2)); // Val2
3668 break;
3669 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003670 SubExprs.push_back(TheCall->getArg(3)); // Order
3671 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003672 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003673 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003674 break;
3675 case GNUCmpXchg:
3676 SubExprs.push_back(TheCall->getArg(4)); // Order
3677 SubExprs.push_back(TheCall->getArg(1)); // Val1
3678 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3679 SubExprs.push_back(TheCall->getArg(2)); // Val2
3680 SubExprs.push_back(TheCall->getArg(3)); // Weak
3681 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003682 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003683
3684 if (SubExprs.size() >= 2 && Form != Init) {
3685 llvm::APSInt Result(32);
3686 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3687 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003688 Diag(SubExprs[1]->getLocStart(),
3689 diag::warn_atomic_op_has_invalid_memory_order)
3690 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003691 }
3692
Yaxun Liu30d652a2017-08-15 16:02:49 +00003693 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3694 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3695 llvm::APSInt Result(32);
3696 if (Scope->isIntegerConstantExpr(Result, Context) &&
3697 !ScopeModel->isValid(Result.getZExtValue())) {
3698 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3699 << Scope->getSourceRange();
3700 }
3701 SubExprs.push_back(Scope);
3702 }
3703
Fariborz Jahanian615de762013-05-28 17:37:39 +00003704 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3705 SubExprs, ResultType, Op,
3706 TheCall->getRParenLoc());
3707
3708 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00003709 Op == AtomicExpr::AO__c11_atomic_store ||
3710 Op == AtomicExpr::AO__opencl_atomic_load ||
3711 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00003712 Context.AtomicUsesUnsupportedLibcall(AE))
Yaxun Liu39195062017-08-04 18:16:31 +00003713 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3714 << ((Op == AtomicExpr::AO__c11_atomic_load ||
3715 Op == AtomicExpr::AO__opencl_atomic_load)
3716 ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003717
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003718 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003719}
3720
John McCall29ad95b2011-08-27 01:09:30 +00003721/// checkBuiltinArgument - Given a call to a builtin function, perform
3722/// normal type-checking on the given argument, updating the call in
3723/// place. This is useful when a builtin function requires custom
3724/// type-checking for some of its arguments but not necessarily all of
3725/// them.
3726///
3727/// Returns true on error.
3728static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3729 FunctionDecl *Fn = E->getDirectCallee();
3730 assert(Fn && "builtin call without direct callee!");
3731
3732 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3733 InitializedEntity Entity =
3734 InitializedEntity::InitializeParameter(S.Context, Param);
3735
3736 ExprResult Arg = E->getArg(0);
3737 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3738 if (Arg.isInvalid())
3739 return true;
3740
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003741 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003742 return false;
3743}
3744
Chris Lattnerdc046542009-05-08 06:58:22 +00003745/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3746/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3747/// type of its first argument. The main ActOnCallExpr routines have already
3748/// promoted the types of arguments because all of these calls are prototyped as
3749/// void(...).
3750///
3751/// This function goes through and does final semantic checking for these
3752/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003753ExprResult
3754Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003755 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003756 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3757 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3758
3759 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003760 if (TheCall->getNumArgs() < 1) {
3761 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3762 << 0 << 1 << TheCall->getNumArgs()
3763 << TheCall->getCallee()->getSourceRange();
3764 return ExprError();
3765 }
Mike Stump11289f42009-09-09 15:08:12 +00003766
Chris Lattnerdc046542009-05-08 06:58:22 +00003767 // Inspect the first argument of the atomic builtin. This should always be
3768 // a pointer type, whose element is an integral scalar or pointer type.
3769 // Because it is a pointer type, we don't have to worry about any implicit
3770 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003771 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003772 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003773 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3774 if (FirstArgResult.isInvalid())
3775 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003776 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003777 TheCall->setArg(0, FirstArg);
3778
John McCall31168b02011-06-15 23:02:42 +00003779 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3780 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003781 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3782 << FirstArg->getType() << FirstArg->getSourceRange();
3783 return ExprError();
3784 }
Mike Stump11289f42009-09-09 15:08:12 +00003785
John McCall31168b02011-06-15 23:02:42 +00003786 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003787 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003788 !ValType->isBlockPointerType()) {
3789 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3790 << FirstArg->getType() << FirstArg->getSourceRange();
3791 return ExprError();
3792 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003793
Aaron Ballmana383c942018-05-05 17:38:42 +00003794 if (ValType.isConstQualified()) {
3795 Diag(DRE->getLocStart(), diag::err_atomic_builtin_cannot_be_const)
3796 << FirstArg->getType() << FirstArg->getSourceRange();
3797 return ExprError();
3798 }
3799
John McCall31168b02011-06-15 23:02:42 +00003800 switch (ValType.getObjCLifetime()) {
3801 case Qualifiers::OCL_None:
3802 case Qualifiers::OCL_ExplicitNone:
3803 // okay
3804 break;
3805
3806 case Qualifiers::OCL_Weak:
3807 case Qualifiers::OCL_Strong:
3808 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003809 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003810 << ValType << FirstArg->getSourceRange();
3811 return ExprError();
3812 }
3813
John McCallb50451a2011-10-05 07:41:44 +00003814 // Strip any qualifiers off ValType.
3815 ValType = ValType.getUnqualifiedType();
3816
Chandler Carruth3973af72010-07-18 20:54:12 +00003817 // The majority of builtins return a value, but a few have special return
3818 // types, so allow them to override appropriately below.
3819 QualType ResultType = ValType;
3820
Chris Lattnerdc046542009-05-08 06:58:22 +00003821 // We need to figure out which concrete builtin this maps onto. For example,
3822 // __sync_fetch_and_add with a 2 byte object turns into
3823 // __sync_fetch_and_add_2.
3824#define BUILTIN_ROW(x) \
3825 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3826 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003827
Chris Lattnerdc046542009-05-08 06:58:22 +00003828 static const unsigned BuiltinIndices[][5] = {
3829 BUILTIN_ROW(__sync_fetch_and_add),
3830 BUILTIN_ROW(__sync_fetch_and_sub),
3831 BUILTIN_ROW(__sync_fetch_and_or),
3832 BUILTIN_ROW(__sync_fetch_and_and),
3833 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003834 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003835
Chris Lattnerdc046542009-05-08 06:58:22 +00003836 BUILTIN_ROW(__sync_add_and_fetch),
3837 BUILTIN_ROW(__sync_sub_and_fetch),
3838 BUILTIN_ROW(__sync_and_and_fetch),
3839 BUILTIN_ROW(__sync_or_and_fetch),
3840 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003841 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003842
Chris Lattnerdc046542009-05-08 06:58:22 +00003843 BUILTIN_ROW(__sync_val_compare_and_swap),
3844 BUILTIN_ROW(__sync_bool_compare_and_swap),
3845 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003846 BUILTIN_ROW(__sync_lock_release),
3847 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003848 };
Mike Stump11289f42009-09-09 15:08:12 +00003849#undef BUILTIN_ROW
3850
Chris Lattnerdc046542009-05-08 06:58:22 +00003851 // Determine the index of the size.
3852 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003853 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003854 case 1: SizeIndex = 0; break;
3855 case 2: SizeIndex = 1; break;
3856 case 4: SizeIndex = 2; break;
3857 case 8: SizeIndex = 3; break;
3858 case 16: SizeIndex = 4; break;
3859 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003860 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3861 << FirstArg->getType() << FirstArg->getSourceRange();
3862 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003863 }
Mike Stump11289f42009-09-09 15:08:12 +00003864
Chris Lattnerdc046542009-05-08 06:58:22 +00003865 // Each of these builtins has one pointer argument, followed by some number of
3866 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3867 // that we ignore. Find out which row of BuiltinIndices to read from as well
3868 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003869 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003870 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003871 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003872 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003873 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003874 case Builtin::BI__sync_fetch_and_add:
3875 case Builtin::BI__sync_fetch_and_add_1:
3876 case Builtin::BI__sync_fetch_and_add_2:
3877 case Builtin::BI__sync_fetch_and_add_4:
3878 case Builtin::BI__sync_fetch_and_add_8:
3879 case Builtin::BI__sync_fetch_and_add_16:
3880 BuiltinIndex = 0;
3881 break;
3882
3883 case Builtin::BI__sync_fetch_and_sub:
3884 case Builtin::BI__sync_fetch_and_sub_1:
3885 case Builtin::BI__sync_fetch_and_sub_2:
3886 case Builtin::BI__sync_fetch_and_sub_4:
3887 case Builtin::BI__sync_fetch_and_sub_8:
3888 case Builtin::BI__sync_fetch_and_sub_16:
3889 BuiltinIndex = 1;
3890 break;
3891
3892 case Builtin::BI__sync_fetch_and_or:
3893 case Builtin::BI__sync_fetch_and_or_1:
3894 case Builtin::BI__sync_fetch_and_or_2:
3895 case Builtin::BI__sync_fetch_and_or_4:
3896 case Builtin::BI__sync_fetch_and_or_8:
3897 case Builtin::BI__sync_fetch_and_or_16:
3898 BuiltinIndex = 2;
3899 break;
3900
3901 case Builtin::BI__sync_fetch_and_and:
3902 case Builtin::BI__sync_fetch_and_and_1:
3903 case Builtin::BI__sync_fetch_and_and_2:
3904 case Builtin::BI__sync_fetch_and_and_4:
3905 case Builtin::BI__sync_fetch_and_and_8:
3906 case Builtin::BI__sync_fetch_and_and_16:
3907 BuiltinIndex = 3;
3908 break;
Mike Stump11289f42009-09-09 15:08:12 +00003909
Douglas Gregor73722482011-11-28 16:30:08 +00003910 case Builtin::BI__sync_fetch_and_xor:
3911 case Builtin::BI__sync_fetch_and_xor_1:
3912 case Builtin::BI__sync_fetch_and_xor_2:
3913 case Builtin::BI__sync_fetch_and_xor_4:
3914 case Builtin::BI__sync_fetch_and_xor_8:
3915 case Builtin::BI__sync_fetch_and_xor_16:
3916 BuiltinIndex = 4;
3917 break;
3918
Hal Finkeld2208b52014-10-02 20:53:50 +00003919 case Builtin::BI__sync_fetch_and_nand:
3920 case Builtin::BI__sync_fetch_and_nand_1:
3921 case Builtin::BI__sync_fetch_and_nand_2:
3922 case Builtin::BI__sync_fetch_and_nand_4:
3923 case Builtin::BI__sync_fetch_and_nand_8:
3924 case Builtin::BI__sync_fetch_and_nand_16:
3925 BuiltinIndex = 5;
3926 WarnAboutSemanticsChange = true;
3927 break;
3928
Douglas Gregor73722482011-11-28 16:30:08 +00003929 case Builtin::BI__sync_add_and_fetch:
3930 case Builtin::BI__sync_add_and_fetch_1:
3931 case Builtin::BI__sync_add_and_fetch_2:
3932 case Builtin::BI__sync_add_and_fetch_4:
3933 case Builtin::BI__sync_add_and_fetch_8:
3934 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003935 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003936 break;
3937
3938 case Builtin::BI__sync_sub_and_fetch:
3939 case Builtin::BI__sync_sub_and_fetch_1:
3940 case Builtin::BI__sync_sub_and_fetch_2:
3941 case Builtin::BI__sync_sub_and_fetch_4:
3942 case Builtin::BI__sync_sub_and_fetch_8:
3943 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003944 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003945 break;
3946
3947 case Builtin::BI__sync_and_and_fetch:
3948 case Builtin::BI__sync_and_and_fetch_1:
3949 case Builtin::BI__sync_and_and_fetch_2:
3950 case Builtin::BI__sync_and_and_fetch_4:
3951 case Builtin::BI__sync_and_and_fetch_8:
3952 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003953 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003954 break;
3955
3956 case Builtin::BI__sync_or_and_fetch:
3957 case Builtin::BI__sync_or_and_fetch_1:
3958 case Builtin::BI__sync_or_and_fetch_2:
3959 case Builtin::BI__sync_or_and_fetch_4:
3960 case Builtin::BI__sync_or_and_fetch_8:
3961 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003962 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003963 break;
3964
3965 case Builtin::BI__sync_xor_and_fetch:
3966 case Builtin::BI__sync_xor_and_fetch_1:
3967 case Builtin::BI__sync_xor_and_fetch_2:
3968 case Builtin::BI__sync_xor_and_fetch_4:
3969 case Builtin::BI__sync_xor_and_fetch_8:
3970 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003971 BuiltinIndex = 10;
3972 break;
3973
3974 case Builtin::BI__sync_nand_and_fetch:
3975 case Builtin::BI__sync_nand_and_fetch_1:
3976 case Builtin::BI__sync_nand_and_fetch_2:
3977 case Builtin::BI__sync_nand_and_fetch_4:
3978 case Builtin::BI__sync_nand_and_fetch_8:
3979 case Builtin::BI__sync_nand_and_fetch_16:
3980 BuiltinIndex = 11;
3981 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003982 break;
Mike Stump11289f42009-09-09 15:08:12 +00003983
Chris Lattnerdc046542009-05-08 06:58:22 +00003984 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003985 case Builtin::BI__sync_val_compare_and_swap_1:
3986 case Builtin::BI__sync_val_compare_and_swap_2:
3987 case Builtin::BI__sync_val_compare_and_swap_4:
3988 case Builtin::BI__sync_val_compare_and_swap_8:
3989 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003990 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003991 NumFixed = 2;
3992 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003993
Chris Lattnerdc046542009-05-08 06:58:22 +00003994 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003995 case Builtin::BI__sync_bool_compare_and_swap_1:
3996 case Builtin::BI__sync_bool_compare_and_swap_2:
3997 case Builtin::BI__sync_bool_compare_and_swap_4:
3998 case Builtin::BI__sync_bool_compare_and_swap_8:
3999 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004000 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00004001 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00004002 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00004003 break;
Douglas Gregor73722482011-11-28 16:30:08 +00004004
JF Bastien7f0a05a2018-05-25 00:07:09 +00004005 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +00004006 case Builtin::BI__sync_lock_test_and_set_1:
4007 case Builtin::BI__sync_lock_test_and_set_2:
4008 case Builtin::BI__sync_lock_test_and_set_4:
4009 case Builtin::BI__sync_lock_test_and_set_8:
4010 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004011 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00004012 break;
4013
Chris Lattnerdc046542009-05-08 06:58:22 +00004014 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00004015 case Builtin::BI__sync_lock_release_1:
4016 case Builtin::BI__sync_lock_release_2:
4017 case Builtin::BI__sync_lock_release_4:
4018 case Builtin::BI__sync_lock_release_8:
4019 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004020 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00004021 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00004022 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00004023 break;
Douglas Gregor73722482011-11-28 16:30:08 +00004024
4025 case Builtin::BI__sync_swap:
4026 case Builtin::BI__sync_swap_1:
4027 case Builtin::BI__sync_swap_2:
4028 case Builtin::BI__sync_swap_4:
4029 case Builtin::BI__sync_swap_8:
4030 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004031 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00004032 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00004033 }
Mike Stump11289f42009-09-09 15:08:12 +00004034
Chris Lattnerdc046542009-05-08 06:58:22 +00004035 // Now that we know how many fixed arguments we expect, first check that we
4036 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004037 if (TheCall->getNumArgs() < 1+NumFixed) {
4038 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
4039 << 0 << 1+NumFixed << TheCall->getNumArgs()
4040 << TheCall->getCallee()->getSourceRange();
4041 return ExprError();
4042 }
Mike Stump11289f42009-09-09 15:08:12 +00004043
Hal Finkeld2208b52014-10-02 20:53:50 +00004044 if (WarnAboutSemanticsChange) {
4045 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
4046 << TheCall->getCallee()->getSourceRange();
4047 }
4048
Chris Lattner5b9241b2009-05-08 15:36:58 +00004049 // Get the decl for the concrete builtin from this, we can tell what the
4050 // concrete integer type we should convert to is.
4051 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00004052 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00004053 FunctionDecl *NewBuiltinDecl;
4054 if (NewBuiltinID == BuiltinID)
4055 NewBuiltinDecl = FDecl;
4056 else {
4057 // Perform builtin lookup to avoid redeclaring it.
4058 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
4059 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
4060 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
4061 assert(Res.getFoundDecl());
4062 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004063 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00004064 return ExprError();
4065 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004066
John McCallcf142162010-08-07 06:22:56 +00004067 // The first argument --- the pointer --- has a fixed type; we
4068 // deduce the types of the rest of the arguments accordingly. Walk
4069 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00004070 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00004071 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00004072
Chris Lattnerdc046542009-05-08 06:58:22 +00004073 // GCC does an implicit conversion to the pointer or integer ValType. This
4074 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00004075 // Initialize the argument.
4076 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4077 ValType, /*consume*/ false);
4078 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00004079 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004080 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004081
Chris Lattnerdc046542009-05-08 06:58:22 +00004082 // Okay, we have something that *can* be converted to the right type. Check
4083 // to see if there is a potentially weird extension going on here. This can
4084 // happen when you do an atomic operation on something like an char* and
4085 // pass in 42. The 42 gets converted to char. This is even more strange
4086 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00004087 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004088 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00004089 }
Mike Stump11289f42009-09-09 15:08:12 +00004090
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004091 ASTContext& Context = this->getASTContext();
4092
4093 // Create a new DeclRefExpr to refer to the new decl.
4094 DeclRefExpr* NewDRE = DeclRefExpr::Create(
4095 Context,
4096 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00004097 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004098 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00004099 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004100 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00004101 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004102 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00004103
Chris Lattnerdc046542009-05-08 06:58:22 +00004104 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00004105 // FIXME: This loses syntactic information.
4106 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
4107 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
4108 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004109 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00004110
Chandler Carruthbc8cab12010-07-18 07:23:17 +00004111 // Change the result type of the call to match the original value type. This
4112 // is arbitrary, but the codegen for these builtins ins design to handle it
4113 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00004114 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004115
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004116 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00004117}
4118
Michael Zolotukhin84df1232015-09-08 23:52:33 +00004119/// SemaBuiltinNontemporalOverloaded - We have a call to
4120/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
4121/// overloaded function based on the pointer type of its last argument.
4122///
4123/// This function goes through and does final semantic checking for these
4124/// builtins.
4125ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
4126 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
4127 DeclRefExpr *DRE =
4128 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4129 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4130 unsigned BuiltinID = FDecl->getBuiltinID();
4131 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
4132 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
4133 "Unexpected nontemporal load/store builtin!");
4134 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
4135 unsigned numArgs = isStore ? 2 : 1;
4136
4137 // Ensure that we have the proper number of arguments.
4138 if (checkArgCount(*this, TheCall, numArgs))
4139 return ExprError();
4140
4141 // Inspect the last argument of the nontemporal builtin. This should always
4142 // be a pointer type, from which we imply the type of the memory access.
4143 // Because it is a pointer type, we don't have to worry about any implicit
4144 // casts here.
4145 Expr *PointerArg = TheCall->getArg(numArgs - 1);
4146 ExprResult PointerArgResult =
4147 DefaultFunctionArrayLvalueConversion(PointerArg);
4148
4149 if (PointerArgResult.isInvalid())
4150 return ExprError();
4151 PointerArg = PointerArgResult.get();
4152 TheCall->setArg(numArgs - 1, PointerArg);
4153
4154 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
4155 if (!pointerType) {
4156 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
4157 << PointerArg->getType() << PointerArg->getSourceRange();
4158 return ExprError();
4159 }
4160
4161 QualType ValType = pointerType->getPointeeType();
4162
4163 // Strip any qualifiers off ValType.
4164 ValType = ValType.getUnqualifiedType();
4165 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4166 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
4167 !ValType->isVectorType()) {
4168 Diag(DRE->getLocStart(),
4169 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
4170 << PointerArg->getType() << PointerArg->getSourceRange();
4171 return ExprError();
4172 }
4173
4174 if (!isStore) {
4175 TheCall->setType(ValType);
4176 return TheCallResult;
4177 }
4178
4179 ExprResult ValArg = TheCall->getArg(0);
4180 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4181 Context, ValType, /*consume*/ false);
4182 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
4183 if (ValArg.isInvalid())
4184 return ExprError();
4185
4186 TheCall->setArg(0, ValArg.get());
4187 TheCall->setType(Context.VoidTy);
4188 return TheCallResult;
4189}
4190
Chris Lattner6436fb62009-02-18 06:01:06 +00004191/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00004192/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00004193/// Note: It might also make sense to do the UTF-16 conversion here (would
4194/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00004195bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00004196 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00004197 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
4198
Douglas Gregorfb65e592011-07-27 05:40:30 +00004199 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00004200 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
4201 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00004202 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00004203 }
Mike Stump11289f42009-09-09 15:08:12 +00004204
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004205 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004206 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004207 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00004208 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
4209 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4210 llvm::UTF16 *ToPtr = &ToBuf[0];
4211
4212 llvm::ConversionResult Result =
4213 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4214 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004215 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00004216 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004217 Diag(Arg->getLocStart(),
4218 diag::warn_cfstring_truncated) << Arg->getSourceRange();
4219 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00004220 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004221}
4222
Mehdi Amini06d367c2016-10-24 20:39:34 +00004223/// CheckObjCString - Checks that the format string argument to the os_log()
4224/// and os_trace() functions is correct, and converts it to const char *.
4225ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
4226 Arg = Arg->IgnoreParenCasts();
4227 auto *Literal = dyn_cast<StringLiteral>(Arg);
4228 if (!Literal) {
4229 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
4230 Literal = ObjcLiteral->getString();
4231 }
4232 }
4233
4234 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
4235 return ExprError(
4236 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
4237 << Arg->getSourceRange());
4238 }
4239
4240 ExprResult Result(Literal);
4241 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
4242 InitializedEntity Entity =
4243 InitializedEntity::InitializeParameter(Context, ResultTy, false);
4244 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
4245 return Result;
4246}
4247
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004248/// Check that the user is calling the appropriate va_start builtin for the
4249/// target and calling convention.
4250static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
4251 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
4252 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00004253 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004254 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00004255 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
4256 if (IsX64 || IsAArch64) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004257 CallingConv CC = CC_C;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004258 if (const FunctionDecl *FD = S.getCurFunctionDecl())
4259 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
4260 if (IsMSVAStart) {
4261 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00004262 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004263 return S.Diag(Fn->getLocStart(),
4264 diag::err_ms_va_start_used_in_sysv_function);
4265 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00004266 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004267 // On x64 Windows, don't allow this in System V ABI functions.
4268 // (Yes, that means there's no corresponding way to support variadic
4269 // System V ABI functions on Windows.)
4270 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00004271 (!IsWindows && CC == CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004272 return S.Diag(Fn->getLocStart(),
4273 diag::err_va_start_used_in_wrong_abi_function)
4274 << !IsWindows;
4275 }
4276 return false;
4277 }
4278
4279 if (IsMSVAStart)
Martin Storsjo022e7822017-07-17 20:49:45 +00004280 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004281 return false;
4282}
4283
4284static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
4285 ParmVarDecl **LastParam = nullptr) {
4286 // Determine whether the current function, block, or obj-c method is variadic
4287 // and get its parameter list.
4288 bool IsVariadic = false;
4289 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00004290 DeclContext *Caller = S.CurContext;
4291 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
4292 IsVariadic = Block->isVariadic();
4293 Params = Block->parameters();
4294 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004295 IsVariadic = FD->isVariadic();
4296 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00004297 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004298 IsVariadic = MD->isVariadic();
4299 // FIXME: This isn't correct for methods (results in bogus warning).
4300 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00004301 } else if (isa<CapturedDecl>(Caller)) {
4302 // We don't support va_start in a CapturedDecl.
4303 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
4304 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004305 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00004306 // This must be some other declcontext that parses exprs.
4307 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
4308 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004309 }
4310
4311 if (!IsVariadic) {
Reid Klecknerf1deb832017-05-04 19:51:05 +00004312 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004313 return true;
4314 }
4315
4316 if (LastParam)
4317 *LastParam = Params.empty() ? nullptr : Params.back();
4318
4319 return false;
4320}
4321
Charles Davisc7d5c942015-09-17 20:55:33 +00004322/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
4323/// for validity. Emit an error and return true on failure; return false
4324/// on success.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004325bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00004326 Expr *Fn = TheCall->getCallee();
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004327
4328 if (checkVAStartABI(*this, BuiltinID, Fn))
4329 return true;
4330
Chris Lattner08464942007-12-28 05:29:59 +00004331 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00004332 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004333 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004334 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4335 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00004336 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004337 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00004338 return true;
4339 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00004340
4341 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00004342 return Diag(TheCall->getLocEnd(),
4343 diag::err_typecheck_call_too_few_args_at_least)
4344 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00004345 }
4346
John McCall29ad95b2011-08-27 01:09:30 +00004347 // Type-check the first argument normally.
4348 if (checkBuiltinArgument(*this, TheCall, 0))
4349 return true;
4350
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004351 // Check that the current function is variadic, and get its last parameter.
4352 ParmVarDecl *LastParam;
4353 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
Chris Lattner43be2e62007-12-19 23:59:04 +00004354 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004355
Chris Lattner43be2e62007-12-19 23:59:04 +00004356 // Verify that the second argument to the builtin is the last argument of the
4357 // current function or method.
4358 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00004359 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004360
Nico Weber9eea7642013-05-24 23:31:57 +00004361 // These are valid if SecondArgIsLastNamedArgument is false after the next
4362 // block.
4363 QualType Type;
4364 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00004365 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00004366
Anders Carlsson6a8350b2008-02-11 04:20:54 +00004367 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
4368 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004369 SecondArgIsLastNamedArgument = PV == LastParam;
Nico Weber9eea7642013-05-24 23:31:57 +00004370
4371 Type = PV->getType();
4372 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00004373 IsCRegister =
4374 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00004375 }
4376 }
Mike Stump11289f42009-09-09 15:08:12 +00004377
Chris Lattner43be2e62007-12-19 23:59:04 +00004378 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00004379 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00004380 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00004381 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00004382 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
4383 // Promotable integers are UB, but enumerations need a bit of
4384 // extra checking to see what their promotable type actually is.
4385 if (!Type->isPromotableIntegerType())
4386 return false;
4387 if (!Type->isEnumeralType())
4388 return true;
4389 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
4390 return !(ED &&
4391 Context.typesAreCompatible(ED->getPromotionType(), Type));
4392 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00004393 unsigned Reason = 0;
4394 if (Type->isReferenceType()) Reason = 1;
4395 else if (IsCRegister) Reason = 2;
4396 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00004397 Diag(ParamLoc, diag::note_parameter_type) << Type;
4398 }
4399
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00004400 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00004401 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00004402}
Chris Lattner43be2e62007-12-19 23:59:04 +00004403
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +00004404bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004405 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
4406 // const char *named_addr);
4407
4408 Expr *Func = Call->getCallee();
4409
4410 if (Call->getNumArgs() < 3)
4411 return Diag(Call->getLocEnd(),
4412 diag::err_typecheck_call_too_few_args_at_least)
4413 << 0 /*function call*/ << 3 << Call->getNumArgs();
4414
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004415 // Type-check the first argument normally.
4416 if (checkBuiltinArgument(*this, Call, 0))
4417 return true;
4418
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004419 // Check that the current function is variadic.
4420 if (checkVAStartIsInVariadicFunction(*this, Func))
4421 return true;
4422
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004423 // __va_start on Windows does not validate the parameter qualifiers
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004424
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004425 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4426 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4427
4428 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4429 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4430
4431 const QualType &ConstCharPtrTy =
4432 Context.getPointerType(Context.CharTy.withConst());
4433 if (!Arg1Ty->isPointerType() ||
4434 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4435 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4436 << Arg1->getType() << ConstCharPtrTy
4437 << 1 /* different class */
4438 << 0 /* qualifier difference */
4439 << 3 /* parameter mismatch */
4440 << 2 << Arg1->getType() << ConstCharPtrTy;
4441
4442 const QualType SizeTy = Context.getSizeType();
4443 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4444 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4445 << Arg2->getType() << SizeTy
4446 << 1 /* different class */
4447 << 0 /* qualifier difference */
4448 << 3 /* parameter mismatch */
4449 << 3 << Arg2->getType() << SizeTy;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004450
4451 return false;
4452}
4453
Chris Lattner2da14fb2007-12-20 00:26:33 +00004454/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4455/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00004456bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4457 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00004458 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004459 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00004460 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00004461 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004462 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004463 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00004464 << SourceRange(TheCall->getArg(2)->getLocStart(),
4465 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004466
John Wiegley01296292011-04-08 18:41:53 +00004467 ExprResult OrigArg0 = TheCall->getArg(0);
4468 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004469
Chris Lattner2da14fb2007-12-20 00:26:33 +00004470 // Do standard promotions between the two arguments, returning their common
4471 // type.
Chris Lattner08464942007-12-28 05:29:59 +00004472 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00004473 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4474 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00004475
4476 // Make sure any conversions are pushed back into the call; this is
4477 // type safe since unordered compare builtins are declared as "_Bool
4478 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00004479 TheCall->setArg(0, OrigArg0.get());
4480 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00004481
John Wiegley01296292011-04-08 18:41:53 +00004482 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00004483 return false;
4484
Chris Lattner2da14fb2007-12-20 00:26:33 +00004485 // If the common type isn't a real floating type, then the arguments were
4486 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00004487 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00004488 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004489 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00004490 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4491 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004492
Chris Lattner2da14fb2007-12-20 00:26:33 +00004493 return false;
4494}
4495
Benjamin Kramer634fc102010-02-15 22:42:31 +00004496/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4497/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00004498/// to check everything. We expect the last argument to be a floating point
4499/// value.
4500bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4501 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00004502 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004503 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00004504 if (TheCall->getNumArgs() > NumArgs)
4505 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004506 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004507 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00004508 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004509 (*(TheCall->arg_end()-1))->getLocEnd());
4510
Benjamin Kramer64aae502010-02-16 10:07:31 +00004511 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00004512
Eli Friedman7e4faac2009-08-31 20:06:00 +00004513 if (OrigArg->isTypeDependent())
4514 return false;
4515
Chris Lattner68784ef2010-05-06 05:50:07 +00004516 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00004517 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00004518 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004519 diag::err_typecheck_call_invalid_unary_fp)
4520 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004521
Neil Hickey88c0fac2016-12-13 16:22:50 +00004522 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00004523 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00004524 // Only remove standard FloatCasts, leaving other casts inplace
4525 if (Cast->getCastKind() == CK_FloatingCast) {
4526 Expr *CastArg = Cast->getSubExpr();
4527 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4528 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4529 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4530 "promotion from float to either float or double is the only expected cast here");
4531 Cast->setSubExpr(nullptr);
4532 TheCall->setArg(NumArgs-1, CastArg);
4533 }
Chris Lattner68784ef2010-05-06 05:50:07 +00004534 }
4535 }
4536
Eli Friedman7e4faac2009-08-31 20:06:00 +00004537 return false;
4538}
4539
Tony Jiangbbc48e92017-05-24 15:13:32 +00004540// Customized Sema Checking for VSX builtins that have the following signature:
4541// vector [...] builtinName(vector [...], vector [...], const int);
4542// Which takes the same type of vectors (any legal vector type) for the first
4543// two arguments and takes compile time constant for the third argument.
4544// Example builtins are :
4545// vector double vec_xxpermdi(vector double, vector double, int);
4546// vector short vec_xxsldwi(vector short, vector short, int);
4547bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4548 unsigned ExpectedNumArgs = 3;
4549 if (TheCall->getNumArgs() < ExpectedNumArgs)
4550 return Diag(TheCall->getLocEnd(),
4551 diag::err_typecheck_call_too_few_args_at_least)
4552 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4553 << TheCall->getSourceRange();
4554
4555 if (TheCall->getNumArgs() > ExpectedNumArgs)
4556 return Diag(TheCall->getLocEnd(),
4557 diag::err_typecheck_call_too_many_args_at_most)
4558 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4559 << TheCall->getSourceRange();
4560
4561 // Check the third argument is a compile time constant
4562 llvm::APSInt Value;
4563 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4564 return Diag(TheCall->getLocStart(),
4565 diag::err_vsx_builtin_nonconstant_argument)
4566 << 3 /* argument index */ << TheCall->getDirectCallee()
4567 << SourceRange(TheCall->getArg(2)->getLocStart(),
4568 TheCall->getArg(2)->getLocEnd());
4569
4570 QualType Arg1Ty = TheCall->getArg(0)->getType();
4571 QualType Arg2Ty = TheCall->getArg(1)->getType();
4572
4573 // Check the type of argument 1 and argument 2 are vectors.
4574 SourceLocation BuiltinLoc = TheCall->getLocStart();
4575 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4576 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4577 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4578 << TheCall->getDirectCallee()
4579 << SourceRange(TheCall->getArg(0)->getLocStart(),
4580 TheCall->getArg(1)->getLocEnd());
4581 }
4582
4583 // Check the first two arguments are the same type.
4584 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4585 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4586 << TheCall->getDirectCallee()
4587 << SourceRange(TheCall->getArg(0)->getLocStart(),
4588 TheCall->getArg(1)->getLocEnd());
4589 }
4590
4591 // When default clang type checking is turned off and the customized type
4592 // checking is used, the returning type of the function must be explicitly
4593 // set. Otherwise it is _Bool by default.
4594 TheCall->setType(Arg1Ty);
4595
4596 return false;
4597}
4598
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004599/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4600// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00004601ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00004602 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004603 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00004604 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00004605 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4606 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004607
Nate Begemana0110022010-06-08 00:16:34 +00004608 // Determine which of the following types of shufflevector we're checking:
4609 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00004610 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00004611 QualType resType = TheCall->getArg(0)->getType();
4612 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00004613
Douglas Gregorc25f7662009-05-19 22:10:17 +00004614 if (!TheCall->getArg(0)->isTypeDependent() &&
4615 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00004616 QualType LHSType = TheCall->getArg(0)->getType();
4617 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00004618
Craig Topperbaca3892013-07-29 06:47:04 +00004619 if (!LHSType->isVectorType() || !RHSType->isVectorType())
4620 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004621 diag::err_vec_builtin_non_vector)
4622 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004623 << SourceRange(TheCall->getArg(0)->getLocStart(),
4624 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004625
Nate Begemana0110022010-06-08 00:16:34 +00004626 numElements = LHSType->getAs<VectorType>()->getNumElements();
4627 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00004628
Nate Begemana0110022010-06-08 00:16:34 +00004629 // Check to see if we have a call with 2 vector arguments, the unary shuffle
4630 // with mask. If so, verify that RHS is an integer vector type with the
4631 // same number of elts as lhs.
4632 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00004633 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00004634 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00004635 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004636 diag::err_vec_builtin_incompatible_vector)
4637 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004638 << SourceRange(TheCall->getArg(1)->getLocStart(),
4639 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004640 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00004641 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004642 diag::err_vec_builtin_incompatible_vector)
4643 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004644 << SourceRange(TheCall->getArg(0)->getLocStart(),
4645 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00004646 } else if (numElements != numResElements) {
4647 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00004648 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00004649 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004650 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004651 }
4652
4653 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00004654 if (TheCall->getArg(i)->isTypeDependent() ||
4655 TheCall->getArg(i)->isValueDependent())
4656 continue;
4657
Nate Begemana0110022010-06-08 00:16:34 +00004658 llvm::APSInt Result(32);
4659 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4660 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004661 diag::err_shufflevector_nonconstant_argument)
4662 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004663
Craig Topper50ad5b72013-08-03 17:40:38 +00004664 // Allow -1 which will be translated to undef in the IR.
4665 if (Result.isSigned() && Result.isAllOnesValue())
4666 continue;
4667
Chris Lattner7ab824e2008-08-10 02:05:13 +00004668 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004669 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004670 diag::err_shufflevector_argument_too_large)
4671 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004672 }
4673
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004674 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004675
Chris Lattner7ab824e2008-08-10 02:05:13 +00004676 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004677 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00004678 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004679 }
4680
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004681 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4682 TheCall->getCallee()->getLocStart(),
4683 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004684}
Chris Lattner43be2e62007-12-19 23:59:04 +00004685
Hal Finkelc4d7c822013-09-18 03:29:45 +00004686/// SemaConvertVectorExpr - Handle __builtin_convertvector
4687ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4688 SourceLocation BuiltinLoc,
4689 SourceLocation RParenLoc) {
4690 ExprValueKind VK = VK_RValue;
4691 ExprObjectKind OK = OK_Ordinary;
4692 QualType DstTy = TInfo->getType();
4693 QualType SrcTy = E->getType();
4694
4695 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4696 return ExprError(Diag(BuiltinLoc,
4697 diag::err_convertvector_non_vector)
4698 << E->getSourceRange());
4699 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4700 return ExprError(Diag(BuiltinLoc,
4701 diag::err_convertvector_non_vector_type));
4702
4703 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4704 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4705 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4706 if (SrcElts != DstElts)
4707 return ExprError(Diag(BuiltinLoc,
4708 diag::err_convertvector_incompatible_vector)
4709 << E->getSourceRange());
4710 }
4711
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004712 return new (Context)
4713 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00004714}
4715
Daniel Dunbarb7257262008-07-21 22:59:13 +00004716/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4717// This is declared to take (const void*, ...) and can take two
4718// optional constant int args.
4719bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00004720 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004721
Chris Lattner3b054132008-11-19 05:08:23 +00004722 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004723 return Diag(TheCall->getLocEnd(),
4724 diag::err_typecheck_call_too_many_args_at_most)
4725 << 0 /*function call*/ << 3 << NumArgs
4726 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004727
4728 // Argument 0 is checked for us and the remaining arguments must be
4729 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00004730 for (unsigned i = 1; i != NumArgs; ++i)
4731 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004732 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004733
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004734 return false;
4735}
4736
Hal Finkelf0417332014-07-17 14:25:55 +00004737/// SemaBuiltinAssume - Handle __assume (MS Extension).
4738// __assume does not evaluate its arguments, and should warn if its argument
4739// has side effects.
4740bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4741 Expr *Arg = TheCall->getArg(0);
4742 if (Arg->isInstantiationDependent()) return false;
4743
4744 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004745 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004746 << Arg->getSourceRange()
4747 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4748
4749 return false;
4750}
4751
David Majnemer86b1bfa2016-10-31 18:07:57 +00004752/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004753/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4754/// than 8.
4755bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4756 // The alignment must be a constant integer.
4757 Expr *Arg = TheCall->getArg(1);
4758
4759 // We can't check the value of a dependent argument.
4760 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004761 if (const auto *UE =
4762 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4763 if (UE->getKind() == UETT_AlignOf)
4764 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4765 << Arg->getSourceRange();
4766
David Majnemer51169932016-10-31 05:37:48 +00004767 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4768
4769 if (!Result.isPowerOf2())
4770 return Diag(TheCall->getLocStart(),
4771 diag::err_alignment_not_power_of_two)
4772 << Arg->getSourceRange();
4773
4774 if (Result < Context.getCharWidth())
4775 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4776 << (unsigned)Context.getCharWidth()
4777 << Arg->getSourceRange();
4778
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004779 if (Result > std::numeric_limits<int32_t>::max())
David Majnemer51169932016-10-31 05:37:48 +00004780 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004781 << std::numeric_limits<int32_t>::max()
David Majnemer51169932016-10-31 05:37:48 +00004782 << Arg->getSourceRange();
4783 }
4784
4785 return false;
4786}
4787
4788/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004789/// as (const void*, size_t, ...) and can take one optional constant int arg.
4790bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4791 unsigned NumArgs = TheCall->getNumArgs();
4792
4793 if (NumArgs > 3)
4794 return Diag(TheCall->getLocEnd(),
4795 diag::err_typecheck_call_too_many_args_at_most)
4796 << 0 /*function call*/ << 3 << NumArgs
4797 << TheCall->getSourceRange();
4798
4799 // The alignment must be a constant integer.
4800 Expr *Arg = TheCall->getArg(1);
4801
4802 // We can't check the value of a dependent argument.
4803 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4804 llvm::APSInt Result;
4805 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4806 return true;
4807
4808 if (!Result.isPowerOf2())
4809 return Diag(TheCall->getLocStart(),
4810 diag::err_alignment_not_power_of_two)
4811 << Arg->getSourceRange();
4812 }
4813
4814 if (NumArgs > 2) {
4815 ExprResult Arg(TheCall->getArg(2));
4816 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4817 Context.getSizeType(), false);
4818 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4819 if (Arg.isInvalid()) return true;
4820 TheCall->setArg(2, Arg.get());
4821 }
Hal Finkelf0417332014-07-17 14:25:55 +00004822
4823 return false;
4824}
4825
Mehdi Amini06d367c2016-10-24 20:39:34 +00004826bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4827 unsigned BuiltinID =
4828 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4829 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4830
4831 unsigned NumArgs = TheCall->getNumArgs();
4832 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4833 if (NumArgs < NumRequiredArgs) {
4834 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4835 << 0 /* function call */ << NumRequiredArgs << NumArgs
4836 << TheCall->getSourceRange();
4837 }
4838 if (NumArgs >= NumRequiredArgs + 0x100) {
4839 return Diag(TheCall->getLocEnd(),
4840 diag::err_typecheck_call_too_many_args_at_most)
4841 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4842 << TheCall->getSourceRange();
4843 }
4844 unsigned i = 0;
4845
4846 // For formatting call, check buffer arg.
4847 if (!IsSizeCall) {
4848 ExprResult Arg(TheCall->getArg(i));
4849 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4850 Context, Context.VoidPtrTy, false);
4851 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4852 if (Arg.isInvalid())
4853 return true;
4854 TheCall->setArg(i, Arg.get());
4855 i++;
4856 }
4857
4858 // Check string literal arg.
4859 unsigned FormatIdx = i;
4860 {
4861 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4862 if (Arg.isInvalid())
4863 return true;
4864 TheCall->setArg(i, Arg.get());
4865 i++;
4866 }
4867
4868 // Make sure variadic args are scalar.
4869 unsigned FirstDataArg = i;
4870 while (i < NumArgs) {
4871 ExprResult Arg = DefaultVariadicArgumentPromotion(
4872 TheCall->getArg(i), VariadicFunction, nullptr);
4873 if (Arg.isInvalid())
4874 return true;
4875 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4876 if (ArgSize.getQuantity() >= 0x100) {
4877 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4878 << i << (int)ArgSize.getQuantity() << 0xff
4879 << TheCall->getSourceRange();
4880 }
4881 TheCall->setArg(i, Arg.get());
4882 i++;
4883 }
4884
4885 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4886 // call to avoid duplicate diagnostics.
4887 if (!IsSizeCall) {
4888 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4889 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4890 bool Success = CheckFormatArguments(
4891 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4892 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4893 CheckedVarArgs);
4894 if (!Success)
4895 return true;
4896 }
4897
4898 if (IsSizeCall) {
4899 TheCall->setType(Context.getSizeType());
4900 } else {
4901 TheCall->setType(Context.VoidPtrTy);
4902 }
4903 return false;
4904}
4905
Eric Christopher8d0c6212010-04-17 02:26:23 +00004906/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4907/// TheCall is a constant expression.
4908bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4909 llvm::APSInt &Result) {
4910 Expr *Arg = TheCall->getArg(ArgNum);
4911 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4912 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4913
4914 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4915
4916 if (!Arg->isIntegerConstantExpr(Result, Context))
4917 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004918 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004919
Chris Lattnerd545ad12009-09-23 06:06:36 +00004920 return false;
4921}
4922
Richard Sandiford28940af2014-04-16 08:47:51 +00004923/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4924/// TheCall is a constant expression in the range [Low, High].
4925bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4926 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004927 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004928
4929 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004930 Expr *Arg = TheCall->getArg(ArgNum);
4931 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004932 return false;
4933
Eric Christopher8d0c6212010-04-17 02:26:23 +00004934 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004935 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004936 return true;
4937
Richard Sandiford28940af2014-04-16 08:47:51 +00004938 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004939 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004940 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004941
4942 return false;
4943}
4944
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004945/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4946/// TheCall is a constant expression is a multiple of Num..
4947bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4948 unsigned Num) {
4949 llvm::APSInt Result;
4950
4951 // We can't check the value of a dependent argument.
4952 Expr *Arg = TheCall->getArg(ArgNum);
4953 if (Arg->isTypeDependent() || Arg->isValueDependent())
4954 return false;
4955
4956 // Check constant-ness first.
4957 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4958 return true;
4959
4960 if (Result.getSExtValue() % Num != 0)
4961 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4962 << Num << Arg->getSourceRange();
4963
4964 return false;
4965}
4966
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004967/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4968/// TheCall is an ARM/AArch64 special register string literal.
4969bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4970 int ArgNum, unsigned ExpectedFieldNum,
4971 bool AllowName) {
4972 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4973 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4974 BuiltinID == ARM::BI__builtin_arm_rsr ||
4975 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4976 BuiltinID == ARM::BI__builtin_arm_wsr ||
4977 BuiltinID == ARM::BI__builtin_arm_wsrp;
4978 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4979 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4980 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4981 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4982 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4983 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4984 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4985
4986 // We can't check the value of a dependent argument.
4987 Expr *Arg = TheCall->getArg(ArgNum);
4988 if (Arg->isTypeDependent() || Arg->isValueDependent())
4989 return false;
4990
4991 // Check if the argument is a string literal.
4992 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4993 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4994 << Arg->getSourceRange();
4995
4996 // Check the type of special register given.
4997 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4998 SmallVector<StringRef, 6> Fields;
4999 Reg.split(Fields, ":");
5000
5001 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
5002 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
5003 << Arg->getSourceRange();
5004
5005 // If the string is the name of a register then we cannot check that it is
5006 // valid here but if the string is of one the forms described in ACLE then we
5007 // can check that the supplied fields are integers and within the valid
5008 // ranges.
5009 if (Fields.size() > 1) {
5010 bool FiveFields = Fields.size() == 5;
5011
5012 bool ValidString = true;
5013 if (IsARMBuiltin) {
5014 ValidString &= Fields[0].startswith_lower("cp") ||
5015 Fields[0].startswith_lower("p");
5016 if (ValidString)
5017 Fields[0] =
5018 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
5019
5020 ValidString &= Fields[2].startswith_lower("c");
5021 if (ValidString)
5022 Fields[2] = Fields[2].drop_front(1);
5023
5024 if (FiveFields) {
5025 ValidString &= Fields[3].startswith_lower("c");
5026 if (ValidString)
5027 Fields[3] = Fields[3].drop_front(1);
5028 }
5029 }
5030
5031 SmallVector<int, 5> Ranges;
5032 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00005033 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00005034 else
5035 Ranges.append({15, 7, 15});
5036
5037 for (unsigned i=0; i<Fields.size(); ++i) {
5038 int IntField;
5039 ValidString &= !Fields[i].getAsInteger(10, IntField);
5040 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
5041 }
5042
5043 if (!ValidString)
5044 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
5045 << Arg->getSourceRange();
Luke Cheeseman59b2d832015-06-15 17:51:01 +00005046 } else if (IsAArch64Builtin && Fields.size() == 1) {
5047 // If the register name is one of those that appear in the condition below
5048 // and the special register builtin being used is one of the write builtins,
5049 // then we require that the argument provided for writing to the register
5050 // is an integer constant expression. This is because it will be lowered to
5051 // an MSR (immediate) instruction, so we need to know the immediate at
5052 // compile time.
5053 if (TheCall->getNumArgs() != 2)
5054 return false;
5055
5056 std::string RegLower = Reg.lower();
5057 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
5058 RegLower != "pan" && RegLower != "uao")
5059 return false;
5060
5061 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
5062 }
5063
5064 return false;
5065}
5066
Eli Friedmanc97d0142009-05-03 06:04:26 +00005067/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005068/// This checks that the target supports __builtin_longjmp and
5069/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00005070bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005071 if (!Context.getTargetInfo().hasSjLjLowering())
5072 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
5073 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
5074
Eli Friedmaneed8ad22009-05-03 04:46:36 +00005075 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00005076 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00005077
Eric Christopher8d0c6212010-04-17 02:26:23 +00005078 // TODO: This is less than ideal. Overload this to take a value.
5079 if (SemaBuiltinConstantArg(TheCall, 1, Result))
5080 return true;
5081
5082 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00005083 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
5084 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
5085
5086 return false;
5087}
5088
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005089/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
5090/// This checks that the target supports __builtin_setjmp.
5091bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
5092 if (!Context.getTargetInfo().hasSjLjLowering())
5093 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
5094 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
5095 return false;
5096}
5097
Richard Smithd7293d72013-08-05 18:49:43 +00005098namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005099
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005100class UncoveredArgHandler {
5101 enum { Unknown = -1, AllCovered = -2 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005102
5103 signed FirstUncoveredArg = Unknown;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005104 SmallVector<const Expr *, 4> DiagnosticExprs;
5105
5106public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005107 UncoveredArgHandler() = default;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005108
5109 bool hasUncoveredArg() const {
5110 return (FirstUncoveredArg >= 0);
5111 }
5112
5113 unsigned getUncoveredArg() const {
5114 assert(hasUncoveredArg() && "no uncovered argument");
5115 return FirstUncoveredArg;
5116 }
5117
5118 void setAllCovered() {
5119 // A string has been found with all arguments covered, so clear out
5120 // the diagnostics.
5121 DiagnosticExprs.clear();
5122 FirstUncoveredArg = AllCovered;
5123 }
5124
5125 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
5126 assert(NewFirstUncoveredArg >= 0 && "Outside range");
5127
5128 // Don't update if a previous string covers all arguments.
5129 if (FirstUncoveredArg == AllCovered)
5130 return;
5131
5132 // UncoveredArgHandler tracks the highest uncovered argument index
5133 // and with it all the strings that match this index.
5134 if (NewFirstUncoveredArg == FirstUncoveredArg)
5135 DiagnosticExprs.push_back(StrExpr);
5136 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
5137 DiagnosticExprs.clear();
5138 DiagnosticExprs.push_back(StrExpr);
5139 FirstUncoveredArg = NewFirstUncoveredArg;
5140 }
5141 }
5142
5143 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
5144};
5145
Richard Smithd7293d72013-08-05 18:49:43 +00005146enum StringLiteralCheckType {
5147 SLCT_NotALiteral,
5148 SLCT_UncheckedLiteral,
5149 SLCT_CheckedLiteral
5150};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005151
5152} // namespace
Richard Smithd7293d72013-08-05 18:49:43 +00005153
Stephen Hines648c3692016-09-16 01:07:04 +00005154static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
5155 BinaryOperatorKind BinOpKind,
5156 bool AddendIsRight) {
5157 unsigned BitWidth = Offset.getBitWidth();
5158 unsigned AddendBitWidth = Addend.getBitWidth();
5159 // There might be negative interim results.
5160 if (Addend.isUnsigned()) {
5161 Addend = Addend.zext(++AddendBitWidth);
5162 Addend.setIsSigned(true);
5163 }
5164 // Adjust the bit width of the APSInts.
5165 if (AddendBitWidth > BitWidth) {
5166 Offset = Offset.sext(AddendBitWidth);
5167 BitWidth = AddendBitWidth;
5168 } else if (BitWidth > AddendBitWidth) {
5169 Addend = Addend.sext(BitWidth);
5170 }
5171
5172 bool Ov = false;
5173 llvm::APSInt ResOffset = Offset;
5174 if (BinOpKind == BO_Add)
5175 ResOffset = Offset.sadd_ov(Addend, Ov);
5176 else {
5177 assert(AddendIsRight && BinOpKind == BO_Sub &&
5178 "operator must be add or sub with addend on the right");
5179 ResOffset = Offset.ssub_ov(Addend, Ov);
5180 }
5181
5182 // We add an offset to a pointer here so we should support an offset as big as
5183 // possible.
5184 if (Ov) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005185 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
5186 "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00005187 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00005188 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
5189 return;
5190 }
5191
5192 Offset = ResOffset;
5193}
5194
5195namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005196
Stephen Hines648c3692016-09-16 01:07:04 +00005197// This is a wrapper class around StringLiteral to support offsetted string
5198// literals as format strings. It takes the offset into account when returning
5199// the string and its length or the source locations to display notes correctly.
5200class FormatStringLiteral {
5201 const StringLiteral *FExpr;
5202 int64_t Offset;
5203
5204 public:
5205 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
5206 : FExpr(fexpr), Offset(Offset) {}
5207
5208 StringRef getString() const {
5209 return FExpr->getString().drop_front(Offset);
5210 }
5211
5212 unsigned getByteLength() const {
5213 return FExpr->getByteLength() - getCharByteWidth() * Offset;
5214 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005215
Stephen Hines648c3692016-09-16 01:07:04 +00005216 unsigned getLength() const { return FExpr->getLength() - Offset; }
5217 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
5218
5219 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
5220
5221 QualType getType() const { return FExpr->getType(); }
5222
5223 bool isAscii() const { return FExpr->isAscii(); }
5224 bool isWide() const { return FExpr->isWide(); }
5225 bool isUTF8() const { return FExpr->isUTF8(); }
5226 bool isUTF16() const { return FExpr->isUTF16(); }
5227 bool isUTF32() const { return FExpr->isUTF32(); }
5228 bool isPascal() const { return FExpr->isPascal(); }
5229
5230 SourceLocation getLocationOfByte(
5231 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
5232 const TargetInfo &Target, unsigned *StartToken = nullptr,
5233 unsigned *StartTokenByteOffset = nullptr) const {
5234 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
5235 StartToken, StartTokenByteOffset);
5236 }
5237
5238 SourceLocation getLocStart() const LLVM_READONLY {
5239 return FExpr->getLocStart().getLocWithOffset(Offset);
5240 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005241
Stephen Hines648c3692016-09-16 01:07:04 +00005242 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
5243};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005244
5245} // namespace
Stephen Hines648c3692016-09-16 01:07:04 +00005246
5247static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005248 const Expr *OrigFormatExpr,
5249 ArrayRef<const Expr *> Args,
5250 bool HasVAListArg, unsigned format_idx,
5251 unsigned firstDataArg,
5252 Sema::FormatStringType Type,
5253 bool inFunctionCall,
5254 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005255 llvm::SmallBitVector &CheckedVarArgs,
5256 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005257
Richard Smith55ce3522012-06-25 20:30:08 +00005258// Determine if an expression is a string literal or constant string.
5259// If this function returns false on the arguments to a function expecting a
5260// format string, we will usually need to emit a warning.
5261// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00005262static StringLiteralCheckType
5263checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
5264 bool HasVAListArg, unsigned format_idx,
5265 unsigned firstDataArg, Sema::FormatStringType Type,
5266 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005267 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005268 UncoveredArgHandler &UncoveredArg,
5269 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00005270 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00005271 assert(Offset.isSigned() && "invalid offset");
5272
Douglas Gregorc25f7662009-05-19 22:10:17 +00005273 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00005274 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005275
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005276 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00005277
Richard Smithd7293d72013-08-05 18:49:43 +00005278 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00005279 // Technically -Wformat-nonliteral does not warn about this case.
5280 // The behavior of printf and friends in this case is implementation
5281 // dependent. Ideally if the format string cannot be null then
5282 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00005283 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00005284
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005285 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00005286 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005287 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00005288 // The expression is a literal if both sub-expressions were, and it was
5289 // completely checked only if both sub-expressions were checked.
5290 const AbstractConditionalOperator *C =
5291 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005292
5293 // Determine whether it is necessary to check both sub-expressions, for
5294 // example, because the condition expression is a constant that can be
5295 // evaluated at compile time.
5296 bool CheckLeft = true, CheckRight = true;
5297
5298 bool Cond;
5299 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
5300 if (Cond)
5301 CheckRight = false;
5302 else
5303 CheckLeft = false;
5304 }
5305
Stephen Hines648c3692016-09-16 01:07:04 +00005306 // We need to maintain the offsets for the right and the left hand side
5307 // separately to check if every possible indexed expression is a valid
5308 // string literal. They might have different offsets for different string
5309 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005310 StringLiteralCheckType Left;
5311 if (!CheckLeft)
5312 Left = SLCT_UncheckedLiteral;
5313 else {
5314 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
5315 HasVAListArg, format_idx, firstDataArg,
5316 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005317 CheckedVarArgs, UncoveredArg, Offset);
5318 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005319 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00005320 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005321 }
5322
Richard Smith55ce3522012-06-25 20:30:08 +00005323 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00005324 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005325 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005326 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005327 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005328
5329 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005330 }
5331
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005332 case Stmt::ImplicitCastExprClass:
Ted Kremenek808829352010-09-09 03:51:39 +00005333 E = cast<ImplicitCastExpr>(E)->getSubExpr();
5334 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005335
John McCallc07a0c72011-02-17 10:25:35 +00005336 case Stmt::OpaqueValueExprClass:
5337 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
5338 E = src;
5339 goto tryAgain;
5340 }
Richard Smith55ce3522012-06-25 20:30:08 +00005341 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00005342
Ted Kremeneka8890832011-02-24 23:03:04 +00005343 case Stmt::PredefinedExprClass:
5344 // While __func__, etc., are technically not string literals, they
5345 // cannot contain format specifiers and thus are not a security
5346 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00005347 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00005348
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005349 case Stmt::DeclRefExprClass: {
5350 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005351
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005352 // As an exception, do not flag errors for variables binding to
5353 // const string literals.
5354 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
5355 bool isConstant = false;
5356 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005357
Richard Smithd7293d72013-08-05 18:49:43 +00005358 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
5359 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00005360 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00005361 isConstant = T.isConstant(S.Context) &&
5362 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00005363 } else if (T->isObjCObjectPointerType()) {
5364 // In ObjC, there is usually no "const ObjectPointer" type,
5365 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00005366 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005367 }
Mike Stump11289f42009-09-09 15:08:12 +00005368
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005369 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00005370 if (const Expr *Init = VD->getAnyInitializer()) {
5371 // Look through initializers like const char c[] = { "foo" }
5372 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
5373 if (InitList->isStringLiteralInit())
5374 Init = InitList->getInit(0)->IgnoreParenImpCasts();
5375 }
Richard Smithd7293d72013-08-05 18:49:43 +00005376 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005377 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005378 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005379 /*InFunctionCall*/ false, CheckedVarArgs,
5380 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00005381 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005382 }
Mike Stump11289f42009-09-09 15:08:12 +00005383
Anders Carlssonb012ca92009-06-28 19:55:58 +00005384 // For vprintf* functions (i.e., HasVAListArg==true), we add a
5385 // special check to see if the format string is a function parameter
5386 // of the function calling the printf function. If the function
5387 // has an attribute indicating it is a printf-like function, then we
5388 // should suppress warnings concerning non-literals being used in a call
5389 // to a vprintf function. For example:
5390 //
5391 // void
5392 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
5393 // va_list ap;
5394 // va_start(ap, fmt);
5395 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
5396 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00005397 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005398 if (HasVAListArg) {
5399 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
5400 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
5401 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00005402 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005403 // adjust for implicit parameter
5404 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5405 if (MD->isInstance())
5406 ++PVIndex;
5407 // We also check if the formats are compatible.
5408 // We can't pass a 'scanf' string to a 'printf' function.
5409 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00005410 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00005411 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005412 }
5413 }
5414 }
5415 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005416 }
Mike Stump11289f42009-09-09 15:08:12 +00005417
Richard Smith55ce3522012-06-25 20:30:08 +00005418 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005419 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005420
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005421 case Stmt::CallExprClass:
5422 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005423 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005424 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5425 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00005426 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
Richard Smithd7293d72013-08-05 18:49:43 +00005427 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005428 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00005429 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005430 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005431 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5432 unsigned BuiltinID = FD->getBuiltinID();
5433 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5434 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5435 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00005436 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005437 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005438 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005439 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005440 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005441 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005442 }
5443 }
Mike Stump11289f42009-09-09 15:08:12 +00005444
Richard Smith55ce3522012-06-25 20:30:08 +00005445 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005446 }
Alex Lorenzd9007142016-10-24 09:42:34 +00005447 case Stmt::ObjCMessageExprClass: {
5448 const auto *ME = cast<ObjCMessageExpr>(E);
5449 if (const auto *ND = ME->getMethodDecl()) {
5450 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00005451 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
Alex Lorenzd9007142016-10-24 09:42:34 +00005452 return checkFormatStringExpr(
5453 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5454 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5455 }
5456 }
5457
5458 return SLCT_NotALiteral;
5459 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005460 case Stmt::ObjCStringLiteralClass:
5461 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00005462 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005463
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005464 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005465 StrE = ObjCFExpr->getString();
5466 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005467 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005468
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005469 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005470 if (Offset.isNegative() || Offset > StrE->getLength()) {
5471 // TODO: It would be better to have an explicit warning for out of
5472 // bounds literals.
5473 return SLCT_NotALiteral;
5474 }
5475 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5476 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005477 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005478 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00005479 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005480 }
Mike Stump11289f42009-09-09 15:08:12 +00005481
Richard Smith55ce3522012-06-25 20:30:08 +00005482 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005483 }
Stephen Hines648c3692016-09-16 01:07:04 +00005484 case Stmt::BinaryOperatorClass: {
5485 llvm::APSInt LResult;
5486 llvm::APSInt RResult;
5487
5488 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5489
5490 // A string literal + an int offset is still a string literal.
5491 if (BinOp->isAdditiveOp()) {
5492 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5493 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5494
5495 if (LIsInt != RIsInt) {
5496 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5497
5498 if (LIsInt) {
5499 if (BinOpKind == BO_Add) {
5500 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5501 E = BinOp->getRHS();
5502 goto tryAgain;
5503 }
5504 } else {
5505 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5506 E = BinOp->getLHS();
5507 goto tryAgain;
5508 }
5509 }
Stephen Hines648c3692016-09-16 01:07:04 +00005510 }
George Burgess IVd273aab2016-09-22 00:00:26 +00005511
5512 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00005513 }
5514 case Stmt::UnaryOperatorClass: {
5515 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5516 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005517 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005518 llvm::APSInt IndexResult;
5519 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5520 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5521 E = ASE->getBase();
5522 goto tryAgain;
5523 }
5524 }
5525
5526 return SLCT_NotALiteral;
5527 }
Mike Stump11289f42009-09-09 15:08:12 +00005528
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005529 default:
Richard Smith55ce3522012-06-25 20:30:08 +00005530 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005531 }
5532}
5533
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005534Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00005535 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00005536 .Case("scanf", FST_Scanf)
5537 .Cases("printf", "printf0", FST_Printf)
5538 .Cases("NSString", "CFString", FST_NSString)
5539 .Case("strftime", FST_Strftime)
5540 .Case("strfmon", FST_Strfmon)
5541 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5542 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5543 .Case("os_trace", FST_OSLog)
5544 .Case("os_log", FST_OSLog)
5545 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005546}
5547
Jordan Rose3e0ec582012-07-19 18:10:23 +00005548/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00005549/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00005550/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005551bool Sema::CheckFormatArguments(const FormatAttr *Format,
5552 ArrayRef<const Expr *> Args,
5553 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005554 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005555 SourceLocation Loc, SourceRange Range,
5556 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00005557 FormatStringInfo FSI;
5558 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005559 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00005560 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00005561 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00005562 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005563}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00005564
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005565bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005566 bool HasVAListArg, unsigned format_idx,
5567 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005568 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005569 SourceLocation Loc, SourceRange Range,
5570 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00005571 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005572 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005573 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00005574 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005575 }
Mike Stump11289f42009-09-09 15:08:12 +00005576
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005577 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005578
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005579 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00005580 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005581 // Dynamically generated format strings are difficult to
5582 // automatically vet at compile time. Requiring that format strings
5583 // are string literals: (1) permits the checking of format strings by
5584 // the compiler and thereby (2) can practically remove the source of
5585 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00005586
Mike Stump11289f42009-09-09 15:08:12 +00005587 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00005588 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00005589 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00005590 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005591 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00005592 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00005593 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5594 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005595 /*IsFunctionCall*/ true, CheckedVarArgs,
5596 UncoveredArg,
5597 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005598
5599 // Generate a diagnostic where an uncovered argument is detected.
5600 if (UncoveredArg.hasUncoveredArg()) {
5601 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5602 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5603 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5604 }
5605
Richard Smith55ce3522012-06-25 20:30:08 +00005606 if (CT != SLCT_NotALiteral)
5607 // Literal format string found, check done!
5608 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00005609
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005610 // Strftime is particular as it always uses a single 'time' argument,
5611 // so it is safe to pass a non-literal string.
5612 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00005613 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005614
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005615 // Do not emit diag when the string param is a macro expansion and the
5616 // format is either NSString or CFString. This is a hack to prevent
5617 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5618 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005619 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5620 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00005621 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005622
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005623 // If there are no arguments specified, warn with -Wformat-security, otherwise
5624 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005625 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00005626 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5627 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005628 switch (Type) {
5629 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005630 break;
5631 case FST_Kprintf:
5632 case FST_FreeBSDKPrintf:
5633 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00005634 Diag(FormatLoc, diag::note_format_security_fixit)
5635 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005636 break;
5637 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00005638 Diag(FormatLoc, diag::note_format_security_fixit)
5639 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005640 break;
5641 }
5642 } else {
5643 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005644 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005645 }
Richard Smith55ce3522012-06-25 20:30:08 +00005646 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005647}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005648
Ted Kremenekab278de2010-01-28 23:39:18 +00005649namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005650
Ted Kremenek02087932010-07-16 02:11:22 +00005651class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5652protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005653 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005654 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005655 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005656 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005657 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005658 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005659 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005660 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005661 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005662 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005663 llvm::SmallBitVector CoveredArgs;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005664 bool usesPositionalArgs = false;
5665 bool atFirstArg = true;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005666 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005667 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005668 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005669 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005670
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005671public:
Stephen Hines648c3692016-09-16 01:07:04 +00005672 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005673 const Expr *origFormatExpr,
5674 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005675 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005676 ArrayRef<const Expr *> Args, unsigned formatIdx,
5677 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005678 llvm::SmallBitVector &CheckedVarArgs,
5679 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005680 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5681 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5682 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
Mehdi Amini06d367c2016-10-24 20:39:34 +00005683 inFunctionCall(inFunctionCall), CallType(callType),
5684 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005685 CoveredArgs.resize(numDataArgs);
5686 CoveredArgs.reset();
5687 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005688
Ted Kremenek019d2242010-01-29 01:50:07 +00005689 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005690
Ted Kremenek02087932010-07-16 02:11:22 +00005691 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005692 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005693
Jordan Rose92303592012-09-08 04:00:03 +00005694 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005695 const analyze_format_string::FormatSpecifier &FS,
5696 const analyze_format_string::ConversionSpecifier &CS,
5697 const char *startSpecifier, unsigned specifierLen,
5698 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005699
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005700 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005701 const analyze_format_string::FormatSpecifier &FS,
5702 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005703
5704 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005705 const analyze_format_string::ConversionSpecifier &CS,
5706 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005707
Craig Toppere14c0f82014-03-12 04:55:44 +00005708 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005709
Craig Toppere14c0f82014-03-12 04:55:44 +00005710 void HandleInvalidPosition(const char *startSpecifier,
5711 unsigned specifierLen,
5712 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005713
Craig Toppere14c0f82014-03-12 04:55:44 +00005714 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005715
Craig Toppere14c0f82014-03-12 04:55:44 +00005716 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005717
Richard Trieu03cf7b72011-10-28 00:41:25 +00005718 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005719 static void
5720 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5721 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5722 bool IsStringLocation, Range StringRange,
5723 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005724
Ted Kremenek02087932010-07-16 02:11:22 +00005725protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005726 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5727 const char *startSpec,
5728 unsigned specifierLen,
5729 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005730
5731 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5732 const char *startSpec,
5733 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005734
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005735 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005736 CharSourceRange getSpecifierRange(const char *startSpecifier,
5737 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005738 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005739
Ted Kremenek5739de72010-01-29 01:06:55 +00005740 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005741
5742 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5743 const analyze_format_string::ConversionSpecifier &CS,
5744 const char *startSpecifier, unsigned specifierLen,
5745 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005746
5747 template <typename Range>
5748 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5749 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005750 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005751};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005752
5753} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005754
Ted Kremenek02087932010-07-16 02:11:22 +00005755SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005756 return OrigFormatExpr->getSourceRange();
5757}
5758
Ted Kremenek02087932010-07-16 02:11:22 +00005759CharSourceRange CheckFormatHandler::
5760getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005761 SourceLocation Start = getLocationOfByte(startSpecifier);
5762 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5763
5764 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005765 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005766
5767 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005768}
5769
Ted Kremenek02087932010-07-16 02:11:22 +00005770SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005771 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5772 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005773}
5774
Ted Kremenek02087932010-07-16 02:11:22 +00005775void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5776 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005777 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5778 getLocationOfByte(startSpecifier),
5779 /*IsStringLocation*/true,
5780 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005781}
5782
Jordan Rose92303592012-09-08 04:00:03 +00005783void CheckFormatHandler::HandleInvalidLengthModifier(
5784 const analyze_format_string::FormatSpecifier &FS,
5785 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005786 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005787 using namespace analyze_format_string;
5788
5789 const LengthModifier &LM = FS.getLengthModifier();
5790 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5791
5792 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005793 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005794 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005795 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005796 getLocationOfByte(LM.getStart()),
5797 /*IsStringLocation*/true,
5798 getSpecifierRange(startSpecifier, specifierLen));
5799
5800 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5801 << FixedLM->toString()
5802 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5803
5804 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005805 FixItHint Hint;
5806 if (DiagID == diag::warn_format_nonsensical_length)
5807 Hint = FixItHint::CreateRemoval(LMRange);
5808
5809 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005810 getLocationOfByte(LM.getStart()),
5811 /*IsStringLocation*/true,
5812 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005813 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005814 }
5815}
5816
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005817void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005818 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005819 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005820 using namespace analyze_format_string;
5821
5822 const LengthModifier &LM = FS.getLengthModifier();
5823 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5824
5825 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005826 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005827 if (FixedLM) {
5828 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5829 << LM.toString() << 0,
5830 getLocationOfByte(LM.getStart()),
5831 /*IsStringLocation*/true,
5832 getSpecifierRange(startSpecifier, specifierLen));
5833
5834 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5835 << FixedLM->toString()
5836 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5837
5838 } else {
5839 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5840 << LM.toString() << 0,
5841 getLocationOfByte(LM.getStart()),
5842 /*IsStringLocation*/true,
5843 getSpecifierRange(startSpecifier, specifierLen));
5844 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005845}
5846
5847void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5848 const analyze_format_string::ConversionSpecifier &CS,
5849 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005850 using namespace analyze_format_string;
5851
5852 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005853 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005854 if (FixedCS) {
5855 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5856 << CS.toString() << /*conversion specifier*/1,
5857 getLocationOfByte(CS.getStart()),
5858 /*IsStringLocation*/true,
5859 getSpecifierRange(startSpecifier, specifierLen));
5860
5861 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5862 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5863 << FixedCS->toString()
5864 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5865 } else {
5866 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5867 << CS.toString() << /*conversion specifier*/1,
5868 getLocationOfByte(CS.getStart()),
5869 /*IsStringLocation*/true,
5870 getSpecifierRange(startSpecifier, specifierLen));
5871 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005872}
5873
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005874void CheckFormatHandler::HandlePosition(const char *startPos,
5875 unsigned posLen) {
5876 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5877 getLocationOfByte(startPos),
5878 /*IsStringLocation*/true,
5879 getSpecifierRange(startPos, posLen));
5880}
5881
Ted Kremenekd1668192010-02-27 01:41:03 +00005882void
Ted Kremenek02087932010-07-16 02:11:22 +00005883CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5884 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005885 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5886 << (unsigned) p,
5887 getLocationOfByte(startPos), /*IsStringLocation*/true,
5888 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005889}
5890
Ted Kremenek02087932010-07-16 02:11:22 +00005891void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005892 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005893 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5894 getLocationOfByte(startPos),
5895 /*IsStringLocation*/true,
5896 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005897}
5898
Ted Kremenek02087932010-07-16 02:11:22 +00005899void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005900 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005901 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005902 EmitFormatDiagnostic(
5903 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5904 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5905 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005906 }
Ted Kremenek02087932010-07-16 02:11:22 +00005907}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005908
Jordan Rose58bbe422012-07-19 18:10:08 +00005909// Note that this may return NULL if there was an error parsing or building
5910// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005911const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005912 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005913}
5914
5915void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005916 // Does the number of data arguments exceed the number of
5917 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005918 if (!HasVAListArg) {
5919 // Find any arguments that weren't covered.
5920 CoveredArgs.flip();
5921 signed notCoveredArg = CoveredArgs.find_first();
5922 if (notCoveredArg >= 0) {
5923 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005924 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5925 } else {
5926 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005927 }
5928 }
5929}
5930
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005931void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5932 const Expr *ArgExpr) {
5933 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5934 "Invalid state");
5935
5936 if (!ArgExpr)
5937 return;
5938
5939 SourceLocation Loc = ArgExpr->getLocStart();
5940
5941 if (S.getSourceManager().isInSystemMacro(Loc))
5942 return;
5943
5944 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5945 for (auto E : DiagnosticExprs)
5946 PDiag << E->getSourceRange();
5947
5948 CheckFormatHandler::EmitFormatDiagnostic(
5949 S, IsFunctionCall, DiagnosticExprs[0],
5950 PDiag, Loc, /*IsStringLocation*/false,
5951 DiagnosticExprs[0]->getSourceRange());
5952}
5953
Ted Kremenekce815422010-07-19 21:25:57 +00005954bool
5955CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5956 SourceLocation Loc,
5957 const char *startSpec,
5958 unsigned specifierLen,
5959 const char *csStart,
5960 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005961 bool keepGoing = true;
5962 if (argIndex < NumDataArgs) {
5963 // Consider the argument coverered, even though the specifier doesn't
5964 // make sense.
5965 CoveredArgs.set(argIndex);
5966 }
5967 else {
5968 // If argIndex exceeds the number of data arguments we
5969 // don't issue a warning because that is just a cascade of warnings (and
5970 // they may have intended '%%' anyway). We don't want to continue processing
5971 // the format string after this point, however, as we will like just get
5972 // gibberish when trying to match arguments.
5973 keepGoing = false;
5974 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005975
5976 StringRef Specifier(csStart, csLen);
5977
5978 // If the specifier in non-printable, it could be the first byte of a UTF-8
5979 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5980 // hex value.
5981 std::string CodePointStr;
5982 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005983 llvm::UTF32 CodePoint;
5984 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5985 const llvm::UTF8 *E =
5986 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5987 llvm::ConversionResult Result =
5988 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005989
Justin Lebar90910552016-09-30 00:38:45 +00005990 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005991 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005992 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005993 }
5994
5995 llvm::raw_string_ostream OS(CodePointStr);
5996 if (CodePoint < 256)
5997 OS << "\\x" << llvm::format("%02x", CodePoint);
5998 else if (CodePoint <= 0xFFFF)
5999 OS << "\\u" << llvm::format("%04x", CodePoint);
6000 else
6001 OS << "\\U" << llvm::format("%08x", CodePoint);
6002 OS.flush();
6003 Specifier = CodePointStr;
6004 }
6005
6006 EmitFormatDiagnostic(
6007 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
6008 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
6009
Ted Kremenekce815422010-07-19 21:25:57 +00006010 return keepGoing;
6011}
6012
Richard Trieu03cf7b72011-10-28 00:41:25 +00006013void
6014CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
6015 const char *startSpec,
6016 unsigned specifierLen) {
6017 EmitFormatDiagnostic(
6018 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
6019 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
6020}
6021
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006022bool
6023CheckFormatHandler::CheckNumArgs(
6024 const analyze_format_string::FormatSpecifier &FS,
6025 const analyze_format_string::ConversionSpecifier &CS,
6026 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
6027
6028 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006029 PartialDiagnostic PDiag = FS.usesPositionalArg()
6030 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
6031 << (argIndex+1) << NumDataArgs)
6032 : S.PDiag(diag::warn_printf_insufficient_data_args);
6033 EmitFormatDiagnostic(
6034 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
6035 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006036
6037 // Since more arguments than conversion tokens are given, by extension
6038 // all arguments are covered, so mark this as so.
6039 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006040 return false;
6041 }
6042 return true;
6043}
6044
Richard Trieu03cf7b72011-10-28 00:41:25 +00006045template<typename Range>
6046void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
6047 SourceLocation Loc,
6048 bool IsStringLocation,
6049 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00006050 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00006051 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00006052 Loc, IsStringLocation, StringRange, FixIt);
6053}
6054
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006055/// If the format string is not within the function call, emit a note
Richard Trieu03cf7b72011-10-28 00:41:25 +00006056/// so that the function call and string are in diagnostic messages.
6057///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00006058/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00006059/// call and only one diagnostic message will be produced. Otherwise, an
6060/// extra note will be emitted pointing to location of the format string.
6061///
6062/// \param ArgumentExpr the expression that is passed as the format string
6063/// argument in the function call. Used for getting locations when two
6064/// diagnostics are emitted.
6065///
6066/// \param PDiag the callee should already have provided any strings for the
6067/// diagnostic message. This function only adds locations and fixits
6068/// to diagnostics.
6069///
6070/// \param Loc primary location for diagnostic. If two diagnostics are
6071/// required, one will be at Loc and a new SourceLocation will be created for
6072/// the other one.
6073///
6074/// \param IsStringLocation if true, Loc points to the format string should be
6075/// used for the note. Otherwise, Loc points to the argument list and will
6076/// be used with PDiag.
6077///
6078/// \param StringRange some or all of the string to highlight. This is
6079/// templated so it can accept either a CharSourceRange or a SourceRange.
6080///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00006081/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00006082template <typename Range>
6083void CheckFormatHandler::EmitFormatDiagnostic(
6084 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
6085 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
6086 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00006087 if (InFunctionCall) {
6088 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
6089 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00006090 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00006091 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006092 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
6093 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00006094
6095 const Sema::SemaDiagnosticBuilder &Note =
6096 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
6097 diag::note_format_string_defined);
6098
6099 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00006100 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00006101 }
6102}
6103
Ted Kremenek02087932010-07-16 02:11:22 +00006104//===--- CHECK: Printf format string checking ------------------------------===//
6105
6106namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006107
Ted Kremenek02087932010-07-16 02:11:22 +00006108class CheckPrintfHandler : public CheckFormatHandler {
6109public:
Stephen Hines648c3692016-09-16 01:07:04 +00006110 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006111 const Expr *origFormatExpr,
6112 const Sema::FormatStringType type, unsigned firstDataArg,
6113 unsigned numDataArgs, bool isObjC, const char *beg,
6114 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006115 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00006116 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006117 llvm::SmallBitVector &CheckedVarArgs,
6118 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006119 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6120 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6121 inFunctionCall, CallType, CheckedVarArgs,
6122 UncoveredArg) {}
6123
6124 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
6125
6126 /// Returns true if '%@' specifiers are allowed in the format string.
6127 bool allowsObjCArg() const {
6128 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
6129 FSType == Sema::FST_OSTrace;
6130 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00006131
Ted Kremenek02087932010-07-16 02:11:22 +00006132 bool HandleInvalidPrintfConversionSpecifier(
6133 const analyze_printf::PrintfSpecifier &FS,
6134 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006135 unsigned specifierLen) override;
6136
Ted Kremenek02087932010-07-16 02:11:22 +00006137 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
6138 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006139 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00006140 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6141 const char *StartSpecifier,
6142 unsigned SpecifierLen,
6143 const Expr *E);
6144
Ted Kremenek02087932010-07-16 02:11:22 +00006145 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
6146 const char *startSpecifier, unsigned specifierLen);
6147 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
6148 const analyze_printf::OptionalAmount &Amt,
6149 unsigned type,
6150 const char *startSpecifier, unsigned specifierLen);
6151 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
6152 const analyze_printf::OptionalFlag &flag,
6153 const char *startSpecifier, unsigned specifierLen);
6154 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
6155 const analyze_printf::OptionalFlag &ignoredFlag,
6156 const analyze_printf::OptionalFlag &flag,
6157 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006158 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00006159 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00006160
6161 void HandleEmptyObjCModifierFlag(const char *startFlag,
6162 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00006163
Ted Kremenek2b417712015-07-02 05:39:16 +00006164 void HandleInvalidObjCModifierFlag(const char *startFlag,
6165 unsigned flagLen) override;
6166
6167 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
6168 const char *flagsEnd,
6169 const char *conversionPosition)
6170 override;
6171};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006172
6173} // namespace
Ted Kremenek02087932010-07-16 02:11:22 +00006174
6175bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
6176 const analyze_printf::PrintfSpecifier &FS,
6177 const char *startSpecifier,
6178 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006179 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006180 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006181
Ted Kremenekce815422010-07-19 21:25:57 +00006182 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6183 getLocationOfByte(CS.getStart()),
6184 startSpecifier, specifierLen,
6185 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00006186}
6187
Ted Kremenek02087932010-07-16 02:11:22 +00006188bool CheckPrintfHandler::HandleAmount(
6189 const analyze_format_string::OptionalAmount &Amt,
6190 unsigned k, const char *startSpecifier,
6191 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006192 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006193 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00006194 unsigned argIndex = Amt.getArgIndex();
6195 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006196 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
6197 << k,
6198 getLocationOfByte(Amt.getStart()),
6199 /*IsStringLocation*/true,
6200 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00006201 // Don't do any more checking. We will just emit
6202 // spurious errors.
6203 return false;
6204 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006205
Ted Kremenek5739de72010-01-29 01:06:55 +00006206 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00006207 // Although not in conformance with C99, we also allow the argument to be
6208 // an 'unsigned int' as that is a reasonably safe case. GCC also
6209 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00006210 CoveredArgs.set(argIndex);
6211 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006212 if (!Arg)
6213 return false;
6214
Ted Kremenek5739de72010-01-29 01:06:55 +00006215 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006216
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006217 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
6218 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006219
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006220 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006221 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006222 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00006223 << T << Arg->getSourceRange(),
6224 getLocationOfByte(Amt.getStart()),
6225 /*IsStringLocation*/true,
6226 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00006227 // Don't do any more checking. We will just emit
6228 // spurious errors.
6229 return false;
6230 }
6231 }
6232 }
6233 return true;
6234}
Ted Kremenek5739de72010-01-29 01:06:55 +00006235
Tom Careb49ec692010-06-17 19:00:27 +00006236void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00006237 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006238 const analyze_printf::OptionalAmount &Amt,
6239 unsigned type,
6240 const char *startSpecifier,
6241 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006242 const analyze_printf::PrintfConversionSpecifier &CS =
6243 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00006244
Richard Trieu03cf7b72011-10-28 00:41:25 +00006245 FixItHint fixit =
6246 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
6247 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
6248 Amt.getConstantLength()))
6249 : FixItHint();
6250
6251 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
6252 << type << CS.toString(),
6253 getLocationOfByte(Amt.getStart()),
6254 /*IsStringLocation*/true,
6255 getSpecifierRange(startSpecifier, specifierLen),
6256 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00006257}
6258
Ted Kremenek02087932010-07-16 02:11:22 +00006259void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006260 const analyze_printf::OptionalFlag &flag,
6261 const char *startSpecifier,
6262 unsigned specifierLen) {
6263 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006264 const analyze_printf::PrintfConversionSpecifier &CS =
6265 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00006266 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
6267 << flag.toString() << CS.toString(),
6268 getLocationOfByte(flag.getPosition()),
6269 /*IsStringLocation*/true,
6270 getSpecifierRange(startSpecifier, specifierLen),
6271 FixItHint::CreateRemoval(
6272 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00006273}
6274
6275void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00006276 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006277 const analyze_printf::OptionalFlag &ignoredFlag,
6278 const analyze_printf::OptionalFlag &flag,
6279 const char *startSpecifier,
6280 unsigned specifierLen) {
6281 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00006282 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
6283 << ignoredFlag.toString() << flag.toString(),
6284 getLocationOfByte(ignoredFlag.getPosition()),
6285 /*IsStringLocation*/true,
6286 getSpecifierRange(startSpecifier, specifierLen),
6287 FixItHint::CreateRemoval(
6288 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00006289}
6290
Ted Kremenek2b417712015-07-02 05:39:16 +00006291void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
6292 unsigned flagLen) {
6293 // Warn about an empty flag.
6294 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
6295 getLocationOfByte(startFlag),
6296 /*IsStringLocation*/true,
6297 getSpecifierRange(startFlag, flagLen));
6298}
6299
6300void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
6301 unsigned flagLen) {
6302 // Warn about an invalid flag.
6303 auto Range = getSpecifierRange(startFlag, flagLen);
6304 StringRef flag(startFlag, flagLen);
6305 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
6306 getLocationOfByte(startFlag),
6307 /*IsStringLocation*/true,
6308 Range, FixItHint::CreateRemoval(Range));
6309}
6310
6311void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
6312 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
6313 // Warn about using '[...]' without a '@' conversion.
6314 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
6315 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
6316 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
6317 getLocationOfByte(conversionPosition),
6318 /*IsStringLocation*/true,
6319 Range, FixItHint::CreateRemoval(Range));
6320}
6321
Richard Smith55ce3522012-06-25 20:30:08 +00006322// Determines if the specified is a C++ class or struct containing
6323// a member with the specified name and kind (e.g. a CXXMethodDecl named
6324// "c_str()").
6325template<typename MemberKind>
6326static llvm::SmallPtrSet<MemberKind*, 1>
6327CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
6328 const RecordType *RT = Ty->getAs<RecordType>();
6329 llvm::SmallPtrSet<MemberKind*, 1> Results;
6330
6331 if (!RT)
6332 return Results;
6333 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00006334 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00006335 return Results;
6336
Alp Tokerb6cc5922014-05-03 03:45:55 +00006337 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00006338 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00006339 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00006340
6341 // We just need to include all members of the right kind turned up by the
6342 // filter, at this point.
6343 if (S.LookupQualifiedName(R, RT->getDecl()))
6344 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6345 NamedDecl *decl = (*I)->getUnderlyingDecl();
6346 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
6347 Results.insert(FK);
6348 }
6349 return Results;
6350}
6351
Richard Smith2868a732014-02-28 01:36:39 +00006352/// Check if we could call '.c_str()' on an object.
6353///
6354/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
6355/// allow the call, or if it would be ambiguous).
6356bool Sema::hasCStrMethod(const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006357 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
6358
Richard Smith2868a732014-02-28 01:36:39 +00006359 MethodSet Results =
6360 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
6361 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6362 MI != ME; ++MI)
6363 if ((*MI)->getMinRequiredArguments() == 0)
6364 return true;
6365 return false;
6366}
6367
Richard Smith55ce3522012-06-25 20:30:08 +00006368// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006369// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00006370// Returns true when a c_str() conversion method is found.
6371bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00006372 const analyze_printf::ArgType &AT, const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006373 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
Richard Smith55ce3522012-06-25 20:30:08 +00006374
6375 MethodSet Results =
6376 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
6377
6378 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6379 MI != ME; ++MI) {
6380 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00006381 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00006382 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00006383 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00006384 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00006385 S.Diag(E->getLocStart(), diag::note_printf_c_str)
6386 << "c_str()"
6387 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
6388 return true;
6389 }
6390 }
6391
6392 return false;
6393}
6394
Ted Kremenekab278de2010-01-28 23:39:18 +00006395bool
Ted Kremenek02087932010-07-16 02:11:22 +00006396CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00006397 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00006398 const char *startSpecifier,
6399 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006400 using namespace analyze_format_string;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006401 using namespace analyze_printf;
6402
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006403 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00006404
Ted Kremenek6cd69422010-07-19 22:01:06 +00006405 if (FS.consumesDataArgument()) {
6406 if (atFirstArg) {
6407 atFirstArg = false;
6408 usesPositionalArgs = FS.usesPositionalArg();
6409 }
6410 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006411 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6412 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006413 return false;
6414 }
Ted Kremenek5739de72010-01-29 01:06:55 +00006415 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006416
Ted Kremenekd1668192010-02-27 01:41:03 +00006417 // First check if the field width, precision, and conversion specifier
6418 // have matching data arguments.
6419 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6420 startSpecifier, specifierLen)) {
6421 return false;
6422 }
6423
6424 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6425 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006426 return false;
6427 }
6428
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006429 if (!CS.consumesDataArgument()) {
6430 // FIXME: Technically specifying a precision or field width here
6431 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00006432 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006433 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006434
Ted Kremenek4a49d982010-02-26 19:18:41 +00006435 // Consume the argument.
6436 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00006437 if (argIndex < NumDataArgs) {
6438 // The check to see if the argIndex is valid will come later.
6439 // We set the bit here because we may exit early from this
6440 // function if we encounter some other error.
6441 CoveredArgs.set(argIndex);
6442 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00006443
Dimitry Andric6b5ed342015-02-19 22:32:33 +00006444 // FreeBSD kernel extensions.
6445 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6446 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6447 // We need at least two arguments.
6448 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6449 return false;
6450
6451 // Claim the second argument.
6452 CoveredArgs.set(argIndex + 1);
6453
6454 // Type check the first argument (int for %b, pointer for %D)
6455 const Expr *Ex = getDataArg(argIndex);
6456 const analyze_printf::ArgType &AT =
6457 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6458 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6459 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6460 EmitFormatDiagnostic(
6461 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6462 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6463 << false << Ex->getSourceRange(),
6464 Ex->getLocStart(), /*IsStringLocation*/false,
6465 getSpecifierRange(startSpecifier, specifierLen));
6466
6467 // Type check the second argument (char * for both %b and %D)
6468 Ex = getDataArg(argIndex + 1);
6469 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6470 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6471 EmitFormatDiagnostic(
6472 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6473 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6474 << false << Ex->getSourceRange(),
6475 Ex->getLocStart(), /*IsStringLocation*/false,
6476 getSpecifierRange(startSpecifier, specifierLen));
6477
6478 return true;
6479 }
6480
Ted Kremenek4a49d982010-02-26 19:18:41 +00006481 // Check for using an Objective-C specific conversion specifier
6482 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006483 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00006484 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6485 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00006486 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006487
Mehdi Amini06d367c2016-10-24 20:39:34 +00006488 // %P can only be used with os_log.
6489 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6490 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6491 specifierLen);
6492 }
6493
6494 // %n is not allowed with os_log.
6495 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6496 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6497 getLocationOfByte(CS.getStart()),
6498 /*IsStringLocation*/ false,
6499 getSpecifierRange(startSpecifier, specifierLen));
6500
6501 return true;
6502 }
6503
6504 // Only scalars are allowed for os_trace.
6505 if (FSType == Sema::FST_OSTrace &&
6506 (CS.getKind() == ConversionSpecifier::PArg ||
6507 CS.getKind() == ConversionSpecifier::sArg ||
6508 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6509 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6510 specifierLen);
6511 }
6512
6513 // Check for use of public/private annotation outside of os_log().
6514 if (FSType != Sema::FST_OSLog) {
6515 if (FS.isPublic().isSet()) {
6516 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6517 << "public",
6518 getLocationOfByte(FS.isPublic().getPosition()),
6519 /*IsStringLocation*/ false,
6520 getSpecifierRange(startSpecifier, specifierLen));
6521 }
6522 if (FS.isPrivate().isSet()) {
6523 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6524 << "private",
6525 getLocationOfByte(FS.isPrivate().getPosition()),
6526 /*IsStringLocation*/ false,
6527 getSpecifierRange(startSpecifier, specifierLen));
6528 }
6529 }
6530
Tom Careb49ec692010-06-17 19:00:27 +00006531 // Check for invalid use of field width
6532 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00006533 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00006534 startSpecifier, specifierLen);
6535 }
6536
6537 // Check for invalid use of precision
6538 if (!FS.hasValidPrecision()) {
6539 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6540 startSpecifier, specifierLen);
6541 }
6542
Mehdi Amini06d367c2016-10-24 20:39:34 +00006543 // Precision is mandatory for %P specifier.
6544 if (CS.getKind() == ConversionSpecifier::PArg &&
6545 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6546 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6547 getLocationOfByte(startSpecifier),
6548 /*IsStringLocation*/ false,
6549 getSpecifierRange(startSpecifier, specifierLen));
6550 }
6551
Tom Careb49ec692010-06-17 19:00:27 +00006552 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00006553 if (!FS.hasValidThousandsGroupingPrefix())
6554 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006555 if (!FS.hasValidLeadingZeros())
6556 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6557 if (!FS.hasValidPlusPrefix())
6558 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00006559 if (!FS.hasValidSpacePrefix())
6560 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006561 if (!FS.hasValidAlternativeForm())
6562 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6563 if (!FS.hasValidLeftJustified())
6564 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6565
6566 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00006567 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6568 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6569 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006570 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6571 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6572 startSpecifier, specifierLen);
6573
6574 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006575 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006576 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6577 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006578 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006579 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006580 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006581 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6582 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00006583
Jordan Rose92303592012-09-08 04:00:03 +00006584 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6585 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6586
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006587 // The remaining checks depend on the data arguments.
6588 if (HasVAListArg)
6589 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006590
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006591 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006592 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006593
Jordan Rose58bbe422012-07-19 18:10:08 +00006594 const Expr *Arg = getDataArg(argIndex);
6595 if (!Arg)
6596 return true;
6597
6598 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00006599}
6600
Jordan Roseaee34382012-09-05 22:56:26 +00006601static bool requiresParensToAddCast(const Expr *E) {
6602 // FIXME: We should have a general way to reason about operator
6603 // precedence and whether parens are actually needed here.
6604 // Take care of a few common cases where they aren't.
6605 const Expr *Inside = E->IgnoreImpCasts();
6606 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6607 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6608
6609 switch (Inside->getStmtClass()) {
6610 case Stmt::ArraySubscriptExprClass:
6611 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006612 case Stmt::CharacterLiteralClass:
6613 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006614 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006615 case Stmt::FloatingLiteralClass:
6616 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006617 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006618 case Stmt::ObjCArrayLiteralClass:
6619 case Stmt::ObjCBoolLiteralExprClass:
6620 case Stmt::ObjCBoxedExprClass:
6621 case Stmt::ObjCDictionaryLiteralClass:
6622 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006623 case Stmt::ObjCIvarRefExprClass:
6624 case Stmt::ObjCMessageExprClass:
6625 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006626 case Stmt::ObjCStringLiteralClass:
6627 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006628 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006629 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006630 case Stmt::UnaryOperatorClass:
6631 return false;
6632 default:
6633 return true;
6634 }
6635}
6636
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006637static std::pair<QualType, StringRef>
6638shouldNotPrintDirectly(const ASTContext &Context,
6639 QualType IntendedTy,
6640 const Expr *E) {
6641 // Use a 'while' to peel off layers of typedefs.
6642 QualType TyTy = IntendedTy;
6643 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6644 StringRef Name = UserTy->getDecl()->getName();
6645 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Saleem Abdulrasoola01ed932017-10-17 17:39:32 +00006646 .Case("CFIndex", Context.getNSIntegerType())
6647 .Case("NSInteger", Context.getNSIntegerType())
6648 .Case("NSUInteger", Context.getNSUIntegerType())
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006649 .Case("SInt32", Context.IntTy)
6650 .Case("UInt32", Context.UnsignedIntTy)
6651 .Default(QualType());
6652
6653 if (!CastTy.isNull())
6654 return std::make_pair(CastTy, Name);
6655
6656 TyTy = UserTy->desugar();
6657 }
6658
6659 // Strip parens if necessary.
6660 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6661 return shouldNotPrintDirectly(Context,
6662 PE->getSubExpr()->getType(),
6663 PE->getSubExpr());
6664
6665 // If this is a conditional expression, then its result type is constructed
6666 // via usual arithmetic conversions and thus there might be no necessary
6667 // typedef sugar there. Recurse to operands to check for NSInteger &
6668 // Co. usage condition.
6669 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6670 QualType TrueTy, FalseTy;
6671 StringRef TrueName, FalseName;
6672
6673 std::tie(TrueTy, TrueName) =
6674 shouldNotPrintDirectly(Context,
6675 CO->getTrueExpr()->getType(),
6676 CO->getTrueExpr());
6677 std::tie(FalseTy, FalseName) =
6678 shouldNotPrintDirectly(Context,
6679 CO->getFalseExpr()->getType(),
6680 CO->getFalseExpr());
6681
6682 if (TrueTy == FalseTy)
6683 return std::make_pair(TrueTy, TrueName);
6684 else if (TrueTy.isNull())
6685 return std::make_pair(FalseTy, FalseName);
6686 else if (FalseTy.isNull())
6687 return std::make_pair(TrueTy, TrueName);
6688 }
6689
6690 return std::make_pair(QualType(), StringRef());
6691}
6692
Richard Smith55ce3522012-06-25 20:30:08 +00006693bool
6694CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6695 const char *StartSpecifier,
6696 unsigned SpecifierLen,
6697 const Expr *E) {
6698 using namespace analyze_format_string;
6699 using namespace analyze_printf;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006700
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006701 // Now type check the data expression that matches the
6702 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006703 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006704 if (!AT.isValid())
6705 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006706
Jordan Rose598ec092012-12-05 18:44:40 +00006707 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006708 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6709 ExprTy = TET->getUnderlyingExpr()->getType();
6710 }
6711
Seth Cantrellb4802962015-03-04 03:12:10 +00006712 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6713
6714 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006715 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006716 }
Jordan Rose98709982012-06-04 22:48:57 +00006717
Jordan Rose22b74712012-09-05 22:56:19 +00006718 // Look through argument promotions for our error message's reported type.
6719 // This includes the integral and floating promotions, but excludes array
6720 // and function pointer decay; seeing that an argument intended to be a
6721 // string has type 'char [6]' is probably more confusing than 'char *'.
6722 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6723 if (ICE->getCastKind() == CK_IntegralCast ||
6724 ICE->getCastKind() == CK_FloatingCast) {
6725 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006726 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006727
6728 // Check if we didn't match because of an implicit cast from a 'char'
6729 // or 'short' to an 'int'. This is done because printf is a varargs
6730 // function.
6731 if (ICE->getType() == S.Context.IntTy ||
6732 ICE->getType() == S.Context.UnsignedIntTy) {
6733 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006734 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006735 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006736 }
Jordan Rose98709982012-06-04 22:48:57 +00006737 }
Jordan Rose598ec092012-12-05 18:44:40 +00006738 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6739 // Special case for 'a', which has type 'int' in C.
6740 // Note, however, that we do /not/ want to treat multibyte constants like
6741 // 'MooV' as characters! This form is deprecated but still exists.
6742 if (ExprTy == S.Context.IntTy)
6743 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6744 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006745 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006746
Jordan Rosebc53ed12014-05-31 04:12:14 +00006747 // Look through enums to their underlying type.
6748 bool IsEnum = false;
6749 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6750 ExprTy = EnumTy->getDecl()->getIntegerType();
6751 IsEnum = true;
6752 }
6753
Jordan Rose0e5badd2012-12-05 18:44:49 +00006754 // %C in an Objective-C context prints a unichar, not a wchar_t.
6755 // If the argument is an integer of some kind, believe the %C and suggest
6756 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006757 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006758 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006759 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6760 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6761 !ExprTy->isCharType()) {
6762 // 'unichar' is defined as a typedef of unsigned short, but we should
6763 // prefer using the typedef if it is visible.
6764 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006765
6766 // While we are here, check if the value is an IntegerLiteral that happens
6767 // to be within the valid range.
6768 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6769 const llvm::APInt &V = IL->getValue();
6770 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6771 return true;
6772 }
6773
Jordan Rose0e5badd2012-12-05 18:44:49 +00006774 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6775 Sema::LookupOrdinaryName);
6776 if (S.LookupName(Result, S.getCurScope())) {
6777 NamedDecl *ND = Result.getFoundDecl();
6778 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6779 if (TD->getUnderlyingType() == IntendedTy)
6780 IntendedTy = S.Context.getTypedefType(TD);
6781 }
6782 }
6783 }
6784
6785 // Special-case some of Darwin's platform-independence types by suggesting
6786 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006787 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006788 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006789 QualType CastTy;
6790 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6791 if (!CastTy.isNull()) {
6792 IntendedTy = CastTy;
6793 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006794 }
6795 }
6796
Jordan Rose22b74712012-09-05 22:56:19 +00006797 // We may be able to offer a FixItHint if it is a supported type.
6798 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006799 bool success =
6800 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006801
Jordan Rose22b74712012-09-05 22:56:19 +00006802 if (success) {
6803 // Get the fix string from the fixed format specifier
6804 SmallString<16> buf;
6805 llvm::raw_svector_ostream os(buf);
6806 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006807
Jordan Roseaee34382012-09-05 22:56:26 +00006808 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6809
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006810 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006811 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6812 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6813 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6814 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006815 // In this case, the specifier is wrong and should be changed to match
6816 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006817 EmitFormatDiagnostic(S.PDiag(diag)
6818 << AT.getRepresentativeTypeName(S.Context)
6819 << IntendedTy << IsEnum << E->getSourceRange(),
6820 E->getLocStart(),
6821 /*IsStringLocation*/ false, SpecRange,
6822 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006823 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006824 // The canonical type for formatting this value is different from the
6825 // actual type of the expression. (This occurs, for example, with Darwin's
6826 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6827 // should be printed as 'long' for 64-bit compatibility.)
6828 // Rather than emitting a normal format/argument mismatch, we want to
6829 // add a cast to the recommended type (and correct the format string
6830 // if necessary).
6831 SmallString<16> CastBuf;
6832 llvm::raw_svector_ostream CastFix(CastBuf);
6833 CastFix << "(";
6834 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6835 CastFix << ")";
6836
6837 SmallVector<FixItHint,4> Hints;
Alexander Shaposhnikov1788a9b2017-09-22 18:36:06 +00006838 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
Jordan Roseaee34382012-09-05 22:56:26 +00006839 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6840
6841 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6842 // If there's already a cast present, just replace it.
6843 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6844 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6845
6846 } else if (!requiresParensToAddCast(E)) {
6847 // If the expression has high enough precedence,
6848 // just write the C-style cast.
6849 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6850 CastFix.str()));
6851 } else {
6852 // Otherwise, add parens around the expression as well as the cast.
6853 CastFix << "(";
6854 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6855 CastFix.str()));
6856
Alp Tokerb6cc5922014-05-03 03:45:55 +00006857 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006858 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6859 }
6860
Jordan Rose0e5badd2012-12-05 18:44:49 +00006861 if (ShouldNotPrintDirectly) {
6862 // The expression has a type that should not be printed directly.
6863 // We extract the name from the typedef because we don't want to show
6864 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006865 StringRef Name;
6866 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6867 Name = TypedefTy->getDecl()->getName();
6868 else
6869 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006870 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006871 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006872 << E->getSourceRange(),
6873 E->getLocStart(), /*IsStringLocation=*/false,
6874 SpecRange, Hints);
6875 } else {
6876 // In this case, the expression could be printed using a different
6877 // specifier, but we've decided that the specifier is probably correct
6878 // and we should cast instead. Just use the normal warning message.
6879 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006880 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6881 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006882 << E->getSourceRange(),
6883 E->getLocStart(), /*IsStringLocation*/false,
6884 SpecRange, Hints);
6885 }
Jordan Roseaee34382012-09-05 22:56:26 +00006886 }
Jordan Rose22b74712012-09-05 22:56:19 +00006887 } else {
6888 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6889 SpecifierLen);
6890 // Since the warning for passing non-POD types to variadic functions
6891 // was deferred until now, we emit a warning for non-POD
6892 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006893 switch (S.isValidVarArgType(ExprTy)) {
6894 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006895 case Sema::VAK_ValidInCXX11: {
6896 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6897 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6898 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6899 }
Richard Smithd7293d72013-08-05 18:49:43 +00006900
Seth Cantrellb4802962015-03-04 03:12:10 +00006901 EmitFormatDiagnostic(
6902 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6903 << IsEnum << CSR << E->getSourceRange(),
6904 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6905 break;
6906 }
Richard Smithd7293d72013-08-05 18:49:43 +00006907 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006908 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006909 EmitFormatDiagnostic(
6910 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006911 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006912 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006913 << CallType
6914 << AT.getRepresentativeTypeName(S.Context)
6915 << CSR
6916 << E->getSourceRange(),
6917 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006918 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006919 break;
6920
6921 case Sema::VAK_Invalid:
6922 if (ExprTy->isObjCObjectType())
6923 EmitFormatDiagnostic(
6924 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6925 << S.getLangOpts().CPlusPlus11
6926 << ExprTy
6927 << CallType
6928 << AT.getRepresentativeTypeName(S.Context)
6929 << CSR
6930 << E->getSourceRange(),
6931 E->getLocStart(), /*IsStringLocation*/false, CSR);
6932 else
6933 // FIXME: If this is an initializer list, suggest removing the braces
6934 // or inserting a cast to the target type.
6935 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6936 << isa<InitListExpr>(E) << ExprTy << CallType
6937 << AT.getRepresentativeTypeName(S.Context)
6938 << E->getSourceRange();
6939 break;
6940 }
6941
6942 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6943 "format string specifier index out of range");
6944 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006945 }
6946
Ted Kremenekab278de2010-01-28 23:39:18 +00006947 return true;
6948}
6949
Ted Kremenek02087932010-07-16 02:11:22 +00006950//===--- CHECK: Scanf format string checking ------------------------------===//
6951
6952namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006953
Ted Kremenek02087932010-07-16 02:11:22 +00006954class CheckScanfHandler : public CheckFormatHandler {
6955public:
Stephen Hines648c3692016-09-16 01:07:04 +00006956 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006957 const Expr *origFormatExpr, Sema::FormatStringType type,
6958 unsigned firstDataArg, unsigned numDataArgs,
6959 const char *beg, bool hasVAListArg,
6960 ArrayRef<const Expr *> Args, unsigned formatIdx,
6961 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006962 llvm::SmallBitVector &CheckedVarArgs,
6963 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006964 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6965 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6966 inFunctionCall, CallType, CheckedVarArgs,
6967 UncoveredArg) {}
6968
Ted Kremenek02087932010-07-16 02:11:22 +00006969 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6970 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006971 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006972
6973 bool HandleInvalidScanfConversionSpecifier(
6974 const analyze_scanf::ScanfSpecifier &FS,
6975 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006976 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006977
Craig Toppere14c0f82014-03-12 04:55:44 +00006978 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006979};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006980
6981} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006982
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006983void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6984 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006985 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6986 getLocationOfByte(end), /*IsStringLocation*/true,
6987 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006988}
6989
Ted Kremenekce815422010-07-19 21:25:57 +00006990bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6991 const analyze_scanf::ScanfSpecifier &FS,
6992 const char *startSpecifier,
6993 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006994 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006995 FS.getConversionSpecifier();
6996
6997 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6998 getLocationOfByte(CS.getStart()),
6999 startSpecifier, specifierLen,
7000 CS.getStart(), CS.getLength());
7001}
7002
Ted Kremenek02087932010-07-16 02:11:22 +00007003bool CheckScanfHandler::HandleScanfSpecifier(
7004 const analyze_scanf::ScanfSpecifier &FS,
7005 const char *startSpecifier,
7006 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00007007 using namespace analyze_scanf;
7008 using namespace analyze_format_string;
7009
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007010 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00007011
Ted Kremenek6cd69422010-07-19 22:01:06 +00007012 // Handle case where '%' and '*' don't consume an argument. These shouldn't
7013 // be used to decide if we are using positional arguments consistently.
7014 if (FS.consumesDataArgument()) {
7015 if (atFirstArg) {
7016 atFirstArg = false;
7017 usesPositionalArgs = FS.usesPositionalArg();
7018 }
7019 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007020 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7021 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00007022 return false;
7023 }
Ted Kremenek02087932010-07-16 02:11:22 +00007024 }
7025
7026 // Check if the field with is non-zero.
7027 const OptionalAmount &Amt = FS.getFieldWidth();
7028 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
7029 if (Amt.getConstantAmount() == 0) {
7030 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
7031 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00007032 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
7033 getLocationOfByte(Amt.getStart()),
7034 /*IsStringLocation*/true, R,
7035 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00007036 }
7037 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007038
Ted Kremenek02087932010-07-16 02:11:22 +00007039 if (!FS.consumesDataArgument()) {
7040 // FIXME: Technically specifying a precision or field width here
7041 // makes no sense. Worth issuing a warning at some point.
7042 return true;
7043 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007044
Ted Kremenek02087932010-07-16 02:11:22 +00007045 // Consume the argument.
7046 unsigned argIndex = FS.getArgIndex();
7047 if (argIndex < NumDataArgs) {
7048 // The check to see if the argIndex is valid will come later.
7049 // We set the bit here because we may exit early from this
7050 // function if we encounter some other error.
7051 CoveredArgs.set(argIndex);
7052 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007053
Ted Kremenek4407ea42010-07-20 20:04:47 +00007054 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00007055 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00007056 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7057 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00007058 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00007059 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00007060 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00007061 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7062 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007063
Jordan Rose92303592012-09-08 04:00:03 +00007064 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7065 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7066
Ted Kremenek02087932010-07-16 02:11:22 +00007067 // The remaining checks depend on the data arguments.
7068 if (HasVAListArg)
7069 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00007070
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007071 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00007072 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00007073
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007074 // Check that the argument type matches the format specifier.
7075 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00007076 if (!Ex)
7077 return true;
7078
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00007079 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00007080
7081 if (!AT.isValid()) {
7082 return true;
7083 }
7084
Seth Cantrellb4802962015-03-04 03:12:10 +00007085 analyze_format_string::ArgType::MatchKind match =
7086 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00007087 if (match == analyze_format_string::ArgType::Match) {
7088 return true;
7089 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007090
Seth Cantrell79340072015-03-04 05:58:08 +00007091 ScanfSpecifier fixedFS = FS;
7092 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
7093 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007094
Seth Cantrell79340072015-03-04 05:58:08 +00007095 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
7096 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
7097 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
7098 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007099
Seth Cantrell79340072015-03-04 05:58:08 +00007100 if (success) {
7101 // Get the fix string from the fixed format specifier.
7102 SmallString<128> buf;
7103 llvm::raw_svector_ostream os(buf);
7104 fixedFS.toString(os);
7105
7106 EmitFormatDiagnostic(
7107 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
7108 << Ex->getType() << false << Ex->getSourceRange(),
7109 Ex->getLocStart(),
7110 /*IsStringLocation*/ false,
7111 getSpecifierRange(startSpecifier, specifierLen),
7112 FixItHint::CreateReplacement(
7113 getSpecifierRange(startSpecifier, specifierLen), os.str()));
7114 } else {
7115 EmitFormatDiagnostic(S.PDiag(diag)
7116 << AT.getRepresentativeTypeName(S.Context)
7117 << Ex->getType() << false << Ex->getSourceRange(),
7118 Ex->getLocStart(),
7119 /*IsStringLocation*/ false,
7120 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007121 }
7122
Ted Kremenek02087932010-07-16 02:11:22 +00007123 return true;
7124}
7125
Stephen Hines648c3692016-09-16 01:07:04 +00007126static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007127 const Expr *OrigFormatExpr,
7128 ArrayRef<const Expr *> Args,
7129 bool HasVAListArg, unsigned format_idx,
7130 unsigned firstDataArg,
7131 Sema::FormatStringType Type,
7132 bool inFunctionCall,
7133 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007134 llvm::SmallBitVector &CheckedVarArgs,
7135 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00007136 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00007137 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007138 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007139 S, inFunctionCall, Args[format_idx],
7140 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00007141 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00007142 return;
7143 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007144
Ted Kremenekab278de2010-01-28 23:39:18 +00007145 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007146 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00007147 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007148 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007149 const ConstantArrayType *T =
7150 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007151 assert(T && "String literal not of constant array type!");
7152 size_t TypeSize = T->getSize().getZExtValue();
7153 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00007154 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007155
7156 // Emit a warning if the string literal is truncated and does not contain an
7157 // embedded null character.
7158 if (TypeSize <= StrRef.size() &&
7159 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
7160 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007161 S, inFunctionCall, Args[format_idx],
7162 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007163 FExpr->getLocStart(),
7164 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
7165 return;
7166 }
7167
Ted Kremenekab278de2010-01-28 23:39:18 +00007168 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00007169 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007170 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007171 S, inFunctionCall, Args[format_idx],
7172 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00007173 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00007174 return;
7175 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007176
7177 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00007178 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
7179 Type == Sema::FST_OSTrace) {
7180 CheckPrintfHandler H(
7181 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
7182 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
7183 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
7184 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007185
Hans Wennborg23926bd2011-12-15 10:25:47 +00007186 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007187 S.getLangOpts(),
7188 S.Context.getTargetInfo(),
7189 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00007190 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007191 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00007192 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
7193 numDataArgs, Str, HasVAListArg, Args, format_idx,
7194 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007195
Hans Wennborg23926bd2011-12-15 10:25:47 +00007196 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007197 S.getLangOpts(),
7198 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00007199 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00007200 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00007201}
7202
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00007203bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
7204 // Str - The format string. NOTE: this is NOT null-terminated!
7205 StringRef StrRef = FExpr->getString();
7206 const char *Str = StrRef.data();
7207 // Account for cases where the string literal is truncated in a declaration.
7208 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
7209 assert(T && "String literal not of constant array type!");
7210 size_t TypeSize = T->getSize().getZExtValue();
7211 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
7212 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
7213 getLangOpts(),
7214 Context.getTargetInfo());
7215}
7216
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007217//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
7218
7219// Returns the related absolute value function that is larger, of 0 if one
7220// does not exist.
7221static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
7222 switch (AbsFunction) {
7223 default:
7224 return 0;
7225
7226 case Builtin::BI__builtin_abs:
7227 return Builtin::BI__builtin_labs;
7228 case Builtin::BI__builtin_labs:
7229 return Builtin::BI__builtin_llabs;
7230 case Builtin::BI__builtin_llabs:
7231 return 0;
7232
7233 case Builtin::BI__builtin_fabsf:
7234 return Builtin::BI__builtin_fabs;
7235 case Builtin::BI__builtin_fabs:
7236 return Builtin::BI__builtin_fabsl;
7237 case Builtin::BI__builtin_fabsl:
7238 return 0;
7239
7240 case Builtin::BI__builtin_cabsf:
7241 return Builtin::BI__builtin_cabs;
7242 case Builtin::BI__builtin_cabs:
7243 return Builtin::BI__builtin_cabsl;
7244 case Builtin::BI__builtin_cabsl:
7245 return 0;
7246
7247 case Builtin::BIabs:
7248 return Builtin::BIlabs;
7249 case Builtin::BIlabs:
7250 return Builtin::BIllabs;
7251 case Builtin::BIllabs:
7252 return 0;
7253
7254 case Builtin::BIfabsf:
7255 return Builtin::BIfabs;
7256 case Builtin::BIfabs:
7257 return Builtin::BIfabsl;
7258 case Builtin::BIfabsl:
7259 return 0;
7260
7261 case Builtin::BIcabsf:
7262 return Builtin::BIcabs;
7263 case Builtin::BIcabs:
7264 return Builtin::BIcabsl;
7265 case Builtin::BIcabsl:
7266 return 0;
7267 }
7268}
7269
7270// Returns the argument type of the absolute value function.
7271static QualType getAbsoluteValueArgumentType(ASTContext &Context,
7272 unsigned AbsType) {
7273 if (AbsType == 0)
7274 return QualType();
7275
7276 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
7277 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
7278 if (Error != ASTContext::GE_None)
7279 return QualType();
7280
7281 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
7282 if (!FT)
7283 return QualType();
7284
7285 if (FT->getNumParams() != 1)
7286 return QualType();
7287
7288 return FT->getParamType(0);
7289}
7290
7291// Returns the best absolute value function, or zero, based on type and
7292// current absolute value function.
7293static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
7294 unsigned AbsFunctionKind) {
7295 unsigned BestKind = 0;
7296 uint64_t ArgSize = Context.getTypeSize(ArgType);
7297 for (unsigned Kind = AbsFunctionKind; Kind != 0;
7298 Kind = getLargerAbsoluteValueFunction(Kind)) {
7299 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
7300 if (Context.getTypeSize(ParamType) >= ArgSize) {
7301 if (BestKind == 0)
7302 BestKind = Kind;
7303 else if (Context.hasSameType(ParamType, ArgType)) {
7304 BestKind = Kind;
7305 break;
7306 }
7307 }
7308 }
7309 return BestKind;
7310}
7311
7312enum AbsoluteValueKind {
7313 AVK_Integer,
7314 AVK_Floating,
7315 AVK_Complex
7316};
7317
7318static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
7319 if (T->isIntegralOrEnumerationType())
7320 return AVK_Integer;
7321 if (T->isRealFloatingType())
7322 return AVK_Floating;
7323 if (T->isAnyComplexType())
7324 return AVK_Complex;
7325
7326 llvm_unreachable("Type not integer, floating, or complex");
7327}
7328
7329// Changes the absolute value function to a different type. Preserves whether
7330// the function is a builtin.
7331static unsigned changeAbsFunction(unsigned AbsKind,
7332 AbsoluteValueKind ValueKind) {
7333 switch (ValueKind) {
7334 case AVK_Integer:
7335 switch (AbsKind) {
7336 default:
7337 return 0;
7338 case Builtin::BI__builtin_fabsf:
7339 case Builtin::BI__builtin_fabs:
7340 case Builtin::BI__builtin_fabsl:
7341 case Builtin::BI__builtin_cabsf:
7342 case Builtin::BI__builtin_cabs:
7343 case Builtin::BI__builtin_cabsl:
7344 return Builtin::BI__builtin_abs;
7345 case Builtin::BIfabsf:
7346 case Builtin::BIfabs:
7347 case Builtin::BIfabsl:
7348 case Builtin::BIcabsf:
7349 case Builtin::BIcabs:
7350 case Builtin::BIcabsl:
7351 return Builtin::BIabs;
7352 }
7353 case AVK_Floating:
7354 switch (AbsKind) {
7355 default:
7356 return 0;
7357 case Builtin::BI__builtin_abs:
7358 case Builtin::BI__builtin_labs:
7359 case Builtin::BI__builtin_llabs:
7360 case Builtin::BI__builtin_cabsf:
7361 case Builtin::BI__builtin_cabs:
7362 case Builtin::BI__builtin_cabsl:
7363 return Builtin::BI__builtin_fabsf;
7364 case Builtin::BIabs:
7365 case Builtin::BIlabs:
7366 case Builtin::BIllabs:
7367 case Builtin::BIcabsf:
7368 case Builtin::BIcabs:
7369 case Builtin::BIcabsl:
7370 return Builtin::BIfabsf;
7371 }
7372 case AVK_Complex:
7373 switch (AbsKind) {
7374 default:
7375 return 0;
7376 case Builtin::BI__builtin_abs:
7377 case Builtin::BI__builtin_labs:
7378 case Builtin::BI__builtin_llabs:
7379 case Builtin::BI__builtin_fabsf:
7380 case Builtin::BI__builtin_fabs:
7381 case Builtin::BI__builtin_fabsl:
7382 return Builtin::BI__builtin_cabsf;
7383 case Builtin::BIabs:
7384 case Builtin::BIlabs:
7385 case Builtin::BIllabs:
7386 case Builtin::BIfabsf:
7387 case Builtin::BIfabs:
7388 case Builtin::BIfabsl:
7389 return Builtin::BIcabsf;
7390 }
7391 }
7392 llvm_unreachable("Unable to convert function");
7393}
7394
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00007395static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007396 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
7397 if (!FnInfo)
7398 return 0;
7399
7400 switch (FDecl->getBuiltinID()) {
7401 default:
7402 return 0;
7403 case Builtin::BI__builtin_abs:
7404 case Builtin::BI__builtin_fabs:
7405 case Builtin::BI__builtin_fabsf:
7406 case Builtin::BI__builtin_fabsl:
7407 case Builtin::BI__builtin_labs:
7408 case Builtin::BI__builtin_llabs:
7409 case Builtin::BI__builtin_cabs:
7410 case Builtin::BI__builtin_cabsf:
7411 case Builtin::BI__builtin_cabsl:
7412 case Builtin::BIabs:
7413 case Builtin::BIlabs:
7414 case Builtin::BIllabs:
7415 case Builtin::BIfabs:
7416 case Builtin::BIfabsf:
7417 case Builtin::BIfabsl:
7418 case Builtin::BIcabs:
7419 case Builtin::BIcabsf:
7420 case Builtin::BIcabsl:
7421 return FDecl->getBuiltinID();
7422 }
7423 llvm_unreachable("Unknown Builtin type");
7424}
7425
7426// If the replacement is valid, emit a note with replacement function.
7427// Additionally, suggest including the proper header if not already included.
7428static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00007429 unsigned AbsKind, QualType ArgType) {
7430 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007431 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00007432 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007433 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7434 FunctionName = "std::abs";
7435 if (ArgType->isIntegralOrEnumerationType()) {
7436 HeaderName = "cstdlib";
7437 } else if (ArgType->isRealFloatingType()) {
7438 HeaderName = "cmath";
7439 } else {
7440 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007441 }
Richard Trieubeffb832014-04-15 23:47:53 +00007442
7443 // Lookup all std::abs
7444 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00007445 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00007446 R.suppressDiagnostics();
7447 S.LookupQualifiedName(R, Std);
7448
7449 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007450 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007451 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7452 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7453 } else {
7454 FDecl = dyn_cast<FunctionDecl>(I);
7455 }
7456 if (!FDecl)
7457 continue;
7458
7459 // Found std::abs(), check that they are the right ones.
7460 if (FDecl->getNumParams() != 1)
7461 continue;
7462
7463 // Check that the parameter type can handle the argument.
7464 QualType ParamType = FDecl->getParamDecl(0)->getType();
7465 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7466 S.Context.getTypeSize(ArgType) <=
7467 S.Context.getTypeSize(ParamType)) {
7468 // Found a function, don't need the header hint.
7469 EmitHeaderHint = false;
7470 break;
7471 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007472 }
Richard Trieubeffb832014-04-15 23:47:53 +00007473 }
7474 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00007475 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00007476 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7477
7478 if (HeaderName) {
7479 DeclarationName DN(&S.Context.Idents.get(FunctionName));
7480 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7481 R.suppressDiagnostics();
7482 S.LookupName(R, S.getCurScope());
7483
7484 if (R.isSingleResult()) {
7485 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7486 if (FD && FD->getBuiltinID() == AbsKind) {
7487 EmitHeaderHint = false;
7488 } else {
7489 return;
7490 }
7491 } else if (!R.empty()) {
7492 return;
7493 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007494 }
7495 }
7496
7497 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00007498 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007499
Richard Trieubeffb832014-04-15 23:47:53 +00007500 if (!HeaderName)
7501 return;
7502
7503 if (!EmitHeaderHint)
7504 return;
7505
Alp Toker5d96e0a2014-07-11 20:53:51 +00007506 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7507 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00007508}
7509
Richard Trieua7f30b12016-12-06 01:42:28 +00007510template <std::size_t StrLen>
7511static bool IsStdFunction(const FunctionDecl *FDecl,
7512 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00007513 if (!FDecl)
7514 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007515 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00007516 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007517 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00007518 return false;
7519
7520 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007521}
7522
7523// Warn when using the wrong abs() function.
7524void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00007525 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007526 if (Call->getNumArgs() != 1)
7527 return;
7528
7529 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00007530 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00007531 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007532 return;
7533
7534 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7535 QualType ParamType = Call->getArg(0)->getType();
7536
Alp Toker5d96e0a2014-07-11 20:53:51 +00007537 // Unsigned types cannot be negative. Suggest removing the absolute value
7538 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007539 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00007540 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00007541 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007542 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7543 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00007544 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007545 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7546 return;
7547 }
7548
David Majnemer7f77eb92015-11-15 03:04:34 +00007549 // Taking the absolute value of a pointer is very suspicious, they probably
7550 // wanted to index into an array, dereference a pointer, call a function, etc.
7551 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7552 unsigned DiagType = 0;
7553 if (ArgType->isFunctionType())
7554 DiagType = 1;
7555 else if (ArgType->isArrayType())
7556 DiagType = 2;
7557
7558 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7559 return;
7560 }
7561
Richard Trieubeffb832014-04-15 23:47:53 +00007562 // std::abs has overloads which prevent most of the absolute value problems
7563 // from occurring.
7564 if (IsStdAbs)
7565 return;
7566
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007567 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7568 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7569
7570 // The argument and parameter are the same kind. Check if they are the right
7571 // size.
7572 if (ArgValueKind == ParamValueKind) {
7573 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7574 return;
7575
7576 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7577 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7578 << FDecl << ArgType << ParamType;
7579
7580 if (NewAbsKind == 0)
7581 return;
7582
7583 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007584 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007585 return;
7586 }
7587
7588 // ArgValueKind != ParamValueKind
7589 // The wrong type of absolute value function was used. Attempt to find the
7590 // proper one.
7591 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7592 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7593 if (NewAbsKind == 0)
7594 return;
7595
7596 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7597 << FDecl << ParamValueKind << ArgValueKind;
7598
7599 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007600 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007601}
7602
Richard Trieu67c00712016-12-05 23:41:46 +00007603//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00007604void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7605 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00007606 if (!Call || !FDecl) return;
7607
7608 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00007609 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007610 if (Call->getExprLoc().isMacroID()) return;
7611
7612 // Only care about the one template argument, two function parameter std::max
7613 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00007614 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007615 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7616 if (!ArgList) return;
7617 if (ArgList->size() != 1) return;
7618
7619 // Check that template type argument is unsigned integer.
7620 const auto& TA = ArgList->get(0);
7621 if (TA.getKind() != TemplateArgument::Type) return;
7622 QualType ArgType = TA.getAsType();
7623 if (!ArgType->isUnsignedIntegerType()) return;
7624
7625 // See if either argument is a literal zero.
7626 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7627 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7628 if (!MTE) return false;
7629 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7630 if (!Num) return false;
7631 if (Num->getValue() != 0) return false;
7632 return true;
7633 };
7634
7635 const Expr *FirstArg = Call->getArg(0);
7636 const Expr *SecondArg = Call->getArg(1);
7637 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7638 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7639
7640 // Only warn when exactly one argument is zero.
7641 if (IsFirstArgZero == IsSecondArgZero) return;
7642
7643 SourceRange FirstRange = FirstArg->getSourceRange();
7644 SourceRange SecondRange = SecondArg->getSourceRange();
7645
7646 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7647
7648 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7649 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7650
7651 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7652 SourceRange RemovalRange;
7653 if (IsFirstArgZero) {
7654 RemovalRange = SourceRange(FirstRange.getBegin(),
7655 SecondRange.getBegin().getLocWithOffset(-1));
7656 } else {
7657 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7658 SecondRange.getEnd());
7659 }
7660
7661 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7662 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7663 << FixItHint::CreateRemoval(RemovalRange);
7664}
7665
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007666//===--- CHECK: Standard memory functions ---------------------------------===//
7667
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007668/// Takes the expression passed to the size_t parameter of functions
Nico Weber0e6daef2013-12-26 23:38:39 +00007669/// such as memcmp, strncat, etc and warns if it's a comparison.
7670///
7671/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7672static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7673 IdentifierInfo *FnName,
7674 SourceLocation FnLoc,
7675 SourceLocation RParenLoc) {
7676 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7677 if (!Size)
7678 return false;
7679
Richard Smithc70f1d62017-12-14 15:16:18 +00007680 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
7681 if (!Size->isComparisonOp() && !Size->isLogicalOp())
Nico Weber0e6daef2013-12-26 23:38:39 +00007682 return false;
7683
Nico Weber0e6daef2013-12-26 23:38:39 +00007684 SourceRange SizeRange = Size->getSourceRange();
7685 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7686 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007687 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007688 << FnName << FixItHint::CreateInsertion(
7689 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007690 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007691 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007692 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007693 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7694 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007695
7696 return true;
7697}
7698
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007699/// Determine whether the given type is or contains a dynamic class type
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007700/// (e.g., whether it has a vtable).
7701static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7702 bool &IsContained) {
7703 // Look through array types while ignoring qualifiers.
7704 const Type *Ty = T->getBaseElementTypeUnsafe();
7705 IsContained = false;
7706
7707 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7708 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007709 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007710 return nullptr;
7711
7712 if (RD->isDynamicClass())
7713 return RD;
7714
7715 // Check all the fields. If any bases were dynamic, the class is dynamic.
7716 // It's impossible for a class to transitively contain itself by value, so
7717 // infinite recursion is impossible.
7718 for (auto *FD : RD->fields()) {
7719 bool SubContained;
7720 if (const CXXRecordDecl *ContainedRD =
7721 getContainedDynamicClass(FD->getType(), SubContained)) {
7722 IsContained = true;
7723 return ContainedRD;
7724 }
7725 }
7726
7727 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007728}
7729
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007730/// If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007731/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007732static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007733 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007734 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007735 if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007736 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007737
Craig Topperc3ec1492014-05-26 06:22:03 +00007738 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007739}
7740
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007741/// If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007742static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007743 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7744 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007745 if (SizeOf->getKind() == UETT_SizeOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007746 return SizeOf->getTypeOfArgument();
7747
7748 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007749}
7750
Akira Hatanaka2be04412018-04-17 19:13:41 +00007751namespace {
7752
7753struct SearchNonTrivialToInitializeField
7754 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
7755 using Super =
7756 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
7757
7758 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
7759
7760 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
7761 SourceLocation SL) {
7762 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7763 asDerived().visitArray(PDIK, AT, SL);
7764 return;
7765 }
7766
7767 Super::visitWithKind(PDIK, FT, SL);
7768 }
7769
7770 void visitARCStrong(QualType FT, SourceLocation SL) {
7771 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7772 }
7773 void visitARCWeak(QualType FT, SourceLocation SL) {
7774 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7775 }
7776 void visitStruct(QualType FT, SourceLocation SL) {
7777 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7778 visit(FD->getType(), FD->getLocation());
7779 }
7780 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
7781 const ArrayType *AT, SourceLocation SL) {
7782 visit(getContext().getBaseElementType(AT), SL);
7783 }
7784 void visitTrivial(QualType FT, SourceLocation SL) {}
7785
7786 static void diag(QualType RT, const Expr *E, Sema &S) {
7787 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
7788 }
7789
7790 ASTContext &getContext() { return S.getASTContext(); }
7791
7792 const Expr *E;
7793 Sema &S;
7794};
7795
7796struct SearchNonTrivialToCopyField
7797 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
7798 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
7799
7800 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
7801
7802 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
7803 SourceLocation SL) {
7804 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7805 asDerived().visitArray(PCK, AT, SL);
7806 return;
7807 }
7808
7809 Super::visitWithKind(PCK, FT, SL);
7810 }
7811
7812 void visitARCStrong(QualType FT, SourceLocation SL) {
7813 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7814 }
7815 void visitARCWeak(QualType FT, SourceLocation SL) {
7816 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7817 }
7818 void visitStruct(QualType FT, SourceLocation SL) {
7819 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7820 visit(FD->getType(), FD->getLocation());
7821 }
7822 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
7823 SourceLocation SL) {
7824 visit(getContext().getBaseElementType(AT), SL);
7825 }
7826 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
7827 SourceLocation SL) {}
7828 void visitTrivial(QualType FT, SourceLocation SL) {}
7829 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
7830
7831 static void diag(QualType RT, const Expr *E, Sema &S) {
7832 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
7833 }
7834
7835 ASTContext &getContext() { return S.getASTContext(); }
7836
7837 const Expr *E;
7838 Sema &S;
7839};
7840
7841}
7842
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007843/// Check for dangerous or invalid arguments to memset().
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007844///
Chandler Carruthac687262011-06-03 06:23:57 +00007845/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007846/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7847/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007848///
7849/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007850void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007851 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007852 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007853 assert(BId != 0);
7854
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007855 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007856 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007857 unsigned ExpectedNumArgs =
7858 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007859 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007860 return;
7861
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007862 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007863 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007864 unsigned LenArg =
7865 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007866 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007867
Nico Weber0e6daef2013-12-26 23:38:39 +00007868 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7869 Call->getLocStart(), Call->getRParenLoc()))
7870 return;
7871
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007872 // We have special checking when the length is a sizeof expression.
7873 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7874 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7875 llvm::FoldingSetNodeID SizeOfArgID;
7876
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007877 // Although widely used, 'bzero' is not a standard function. Be more strict
7878 // with the argument types before allowing diagnostics and only allow the
7879 // form bzero(ptr, sizeof(...)).
7880 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7881 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7882 return;
7883
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007884 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7885 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007886 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007887
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007888 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007889 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007890 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007891 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007892
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007893 // Never warn about void type pointers. This can be used to suppress
7894 // false positives.
7895 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007896 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007897
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007898 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7899 // actually comparing the expressions for equality. Because computing the
7900 // expression IDs can be expensive, we only do this if the diagnostic is
7901 // enabled.
7902 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007903 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7904 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007905 // We only compute IDs for expressions if the warning is enabled, and
7906 // cache the sizeof arg's ID.
7907 if (SizeOfArgID == llvm::FoldingSetNodeID())
7908 SizeOfArg->Profile(SizeOfArgID, Context, true);
7909 llvm::FoldingSetNodeID DestID;
7910 Dest->Profile(DestID, Context, true);
7911 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007912 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7913 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007914 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007915 StringRef ReadableName = FnName->getName();
7916
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007917 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007918 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007919 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007920 if (!PointeeTy->isIncompleteType() &&
7921 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007922 ActionIdx = 2; // If the pointee's size is sizeof(char),
7923 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007924
7925 // If the function is defined as a builtin macro, do not show macro
7926 // expansion.
7927 SourceLocation SL = SizeOfArg->getExprLoc();
7928 SourceRange DSR = Dest->getSourceRange();
7929 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007930 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007931
7932 if (SM.isMacroArgExpansion(SL)) {
7933 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7934 SL = SM.getSpellingLoc(SL);
7935 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7936 SM.getSpellingLoc(DSR.getEnd()));
7937 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7938 SM.getSpellingLoc(SSR.getEnd()));
7939 }
7940
Anna Zaksd08d9152012-05-30 23:14:52 +00007941 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007942 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007943 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007944 << PointeeTy
7945 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007946 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007947 << SSR);
7948 DiagRuntimeBehavior(SL, SizeOfArg,
7949 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7950 << ActionIdx
7951 << SSR);
7952
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007953 break;
7954 }
7955 }
7956
7957 // Also check for cases where the sizeof argument is the exact same
7958 // type as the memory argument, and where it points to a user-defined
7959 // record type.
7960 if (SizeOfArgTy != QualType()) {
7961 if (PointeeTy->isRecordType() &&
7962 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7963 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7964 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7965 << FnName << SizeOfArgTy << ArgIdx
7966 << PointeeTy << Dest->getSourceRange()
7967 << LenExpr->getSourceRange());
7968 break;
7969 }
Nico Weberc5e73862011-06-14 16:14:58 +00007970 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007971 } else if (DestTy->isArrayType()) {
7972 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007973 }
Nico Weberc5e73862011-06-14 16:14:58 +00007974
Nico Weberc44b35e2015-03-21 17:37:46 +00007975 if (PointeeTy == QualType())
7976 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007977
Nico Weberc44b35e2015-03-21 17:37:46 +00007978 // Always complain about dynamic classes.
7979 bool IsContained;
7980 if (const CXXRecordDecl *ContainedRD =
7981 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007982
Nico Weberc44b35e2015-03-21 17:37:46 +00007983 unsigned OperationType = 0;
7984 // "overwritten" if we're warning about the destination for any call
7985 // but memcmp; otherwise a verb appropriate to the call.
7986 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7987 if (BId == Builtin::BImemcpy)
7988 OperationType = 1;
7989 else if(BId == Builtin::BImemmove)
7990 OperationType = 2;
7991 else if (BId == Builtin::BImemcmp)
7992 OperationType = 3;
7993 }
7994
John McCall31168b02011-06-15 23:02:42 +00007995 DiagRuntimeBehavior(
7996 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007997 PDiag(diag::warn_dyn_class_memaccess)
7998 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7999 << FnName << IsContained << ContainedRD << OperationType
8000 << Call->getCallee()->getSourceRange());
8001 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
8002 BId != Builtin::BImemset)
8003 DiagRuntimeBehavior(
8004 Dest->getExprLoc(), Dest,
8005 PDiag(diag::warn_arc_object_memaccess)
8006 << ArgIdx << FnName << PointeeTy
8007 << Call->getCallee()->getSourceRange());
Akira Hatanaka2be04412018-04-17 19:13:41 +00008008 else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
8009 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
8010 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
8011 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
8012 PDiag(diag::warn_cstruct_memaccess)
8013 << ArgIdx << FnName << PointeeTy << 0);
8014 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
8015 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
8016 RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
8017 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
8018 PDiag(diag::warn_cstruct_memaccess)
8019 << ArgIdx << FnName << PointeeTy << 1);
8020 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
8021 } else {
8022 continue;
8023 }
8024 } else
Nico Weberc44b35e2015-03-21 17:37:46 +00008025 continue;
8026
8027 DiagRuntimeBehavior(
8028 Dest->getExprLoc(), Dest,
8029 PDiag(diag::note_bad_memaccess_silence)
8030 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
8031 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00008032 }
8033}
8034
Ted Kremenek6865f772011-08-18 20:55:45 +00008035// A little helper routine: ignore addition and subtraction of integer literals.
8036// This intentionally does not ignore all integer constant expressions because
8037// we don't want to remove sizeof().
8038static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
8039 Ex = Ex->IgnoreParenCasts();
8040
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008041 while (true) {
Ted Kremenek6865f772011-08-18 20:55:45 +00008042 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
8043 if (!BO || !BO->isAdditiveOp())
8044 break;
8045
8046 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
8047 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
8048
8049 if (isa<IntegerLiteral>(RHS))
8050 Ex = LHS;
8051 else if (isa<IntegerLiteral>(LHS))
8052 Ex = RHS;
8053 else
8054 break;
8055 }
8056
8057 return Ex;
8058}
8059
Anna Zaks13b08572012-08-08 21:42:23 +00008060static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
8061 ASTContext &Context) {
8062 // Only handle constant-sized or VLAs, but not flexible members.
8063 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
8064 // Only issue the FIXIT for arrays of size > 1.
8065 if (CAT->getSize().getSExtValue() <= 1)
8066 return false;
8067 } else if (!Ty->isVariableArrayType()) {
8068 return false;
8069 }
8070 return true;
8071}
8072
Ted Kremenek6865f772011-08-18 20:55:45 +00008073// Warn if the user has made the 'size' argument to strlcpy or strlcat
8074// be the size of the source, instead of the destination.
8075void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
8076 IdentifierInfo *FnName) {
8077
8078 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00008079 unsigned NumArgs = Call->getNumArgs();
8080 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00008081 return;
8082
8083 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
8084 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00008085 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00008086
8087 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
8088 Call->getLocStart(), Call->getRParenLoc()))
8089 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00008090
8091 // Look for 'strlcpy(dst, x, sizeof(x))'
8092 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
8093 CompareWithSrc = Ex;
8094 else {
8095 // Look for 'strlcpy(dst, x, strlen(x))'
8096 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00008097 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
8098 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00008099 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
8100 }
8101 }
8102
8103 if (!CompareWithSrc)
8104 return;
8105
8106 // Determine if the argument to sizeof/strlen is equal to the source
8107 // argument. In principle there's all kinds of things you could do
8108 // here, for instance creating an == expression and evaluating it with
8109 // EvaluateAsBooleanCondition, but this uses a more direct technique:
8110 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
8111 if (!SrcArgDRE)
8112 return;
8113
8114 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
8115 if (!CompareWithSrcDRE ||
8116 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
8117 return;
8118
8119 const Expr *OriginalSizeArg = Call->getArg(2);
8120 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
8121 << OriginalSizeArg->getSourceRange() << FnName;
8122
8123 // Output a FIXIT hint if the destination is an array (rather than a
8124 // pointer to an array). This could be enhanced to handle some
8125 // pointers if we know the actual size, like if DstArg is 'array+2'
8126 // we could say 'sizeof(array)-2'.
8127 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00008128 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00008129 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00008130
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008131 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00008132 llvm::raw_svector_ostream OS(sizeString);
8133 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008134 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00008135 OS << ")";
8136
8137 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
8138 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
8139 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00008140}
8141
Anna Zaks314cd092012-02-01 19:08:57 +00008142/// Check if two expressions refer to the same declaration.
8143static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
8144 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
8145 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
8146 return D1->getDecl() == D2->getDecl();
8147 return false;
8148}
8149
8150static const Expr *getStrlenExprArg(const Expr *E) {
8151 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8152 const FunctionDecl *FD = CE->getDirectCallee();
8153 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00008154 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00008155 return CE->getArg(0)->IgnoreParenCasts();
8156 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008157 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00008158}
8159
8160// Warn on anti-patterns as the 'size' argument to strncat.
8161// The correct size argument should look like following:
8162// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
8163void Sema::CheckStrncatArguments(const CallExpr *CE,
8164 IdentifierInfo *FnName) {
8165 // Don't crash if the user has the wrong number of arguments.
8166 if (CE->getNumArgs() < 3)
8167 return;
8168 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
8169 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
8170 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
8171
Nico Weber0e6daef2013-12-26 23:38:39 +00008172 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
8173 CE->getRParenLoc()))
8174 return;
8175
Anna Zaks314cd092012-02-01 19:08:57 +00008176 // Identify common expressions, which are wrongly used as the size argument
8177 // to strncat and may lead to buffer overflows.
8178 unsigned PatternType = 0;
8179 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
8180 // - sizeof(dst)
8181 if (referToTheSameDecl(SizeOfArg, DstArg))
8182 PatternType = 1;
8183 // - sizeof(src)
8184 else if (referToTheSameDecl(SizeOfArg, SrcArg))
8185 PatternType = 2;
8186 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
8187 if (BE->getOpcode() == BO_Sub) {
8188 const Expr *L = BE->getLHS()->IgnoreParenCasts();
8189 const Expr *R = BE->getRHS()->IgnoreParenCasts();
8190 // - sizeof(dst) - strlen(dst)
8191 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
8192 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
8193 PatternType = 1;
8194 // - sizeof(src) - (anything)
8195 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
8196 PatternType = 2;
8197 }
8198 }
8199
8200 if (PatternType == 0)
8201 return;
8202
Anna Zaks5069aa32012-02-03 01:27:37 +00008203 // Generate the diagnostic.
8204 SourceLocation SL = LenArg->getLocStart();
8205 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00008206 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00008207
8208 // If the function is defined as a builtin macro, do not show macro expansion.
8209 if (SM.isMacroArgExpansion(SL)) {
8210 SL = SM.getSpellingLoc(SL);
8211 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
8212 SM.getSpellingLoc(SR.getEnd()));
8213 }
8214
Anna Zaks13b08572012-08-08 21:42:23 +00008215 // Check if the destination is an array (rather than a pointer to an array).
8216 QualType DstTy = DstArg->getType();
8217 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
8218 Context);
8219 if (!isKnownSizeArray) {
8220 if (PatternType == 1)
8221 Diag(SL, diag::warn_strncat_wrong_size) << SR;
8222 else
8223 Diag(SL, diag::warn_strncat_src_size) << SR;
8224 return;
8225 }
8226
Anna Zaks314cd092012-02-01 19:08:57 +00008227 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00008228 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00008229 else
Anna Zaks5069aa32012-02-03 01:27:37 +00008230 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00008231
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008232 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00008233 llvm::raw_svector_ostream OS(sizeString);
8234 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008235 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00008236 OS << ") - ";
8237 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008238 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00008239 OS << ") - 1";
8240
Anna Zaks5069aa32012-02-03 01:27:37 +00008241 Diag(SL, diag::note_strncat_wrong_size)
8242 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00008243}
8244
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008245//===--- CHECK: Return Address of Stack Variable --------------------------===//
8246
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008247static const Expr *EvalVal(const Expr *E,
8248 SmallVectorImpl<const DeclRefExpr *> &refVars,
8249 const Decl *ParentDecl);
8250static const Expr *EvalAddr(const Expr *E,
8251 SmallVectorImpl<const DeclRefExpr *> &refVars,
8252 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008253
8254/// CheckReturnStackAddr - Check if a return statement returns the address
8255/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008256static void
8257CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
8258 SourceLocation ReturnLoc) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008259 const Expr *stackE = nullptr;
8260 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008261
8262 // Perform checking for returned stack addresses, local blocks,
8263 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00008264 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008265 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008266 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00008267 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008268 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008269 }
8270
Craig Topperc3ec1492014-05-26 06:22:03 +00008271 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008272 return; // Nothing suspicious was found.
8273
Simon Pilgrim750bde62017-03-31 11:00:53 +00008274 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00008275 // of a parameter reference doesn't need a warning.
8276 for (auto *DRE : refVars)
8277 if (isa<ParmVarDecl>(DRE->getDecl()))
8278 return;
8279
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008280 SourceLocation diagLoc;
8281 SourceRange diagRange;
8282 if (refVars.empty()) {
8283 diagLoc = stackE->getLocStart();
8284 diagRange = stackE->getSourceRange();
8285 } else {
8286 // We followed through a reference variable. 'stackE' contains the
8287 // problematic expression but we will warn at the return statement pointing
8288 // at the reference variable. We will later display the "trail" of
8289 // reference variables using notes.
8290 diagLoc = refVars[0]->getLocStart();
8291 diagRange = refVars[0]->getSourceRange();
8292 }
8293
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008294 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
8295 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00008296 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008297 << DR->getDecl()->getDeclName() << diagRange;
8298 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008299 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008300 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008301 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008302 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00008303 // If there is an LValue->RValue conversion, then the value of the
8304 // reference type is used, not the reference.
8305 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
8306 if (ICE->getCastKind() == CK_LValueToRValue) {
8307 return;
8308 }
8309 }
Craig Topperda7b27f2015-11-17 05:40:09 +00008310 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
8311 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008312 }
8313
8314 // Display the "trail" of reference variables that we followed until we
8315 // found the problematic expression using notes.
8316 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008317 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008318 // If this var binds to another reference var, show the range of the next
8319 // var, otherwise the var binds to the problematic expression, in which case
8320 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008321 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
8322 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008323 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
8324 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008325 }
8326}
8327
8328/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
8329/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008330/// to a location on the stack, a local block, an address of a label, or a
8331/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008332/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008333/// encounter a subexpression that (1) clearly does not lead to one of the
8334/// above problematic expressions (2) is something we cannot determine leads to
8335/// a problematic expression based on such local checking.
8336///
8337/// Both EvalAddr and EvalVal follow through reference variables to evaluate
8338/// the expression that they point to. Such variables are added to the
8339/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008340///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00008341/// EvalAddr processes expressions that are pointers that are used as
8342/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008343/// At the base case of the recursion is a check for the above problematic
8344/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008345///
8346/// This implementation handles:
8347///
8348/// * pointer-to-pointer casts
8349/// * implicit conversions from array references to pointers
8350/// * taking the address of fields
8351/// * arbitrary interplay between "&" and "*" operators
8352/// * pointer arithmetic from an address of a stack variable
8353/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008354static const Expr *EvalAddr(const Expr *E,
8355 SmallVectorImpl<const DeclRefExpr *> &refVars,
8356 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008357 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00008358 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008359
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008360 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00008361 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00008362 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00008363 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00008364 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00008365
Peter Collingbourne91147592011-04-15 00:35:48 +00008366 E = E->IgnoreParens();
8367
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008368 // Our "symbolic interpreter" is just a dispatch off the currently
8369 // viewed AST node. We then recursively traverse the AST by calling
8370 // EvalAddr and EvalVal appropriately.
8371 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008372 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008373 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008374
Richard Smith40f08eb2014-01-30 22:05:38 +00008375 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00008376 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00008377 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00008378
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008379 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008380 // If this is a reference variable, follow through to the expression that
8381 // it points to.
8382 if (V->hasLocalStorage() &&
8383 V->getType()->isReferenceType() && V->hasInit()) {
8384 // Add the reference variable to the "trail".
8385 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008386 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008387 }
8388
Craig Topperc3ec1492014-05-26 06:22:03 +00008389 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008390 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008391
Chris Lattner934edb22007-12-28 05:31:15 +00008392 case Stmt::UnaryOperatorClass: {
8393 // The only unary operator that make sense to handle here
8394 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008395 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008396
John McCalle3027922010-08-25 11:45:40 +00008397 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008398 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008399 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008400 }
Mike Stump11289f42009-09-09 15:08:12 +00008401
Chris Lattner934edb22007-12-28 05:31:15 +00008402 case Stmt::BinaryOperatorClass: {
8403 // Handle pointer arithmetic. All other binary operators are not valid
8404 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008405 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00008406 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00008407
John McCalle3027922010-08-25 11:45:40 +00008408 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00008409 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008410
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008411 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00008412
8413 // Determine which argument is the real pointer base. It could be
8414 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008415 if (!Base->getType()->isPointerType())
8416 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00008417
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008418 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008419 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00008420 }
Steve Naroff2752a172008-09-10 19:17:48 +00008421
Chris Lattner934edb22007-12-28 05:31:15 +00008422 // For conditional operators we need to see if either the LHS or RHS are
8423 // valid DeclRefExpr*s. If one of them is valid, we return it.
8424 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008425 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008426
Chris Lattner934edb22007-12-28 05:31:15 +00008427 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008428 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008429 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008430 // In C++, we can have a throw-expression, which has 'void' type.
8431 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008432 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008433 return LHS;
8434 }
Chris Lattner934edb22007-12-28 05:31:15 +00008435
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008436 // In C++, we can have a throw-expression, which has 'void' type.
8437 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00008438 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008439
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008440 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00008441 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008442
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008443 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00008444 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008445 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00008446 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008447
8448 case Stmt::AddrLabelExprClass:
8449 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00008450
John McCall28fc7092011-11-10 05:35:25 +00008451 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008452 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8453 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00008454
Ted Kremenekc3b4c522008-08-07 00:49:01 +00008455 // For casts, we need to handle conversions from arrays to
8456 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00008457 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00008458 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008459 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00008460 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00008461 case Stmt::CXXStaticCastExprClass:
8462 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00008463 case Stmt::CXXConstCastExprClass:
8464 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008465 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00008466 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00008467 case CK_LValueToRValue:
8468 case CK_NoOp:
8469 case CK_BaseToDerived:
8470 case CK_DerivedToBase:
8471 case CK_UncheckedDerivedToBase:
8472 case CK_Dynamic:
8473 case CK_CPointerToObjCPointerCast:
8474 case CK_BlockPointerToObjCPointerCast:
8475 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008476 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00008477
8478 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008479 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00008480
Richard Trieudadefde2014-07-02 04:39:38 +00008481 case CK_BitCast:
8482 if (SubExpr->getType()->isAnyPointerType() ||
8483 SubExpr->getType()->isBlockPointerType() ||
8484 SubExpr->getType()->isObjCQualifiedIdType())
8485 return EvalAddr(SubExpr, refVars, ParentDecl);
8486 else
8487 return nullptr;
8488
Eli Friedman8195ad72012-02-23 23:04:32 +00008489 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00008490 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00008491 }
Chris Lattner934edb22007-12-28 05:31:15 +00008492 }
Mike Stump11289f42009-09-09 15:08:12 +00008493
Douglas Gregorfe314812011-06-21 17:03:29 +00008494 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008495 if (const Expr *Result =
8496 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8497 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00008498 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00008499 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008500
Chris Lattner934edb22007-12-28 05:31:15 +00008501 // Everything else: we simply don't reason about them.
8502 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00008503 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00008504 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008505}
Mike Stump11289f42009-09-09 15:08:12 +00008506
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008507/// EvalVal - This function is complements EvalAddr in the mutual recursion.
8508/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008509static const Expr *EvalVal(const Expr *E,
8510 SmallVectorImpl<const DeclRefExpr *> &refVars,
8511 const Decl *ParentDecl) {
8512 do {
8513 // We should only be called for evaluating non-pointer expressions, or
8514 // expressions with a pointer type that are not used as references but
8515 // instead
8516 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00008517
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008518 // Our "symbolic interpreter" is just a dispatch off the currently
8519 // viewed AST node. We then recursively traverse the AST by calling
8520 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00008521
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008522 E = E->IgnoreParens();
8523 switch (E->getStmtClass()) {
8524 case Stmt::ImplicitCastExprClass: {
8525 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
8526 if (IE->getValueKind() == VK_LValue) {
8527 E = IE->getSubExpr();
8528 continue;
8529 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008530 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008531 }
Richard Smith40f08eb2014-01-30 22:05:38 +00008532
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008533 case Stmt::ExprWithCleanupsClass:
8534 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8535 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008536
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008537 case Stmt::DeclRefExprClass: {
8538 // When we hit a DeclRefExpr we are looking at code that refers to a
8539 // variable's name. If it's not a reference variable we check if it has
8540 // local storage within the function, and if so, return the expression.
8541 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8542
8543 // If we leave the immediate function, the lifetime isn't about to end.
8544 if (DR->refersToEnclosingVariableOrCapture())
8545 return nullptr;
8546
8547 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8548 // Check if it refers to itself, e.g. "int& i = i;".
8549 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008550 return DR;
8551
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008552 if (V->hasLocalStorage()) {
8553 if (!V->getType()->isReferenceType())
8554 return DR;
8555
8556 // Reference variable, follow through to the expression that
8557 // it points to.
8558 if (V->hasInit()) {
8559 // Add the reference variable to the "trail".
8560 refVars.push_back(DR);
8561 return EvalVal(V->getInit(), refVars, V);
8562 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008563 }
8564 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008565
8566 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008567 }
Mike Stump11289f42009-09-09 15:08:12 +00008568
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008569 case Stmt::UnaryOperatorClass: {
8570 // The only unary operator that make sense to handle here
8571 // is Deref. All others don't resolve to a "name." This includes
8572 // handling all sorts of rvalues passed to a unary operator.
8573 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008574
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008575 if (U->getOpcode() == UO_Deref)
8576 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00008577
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008578 return nullptr;
8579 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008580
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008581 case Stmt::ArraySubscriptExprClass: {
8582 // Array subscripts are potential references to data on the stack. We
8583 // retrieve the DeclRefExpr* for the array variable if it indeed
8584 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00008585 const auto *ASE = cast<ArraySubscriptExpr>(E);
8586 if (ASE->isTypeDependent())
8587 return nullptr;
8588 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008589 }
Mike Stump11289f42009-09-09 15:08:12 +00008590
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008591 case Stmt::OMPArraySectionExprClass: {
8592 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8593 ParentDecl);
8594 }
Mike Stump11289f42009-09-09 15:08:12 +00008595
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008596 case Stmt::ConditionalOperatorClass: {
8597 // For conditional operators we need to see if either the LHS or RHS are
8598 // non-NULL Expr's. If one is non-NULL, we return it.
8599 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008600
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008601 // Handle the GNU extension for missing LHS.
8602 if (const Expr *LHSExpr = C->getLHS()) {
8603 // In C++, we can have a throw-expression, which has 'void' type.
8604 if (!LHSExpr->getType()->isVoidType())
8605 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8606 return LHS;
8607 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008608
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008609 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008610 if (C->getRHS()->getType()->isVoidType())
8611 return nullptr;
8612
8613 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008614 }
8615
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008616 // Accesses to members are potential references to data on the stack.
8617 case Stmt::MemberExprClass: {
8618 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00008619
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008620 // Check for indirect access. We only want direct field accesses.
8621 if (M->isArrow())
8622 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008623
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008624 // Check whether the member type is itself a reference, in which case
8625 // we're not going to refer to the member, but to what the member refers
8626 // to.
8627 if (M->getMemberDecl()->getType()->isReferenceType())
8628 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008629
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008630 return EvalVal(M->getBase(), refVars, ParentDecl);
8631 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00008632
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008633 case Stmt::MaterializeTemporaryExprClass:
8634 if (const Expr *Result =
8635 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8636 refVars, ParentDecl))
8637 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008638 return E;
8639
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008640 default:
8641 // Check that we don't return or take the address of a reference to a
8642 // temporary. This is only useful in C++.
8643 if (!E->isTypeDependent() && E->isRValue())
8644 return E;
8645
8646 // Everything else: we simply don't reason about them.
8647 return nullptr;
8648 }
8649 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008650}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008651
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008652void
8653Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8654 SourceLocation ReturnLoc,
8655 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00008656 const AttrVec *Attrs,
8657 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008658 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8659
8660 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00008661 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8662 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00008663 CheckNonNullExpr(*this, RetValExp))
8664 Diag(ReturnLoc, diag::warn_null_ret)
8665 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00008666
8667 // C++11 [basic.stc.dynamic.allocation]p4:
8668 // If an allocation function declared with a non-throwing
8669 // exception-specification fails to allocate storage, it shall return
8670 // a null pointer. Any other allocation function that fails to allocate
8671 // storage shall indicate failure only by throwing an exception [...]
8672 if (FD) {
8673 OverloadedOperatorKind Op = FD->getOverloadedOperator();
8674 if (Op == OO_New || Op == OO_Array_New) {
8675 const FunctionProtoType *Proto
8676 = FD->getType()->castAs<FunctionProtoType>();
Richard Smitheaf11ad2018-05-03 03:58:32 +00008677 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
Artyom Skrobov9f213442014-01-24 11:10:39 +00008678 CheckNonNullExpr(*this, RetValExp))
8679 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8680 << FD << getLangOpts().CPlusPlus11;
8681 }
8682 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008683}
8684
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008685//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8686
8687/// Check for comparisons of floating point operands using != and ==.
8688/// Issue a warning if these are no self-comparisons, as they are not likely
8689/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00008690void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00008691 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8692 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008693
8694 // Special case: check for x == x (which is OK).
8695 // Do not emit warnings for such cases.
8696 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8697 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8698 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00008699 return;
Mike Stump11289f42009-09-09 15:08:12 +00008700
Ted Kremenekeda40e22007-11-29 00:59:04 +00008701 // Special case: check for comparisons against literals that can be exactly
8702 // represented by APFloat. In such cases, do not emit a warning. This
8703 // is a heuristic: often comparison against such literals are used to
8704 // detect if a value in a variable has not changed. This clearly can
8705 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00008706 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8707 if (FLL->isExact())
8708 return;
8709 } else
8710 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8711 if (FLR->isExact())
8712 return;
Mike Stump11289f42009-09-09 15:08:12 +00008713
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008714 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00008715 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008716 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008717 return;
Mike Stump11289f42009-09-09 15:08:12 +00008718
David Blaikie1f4ff152012-07-16 20:47:22 +00008719 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008720 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008721 return;
Mike Stump11289f42009-09-09 15:08:12 +00008722
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008723 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00008724 Diag(Loc, diag::warn_floatingpoint_eq)
8725 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008726}
John McCallca01b222010-01-04 23:21:16 +00008727
John McCall70aa5392010-01-06 05:24:50 +00008728//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8729//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00008730
John McCall70aa5392010-01-06 05:24:50 +00008731namespace {
John McCallca01b222010-01-04 23:21:16 +00008732
John McCall70aa5392010-01-06 05:24:50 +00008733/// Structure recording the 'active' range of an integer-valued
8734/// expression.
8735struct IntRange {
8736 /// The number of bits active in the int.
8737 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00008738
John McCall70aa5392010-01-06 05:24:50 +00008739 /// True if the int is known not to have negative values.
8740 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00008741
John McCall70aa5392010-01-06 05:24:50 +00008742 IntRange(unsigned Width, bool NonNegative)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008743 : Width(Width), NonNegative(NonNegative) {}
John McCallca01b222010-01-04 23:21:16 +00008744
John McCall817d4af2010-11-10 23:38:19 +00008745 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00008746 static IntRange forBoolType() {
8747 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00008748 }
8749
John McCall817d4af2010-11-10 23:38:19 +00008750 /// Returns the range of an opaque value of the given integral type.
8751 static IntRange forValueOfType(ASTContext &C, QualType T) {
8752 return forValueOfCanonicalType(C,
8753 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008754 }
8755
John McCall817d4af2010-11-10 23:38:19 +00008756 /// Returns the range of an opaque value of a canonical integral type.
8757 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008758 assert(T->isCanonicalUnqualified());
8759
8760 if (const VectorType *VT = dyn_cast<VectorType>(T))
8761 T = VT->getElementType().getTypePtr();
8762 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8763 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008764 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8765 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008766
Roman Lebedevca1aaac2017-10-21 16:44:03 +00008767 if (!C.getLangOpts().CPlusPlus) {
8768 // For enum types in C code, use the underlying datatype.
8769 if (const EnumType *ET = dyn_cast<EnumType>(T))
8770 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8771 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8772 // For enum types in C++, use the known bit width of the enumerators.
David Majnemer6a426652013-06-07 22:07:20 +00008773 EnumDecl *Enum = ET->getDecl();
Richard Smith371e9e8a2017-12-06 03:00:51 +00008774 // In C++11, enums can have a fixed underlying type. Use this type to
8775 // compute the range.
8776 if (Enum->isFixed()) {
Erich Keane69dbbb02017-09-21 19:58:55 +00008777 return IntRange(C.getIntWidth(QualType(T, 0)),
8778 !ET->isSignedIntegerOrEnumerationType());
Richard Smith371e9e8a2017-12-06 03:00:51 +00008779 }
John McCall18a2c2c2010-11-09 22:22:12 +00008780
David Majnemer6a426652013-06-07 22:07:20 +00008781 unsigned NumPositive = Enum->getNumPositiveBits();
8782 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008783
David Majnemer6a426652013-06-07 22:07:20 +00008784 if (NumNegative == 0)
8785 return IntRange(NumPositive, true/*NonNegative*/);
8786 else
8787 return IntRange(std::max(NumPositive + 1, NumNegative),
8788 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008789 }
John McCall70aa5392010-01-06 05:24:50 +00008790
8791 const BuiltinType *BT = cast<BuiltinType>(T);
8792 assert(BT->isInteger());
8793
8794 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8795 }
8796
John McCall817d4af2010-11-10 23:38:19 +00008797 /// Returns the "target" range of a canonical integral type, i.e.
8798 /// the range of values expressible in the type.
8799 ///
8800 /// This matches forValueOfCanonicalType except that enums have the
8801 /// full range of their type, not the range of their enumerators.
8802 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8803 assert(T->isCanonicalUnqualified());
8804
8805 if (const VectorType *VT = dyn_cast<VectorType>(T))
8806 T = VT->getElementType().getTypePtr();
8807 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8808 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008809 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8810 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008811 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008812 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008813
8814 const BuiltinType *BT = cast<BuiltinType>(T);
8815 assert(BT->isInteger());
8816
8817 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8818 }
8819
8820 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008821 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008822 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008823 L.NonNegative && R.NonNegative);
8824 }
8825
John McCall817d4af2010-11-10 23:38:19 +00008826 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008827 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008828 return IntRange(std::min(L.Width, R.Width),
8829 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008830 }
8831};
8832
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008833} // namespace
8834
8835static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8836 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008837 if (value.isSigned() && value.isNegative())
8838 return IntRange(value.getMinSignedBits(), false);
8839
8840 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008841 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008842
8843 // isNonNegative() just checks the sign bit without considering
8844 // signedness.
8845 return IntRange(value.getActiveBits(), true);
8846}
8847
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008848static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8849 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008850 if (result.isInt())
8851 return GetValueRange(C, result.getInt(), MaxWidth);
8852
8853 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008854 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8855 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8856 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8857 R = IntRange::join(R, El);
8858 }
John McCall70aa5392010-01-06 05:24:50 +00008859 return R;
8860 }
8861
8862 if (result.isComplexInt()) {
8863 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8864 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8865 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008866 }
8867
8868 // This can happen with lossless casts to intptr_t of "based" lvalues.
8869 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008870 // FIXME: The only reason we need to pass the type in here is to get
8871 // the sign right on this one case. It would be nice if APValue
8872 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008873 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008874 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008875}
John McCall70aa5392010-01-06 05:24:50 +00008876
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008877static QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008878 QualType Ty = E->getType();
8879 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8880 Ty = AtomicRHS->getValueType();
8881 return Ty;
8882}
8883
John McCall70aa5392010-01-06 05:24:50 +00008884/// Pseudo-evaluate the given integer expression, estimating the
8885/// range of values it might take.
8886///
8887/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008888static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008889 E = E->IgnoreParens();
8890
8891 // Try a full evaluation first.
8892 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008893 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008894 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008895
8896 // I think we only want to look through implicit casts here; if the
8897 // user has an explicit widening cast, we should treat the value as
8898 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008899 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008900 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008901 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8902
Eli Friedmane6d33952013-07-08 20:20:06 +00008903 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008904
George Burgess IVdf1ed002016-01-13 01:52:39 +00008905 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8906 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008907
John McCall70aa5392010-01-06 05:24:50 +00008908 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008909 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008910 return OutputTypeRange;
8911
8912 IntRange SubRange
8913 = GetExprRange(C, CE->getSubExpr(),
8914 std::min(MaxWidth, OutputTypeRange.Width));
8915
8916 // Bail out if the subexpr's range is as wide as the cast type.
8917 if (SubRange.Width >= OutputTypeRange.Width)
8918 return OutputTypeRange;
8919
8920 // Otherwise, we take the smaller width, and we're non-negative if
8921 // either the output type or the subexpr is.
8922 return IntRange(SubRange.Width,
8923 SubRange.NonNegative || OutputTypeRange.NonNegative);
8924 }
8925
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008926 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008927 // If we can fold the condition, just take that operand.
8928 bool CondResult;
8929 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8930 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8931 : CO->getFalseExpr(),
8932 MaxWidth);
8933
8934 // Otherwise, conservatively merge.
8935 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8936 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8937 return IntRange::join(L, R);
8938 }
8939
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008940 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008941 switch (BO->getOpcode()) {
Richard Smithc70f1d62017-12-14 15:16:18 +00008942 case BO_Cmp:
8943 llvm_unreachable("builtin <=> should have class type");
John McCall70aa5392010-01-06 05:24:50 +00008944
8945 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00008946 case BO_LAnd:
8947 case BO_LOr:
8948 case BO_LT:
8949 case BO_GT:
8950 case BO_LE:
8951 case BO_GE:
8952 case BO_EQ:
8953 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008954 return IntRange::forBoolType();
8955
John McCallc3688382011-07-13 06:35:24 +00008956 // The type of the assignments is the type of the LHS, so the RHS
8957 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008958 case BO_MulAssign:
8959 case BO_DivAssign:
8960 case BO_RemAssign:
8961 case BO_AddAssign:
8962 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008963 case BO_XorAssign:
8964 case BO_OrAssign:
8965 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008966 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008967
John McCallc3688382011-07-13 06:35:24 +00008968 // Simple assignments just pass through the RHS, which will have
8969 // been coerced to the LHS type.
8970 case BO_Assign:
8971 // TODO: bitfields?
8972 return GetExprRange(C, BO->getRHS(), MaxWidth);
8973
John McCall70aa5392010-01-06 05:24:50 +00008974 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008975 case BO_PtrMemD:
8976 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008977 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008978
John McCall2ce81ad2010-01-06 22:07:33 +00008979 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008980 case BO_And:
8981 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008982 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8983 GetExprRange(C, BO->getRHS(), MaxWidth));
8984
John McCall70aa5392010-01-06 05:24:50 +00008985 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008986 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008987 // ...except that we want to treat '1 << (blah)' as logically
8988 // positive. It's an important idiom.
8989 if (IntegerLiteral *I
8990 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8991 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008992 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008993 return IntRange(R.Width, /*NonNegative*/ true);
8994 }
8995 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008996 LLVM_FALLTHROUGH;
John McCall1bff9932010-04-07 01:14:35 +00008997
John McCalle3027922010-08-25 11:45:40 +00008998 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008999 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009000
John McCall2ce81ad2010-01-06 22:07:33 +00009001 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00009002 case BO_Shr:
9003 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00009004 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9005
9006 // If the shift amount is a positive constant, drop the width by
9007 // that much.
9008 llvm::APSInt shift;
9009 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
9010 shift.isNonNegative()) {
9011 unsigned zext = shift.getZExtValue();
9012 if (zext >= L.Width)
9013 L.Width = (L.NonNegative ? 0 : 1);
9014 else
9015 L.Width -= zext;
9016 }
9017
9018 return L;
9019 }
9020
9021 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00009022 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00009023 return GetExprRange(C, BO->getRHS(), MaxWidth);
9024
John McCall2ce81ad2010-01-06 22:07:33 +00009025 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00009026 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00009027 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00009028 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009029 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00009030
John McCall51431812011-07-14 22:39:48 +00009031 // The width of a division result is mostly determined by the size
9032 // of the LHS.
9033 case BO_Div: {
9034 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00009035 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009036 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9037
9038 // If the divisor is constant, use that.
9039 llvm::APSInt divisor;
9040 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
9041 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
9042 if (log2 >= L.Width)
9043 L.Width = (L.NonNegative ? 0 : 1);
9044 else
9045 L.Width = std::min(L.Width - log2, MaxWidth);
9046 return L;
9047 }
9048
9049 // Otherwise, just use the LHS's width.
9050 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9051 return IntRange(L.Width, L.NonNegative && R.NonNegative);
9052 }
9053
9054 // The result of a remainder can't be larger than the result of
9055 // either side.
9056 case BO_Rem: {
9057 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00009058 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009059 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9060 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9061
9062 IntRange meet = IntRange::meet(L, R);
9063 meet.Width = std::min(meet.Width, MaxWidth);
9064 return meet;
9065 }
9066
9067 // The default behavior is okay for these.
9068 case BO_Mul:
9069 case BO_Add:
9070 case BO_Xor:
9071 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00009072 break;
9073 }
9074
John McCall51431812011-07-14 22:39:48 +00009075 // The default case is to treat the operation as if it were closed
9076 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00009077 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9078 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
9079 return IntRange::join(L, R);
9080 }
9081
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009082 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00009083 switch (UO->getOpcode()) {
9084 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00009085 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00009086 return IntRange::forBoolType();
9087
9088 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00009089 case UO_Deref:
9090 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00009091 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009092
9093 default:
9094 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
9095 }
9096 }
9097
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009098 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00009099 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
9100
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009101 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00009102 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00009103 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00009104
Eli Friedmane6d33952013-07-08 20:20:06 +00009105 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009106}
John McCall263a48b2010-01-04 23:31:57 +00009107
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009108static IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009109 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00009110}
9111
John McCall263a48b2010-01-04 23:31:57 +00009112/// Checks whether the given value, which currently has the given
9113/// source semantics, has the same value when coerced through the
9114/// target semantics.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009115static bool IsSameFloatAfterCast(const llvm::APFloat &value,
9116 const llvm::fltSemantics &Src,
9117 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009118 llvm::APFloat truncated = value;
9119
9120 bool ignored;
9121 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
9122 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
9123
9124 return truncated.bitwiseIsEqual(value);
9125}
9126
9127/// Checks whether the given value, which currently has the given
9128/// source semantics, has the same value when coerced through the
9129/// target semantics.
9130///
9131/// The value might be a vector of floats (or a complex number).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009132static bool IsSameFloatAfterCast(const APValue &value,
9133 const llvm::fltSemantics &Src,
9134 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009135 if (value.isFloat())
9136 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
9137
9138 if (value.isVector()) {
9139 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
9140 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
9141 return false;
9142 return true;
9143 }
9144
9145 assert(value.isComplexFloat());
9146 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
9147 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
9148}
9149
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009150static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009151
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009152static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00009153 // Suppress cases where we are comparing against an enum constant.
9154 if (const DeclRefExpr *DR =
9155 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
9156 if (isa<EnumConstantDecl>(DR->getDecl()))
Roman Lebedev6de129e2017-10-15 20:13:17 +00009157 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009158
9159 // Suppress cases where the '0' value is expanded from a macro.
9160 if (E->getLocStart().isMacroID())
Roman Lebedev6de129e2017-10-15 20:13:17 +00009161 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009162
Roman Lebedev6de129e2017-10-15 20:13:17 +00009163 return false;
9164}
9165
Richard Smith692f66ab2017-12-06 19:23:19 +00009166static bool isKnownToHaveUnsignedValue(Expr *E) {
9167 return E->getType()->isIntegerType() &&
Roman Lebedev6de129e2017-10-15 20:13:17 +00009168 (!E->getType()->isSignedIntegerType() ||
9169 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
9170}
9171
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009172namespace {
Richard Smitha5370fb2017-12-08 22:57:11 +00009173/// The promoted range of values of a type. In general this has the
9174/// following structure:
9175///
9176/// |-----------| . . . |-----------|
9177/// ^ ^ ^ ^
9178/// Min HoleMin HoleMax Max
9179///
9180/// ... where there is only a hole if a signed type is promoted to unsigned
9181/// (in which case Min and Max are the smallest and largest representable
9182/// values).
9183struct PromotedRange {
9184 // Min, or HoleMax if there is a hole.
9185 llvm::APSInt PromotedMin;
9186 // Max, or HoleMin if there is a hole.
9187 llvm::APSInt PromotedMax;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009188
Richard Smitha5370fb2017-12-08 22:57:11 +00009189 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
9190 if (R.Width == 0)
9191 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
9192 else if (R.Width >= BitWidth && !Unsigned) {
9193 // Promotion made the type *narrower*. This happens when promoting
9194 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
9195 // Treat all values of 'signed int' as being in range for now.
9196 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
9197 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
9198 } else {
9199 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
9200 .extOrTrunc(BitWidth);
9201 PromotedMin.setIsUnsigned(Unsigned);
9202
9203 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
9204 .extOrTrunc(BitWidth);
9205 PromotedMax.setIsUnsigned(Unsigned);
9206 }
9207 }
9208
9209 // Determine whether this range is contiguous (has no hole).
9210 bool isContiguous() const { return PromotedMin <= PromotedMax; }
9211
9212 // Where a constant value is within the range.
9213 enum ComparisonResult {
9214 LT = 0x1,
9215 LE = 0x2,
9216 GT = 0x4,
9217 GE = 0x8,
9218 EQ = 0x10,
9219 NE = 0x20,
9220 InRangeFlag = 0x40,
9221
9222 Less = LE | LT | NE,
9223 Min = LE | InRangeFlag,
9224 InRange = InRangeFlag,
9225 Max = GE | InRangeFlag,
9226 Greater = GE | GT | NE,
9227
9228 OnlyValue = LE | GE | EQ | InRangeFlag,
9229 InHole = NE
9230 };
9231
9232 ComparisonResult compare(const llvm::APSInt &Value) const {
9233 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
9234 Value.isUnsigned() == PromotedMin.isUnsigned());
9235 if (!isContiguous()) {
9236 assert(Value.isUnsigned() && "discontiguous range for signed compare");
9237 if (Value.isMinValue()) return Min;
9238 if (Value.isMaxValue()) return Max;
9239 if (Value >= PromotedMin) return InRange;
9240 if (Value <= PromotedMax) return InRange;
9241 return InHole;
9242 }
9243
9244 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
9245 case -1: return Less;
9246 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
9247 case 1:
9248 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
9249 case -1: return InRange;
9250 case 0: return Max;
9251 case 1: return Greater;
9252 }
9253 }
9254
9255 llvm_unreachable("impossible compare result");
9256 }
9257
Richard Smithc70f1d62017-12-14 15:16:18 +00009258 static llvm::Optional<StringRef>
9259 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
9260 if (Op == BO_Cmp) {
9261 ComparisonResult LTFlag = LT, GTFlag = GT;
9262 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
9263
9264 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
9265 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
9266 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
9267 return llvm::None;
9268 }
9269
Richard Smitha5370fb2017-12-08 22:57:11 +00009270 ComparisonResult TrueFlag, FalseFlag;
9271 if (Op == BO_EQ) {
9272 TrueFlag = EQ;
9273 FalseFlag = NE;
9274 } else if (Op == BO_NE) {
9275 TrueFlag = NE;
9276 FalseFlag = EQ;
9277 } else {
9278 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
9279 TrueFlag = LT;
9280 FalseFlag = GE;
9281 } else {
9282 TrueFlag = GT;
9283 FalseFlag = LE;
9284 }
9285 if (Op == BO_GE || Op == BO_LE)
9286 std::swap(TrueFlag, FalseFlag);
9287 }
9288 if (R & TrueFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00009289 return StringRef("true");
Richard Smitha5370fb2017-12-08 22:57:11 +00009290 if (R & FalseFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00009291 return StringRef("false");
Richard Smitha5370fb2017-12-08 22:57:11 +00009292 return llvm::None;
9293 }
Roman Lebedev6de129e2017-10-15 20:13:17 +00009294};
John McCallcc7e5bf2010-05-06 08:58:33 +00009295}
9296
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009297static bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00009298 // Strip off implicit integral promotions.
9299 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00009300 if (ICE->getCastKind() != CK_IntegralCast &&
9301 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00009302 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00009303 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00009304 }
9305
9306 return E->getType()->isEnumeralType();
9307}
9308
Richard Smith692f66ab2017-12-06 19:23:19 +00009309static int classifyConstantValue(Expr *Constant) {
9310 // The values of this enumeration are used in the diagnostics
9311 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
9312 enum ConstantValueKind {
9313 Miscellaneous = 0,
9314 LiteralTrue,
9315 LiteralFalse
9316 };
9317 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
9318 return BL->getValue() ? ConstantValueKind::LiteralTrue
9319 : ConstantValueKind::LiteralFalse;
9320 return ConstantValueKind::Miscellaneous;
9321}
9322
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009323static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
9324 Expr *Constant, Expr *Other,
9325 const llvm::APSInt &Value,
9326 bool RhsConstant) {
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009327 if (S.inTemplateInstantiation())
9328 return false;
9329
Richard Smitha5370fb2017-12-08 22:57:11 +00009330 Expr *OriginalOther = Other;
9331
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009332 Constant = Constant->IgnoreParenImpCasts();
9333 Other = Other->IgnoreParenImpCasts();
9334
Richard Smitha5370fb2017-12-08 22:57:11 +00009335 // Suppress warnings on tautological comparisons between values of the same
9336 // enumeration type. There are only two ways we could warn on this:
9337 // - If the constant is outside the range of representable values of
9338 // the enumeration. In such a case, we should warn about the cast
9339 // to enumeration type, not about the comparison.
9340 // - If the constant is the maximum / minimum in-range value. For an
9341 // enumeratin type, such comparisons can be meaningful and useful.
9342 if (Constant->getType()->isEnumeralType() &&
9343 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
9344 return false;
9345
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009346 // TODO: Investigate using GetExprRange() to get tighter bounds
9347 // on the bit ranges.
9348 QualType OtherT = Other->getType();
9349 if (const auto *AT = OtherT->getAs<AtomicType>())
9350 OtherT = AT->getValueType();
9351 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
9352
9353 // Whether we're treating Other as being a bool because of the form of
9354 // expression despite it having another type (typically 'int' in C).
9355 bool OtherIsBooleanDespiteType =
9356 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
9357 if (OtherIsBooleanDespiteType)
9358 OtherRange = IntRange::forBoolType();
9359
Richard Smitha5370fb2017-12-08 22:57:11 +00009360 // Determine the promoted range of the other type and see if a comparison of
9361 // the constant against that range is tautological.
9362 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
9363 Value.isUnsigned());
9364 auto Cmp = OtherPromotedRange.compare(Value);
9365 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
9366 if (!Result)
9367 return false;
Hans Wennborg5791ce72017-12-08 16:54:08 +00009368
Richard Smitha5370fb2017-12-08 22:57:11 +00009369 // Suppress the diagnostic for an in-range comparison if the constant comes
9370 // from a macro or enumerator. We don't want to diagnose
9371 //
9372 // some_long_value <= INT_MAX
9373 //
9374 // when sizeof(int) == sizeof(long).
9375 bool InRange = Cmp & PromotedRange::InRangeFlag;
9376 if (InRange && IsEnumConstOrFromMacro(S, Constant))
9377 return false;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009378
9379 // If this is a comparison to an enum constant, include that
9380 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00009381 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009382 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
9383 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
9384
Richard Smitha5370fb2017-12-08 22:57:11 +00009385 // Should be enough for uint128 (39 decimal digits)
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009386 SmallString<64> PrettySourceValue;
9387 llvm::raw_svector_ostream OS(PrettySourceValue);
9388 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00009389 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009390 else
9391 OS << Value;
9392
Richard Smitha5370fb2017-12-08 22:57:11 +00009393 // FIXME: We use a somewhat different formatting for the in-range cases and
9394 // cases involving boolean values for historical reasons. We should pick a
9395 // consistent way of presenting these diagnostics.
9396 if (!InRange || Other->isKnownToHaveBooleanValue()) {
9397 S.DiagRuntimeBehavior(
9398 E->getOperatorLoc(), E,
9399 S.PDiag(!InRange ? diag::warn_out_of_range_compare
9400 : diag::warn_tautological_bool_compare)
9401 << OS.str() << classifyConstantValue(Constant)
9402 << OtherT << OtherIsBooleanDespiteType << *Result
9403 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
9404 } else {
9405 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
9406 ? (HasEnumType(OriginalOther)
9407 ? diag::warn_unsigned_enum_always_true_comparison
9408 : diag::warn_unsigned_always_true_comparison)
9409 : diag::warn_tautological_constant_compare;
Roman Lebedev6de129e2017-10-15 20:13:17 +00009410
Richard Smitha5370fb2017-12-08 22:57:11 +00009411 S.Diag(E->getOperatorLoc(), Diag)
9412 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
9413 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
9414 }
9415
9416 return true;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009417}
9418
John McCallcc7e5bf2010-05-06 08:58:33 +00009419/// Analyze the operands of the given comparison. Implements the
9420/// fallback case from AnalyzeComparison.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009421static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00009422 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9423 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009424}
John McCall263a48b2010-01-04 23:31:57 +00009425
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009426/// Implements -Wsign-compare.
John McCallca01b222010-01-04 23:21:16 +00009427///
Richard Trieu82402a02011-09-15 21:56:47 +00009428/// \param E the binary operator to check for warnings
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009429static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009430 // The type the comparison is being performed in.
9431 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00009432
9433 // Only analyze comparison operators where both sides have been converted to
9434 // the same type.
9435 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
9436 return AnalyzeImpConvsInComparison(S, E);
9437
9438 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00009439 if (E->isValueDependent())
9440 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00009441
Roman Lebedev6de129e2017-10-15 20:13:17 +00009442 Expr *LHS = E->getLHS();
9443 Expr *RHS = E->getRHS();
9444
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009445 if (T->isIntegralType(S.Context)) {
9446 llvm::APSInt RHSValue;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009447 llvm::APSInt LHSValue;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009448
Roman Lebedev6de129e2017-10-15 20:13:17 +00009449 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
9450 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
Roman Lebedevbd1fc222017-10-12 20:16:51 +00009451
Roman Lebedev6de129e2017-10-15 20:13:17 +00009452 // We don't care about expressions whose result is a constant.
9453 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
9454 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6f405db2017-10-12 22:03:20 +00009455
Roman Lebedev6de129e2017-10-15 20:13:17 +00009456 // We only care about expressions where just one side is literal
9457 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
9458 // Is the constant on the RHS or LHS?
9459 const bool RhsConstant = IsRHSIntegralLiteral;
9460 Expr *Const = RhsConstant ? RHS : LHS;
9461 Expr *Other = RhsConstant ? LHS : RHS;
9462 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
9463
9464 // Check whether an integer constant comparison results in a value
9465 // of 'true' or 'false'.
Roman Lebedev6de129e2017-10-15 20:13:17 +00009466 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
9467 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00009468 }
9469 }
9470
9471 if (!T->hasUnsignedIntegerRepresentation()) {
9472 // We don't do anything special if this isn't an unsigned integral
9473 // comparison: we're only interested in integral comparisons, and
9474 // signed comparisons only happen in cases we don't care to warn about.
Roman Lebedev6f405db2017-10-12 22:03:20 +00009475 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00009476 }
9477
9478 LHS = LHS->IgnoreParenImpCasts();
9479 RHS = RHS->IgnoreParenImpCasts();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009480
Alex Lorenzb57409f2018-02-07 20:45:39 +00009481 if (!S.getLangOpts().CPlusPlus) {
9482 // Avoid warning about comparison of integers with different signs when
9483 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
9484 // the type of `E`.
9485 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
9486 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9487 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
9488 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9489 }
9490
John McCallcc7e5bf2010-05-06 08:58:33 +00009491 // Check to see if one of the (unmodified) operands is of different
9492 // signedness.
9493 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00009494 if (LHS->getType()->hasSignedIntegerRepresentation()) {
9495 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00009496 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00009497 signedOperand = LHS;
9498 unsignedOperand = RHS;
9499 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
9500 signedOperand = RHS;
9501 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00009502 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00009503 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00009504 }
9505
John McCallcc7e5bf2010-05-06 08:58:33 +00009506 // Otherwise, calculate the effective range of the signed operand.
9507 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00009508
John McCallcc7e5bf2010-05-06 08:58:33 +00009509 // Go ahead and analyze implicit conversions in the operands. Note
9510 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00009511 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
9512 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00009513
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009514 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +00009515 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009516 return;
John McCallca01b222010-01-04 23:21:16 +00009517
9518 // For (in)equality comparisons, if the unsigned operand is a
9519 // constant which cannot collide with a overflowed signed operand,
9520 // then reinterpreting the signed operand as unsigned will not
9521 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00009522 if (E->isEqualityOp()) {
9523 unsigned comparisonWidth = S.Context.getIntWidth(T);
9524 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00009525
John McCallcc7e5bf2010-05-06 08:58:33 +00009526 // We should never be unable to prove that the unsigned operand is
9527 // non-negative.
9528 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9529
9530 if (unsignedRange.Width < comparisonWidth)
9531 return;
9532 }
9533
Douglas Gregorbfb4a212012-05-01 01:53:49 +00009534 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9535 S.PDiag(diag::warn_mixed_sign_comparison)
9536 << LHS->getType() << RHS->getType()
9537 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00009538}
9539
John McCall1f425642010-11-11 03:21:53 +00009540/// Analyzes an attempt to assign the given value to a bitfield.
9541///
9542/// Returns true if there was something fishy about the attempt.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009543static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9544 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00009545 assert(Bitfield->isBitField());
9546 if (Bitfield->isInvalidDecl())
9547 return false;
9548
John McCalldeebbcf2010-11-11 05:33:51 +00009549 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00009550 QualType BitfieldType = Bitfield->getType();
9551 if (BitfieldType->isBooleanType())
9552 return false;
9553
9554 if (BitfieldType->isEnumeralType()) {
9555 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9556 // If the underlying enum type was not explicitly specified as an unsigned
9557 // type and the enum contain only positive values, MSVC++ will cause an
9558 // inconsistency by storing this as a signed type.
9559 if (S.getLangOpts().CPlusPlus11 &&
9560 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9561 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9562 BitfieldEnumDecl->getNumNegativeBits() == 0) {
9563 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9564 << BitfieldEnumDecl->getNameAsString();
9565 }
9566 }
9567
John McCalldeebbcf2010-11-11 05:33:51 +00009568 if (Bitfield->getType()->isBooleanType())
9569 return false;
9570
Douglas Gregor789adec2011-02-04 13:09:01 +00009571 // Ignore value- or type-dependent expressions.
9572 if (Bitfield->getBitWidth()->isValueDependent() ||
9573 Bitfield->getBitWidth()->isTypeDependent() ||
9574 Init->isValueDependent() ||
9575 Init->isTypeDependent())
9576 return false;
9577
John McCall1f425642010-11-11 03:21:53 +00009578 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00009579 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00009580
Richard Smith5fab0c92011-12-28 19:48:30 +00009581 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009582 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9583 Expr::SE_AllowSideEffects)) {
9584 // The RHS is not constant. If the RHS has an enum type, make sure the
9585 // bitfield is wide enough to hold all the values of the enum without
9586 // truncation.
9587 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9588 EnumDecl *ED = EnumTy->getDecl();
9589 bool SignedBitfield = BitfieldType->isSignedIntegerType();
9590
9591 // Enum types are implicitly signed on Windows, so check if there are any
9592 // negative enumerators to see if the enum was intended to be signed or
9593 // not.
9594 bool SignedEnum = ED->getNumNegativeBits() > 0;
9595
9596 // Check for surprising sign changes when assigning enum values to a
9597 // bitfield of different signedness. If the bitfield is signed and we
9598 // have exactly the right number of bits to store this unsigned enum,
9599 // suggest changing the enum to an unsigned type. This typically happens
9600 // on Windows where unfixed enums always use an underlying type of 'int'.
9601 unsigned DiagID = 0;
9602 if (SignedEnum && !SignedBitfield) {
9603 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9604 } else if (SignedBitfield && !SignedEnum &&
9605 ED->getNumPositiveBits() == FieldWidth) {
9606 DiagID = diag::warn_signed_bitfield_enum_conversion;
9607 }
9608
9609 if (DiagID) {
9610 S.Diag(InitLoc, DiagID) << Bitfield << ED;
9611 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9612 SourceRange TypeRange =
9613 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9614 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9615 << SignedEnum << TypeRange;
9616 }
9617
9618 // Compute the required bitwidth. If the enum has negative values, we need
9619 // one more bit than the normal number of positive bits to represent the
9620 // sign bit.
9621 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9622 ED->getNumNegativeBits())
9623 : ED->getNumPositiveBits();
9624
9625 // Check the bitwidth.
9626 if (BitsNeeded > FieldWidth) {
9627 Expr *WidthExpr = Bitfield->getBitWidth();
9628 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9629 << Bitfield << ED;
9630 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9631 << BitsNeeded << ED << WidthExpr->getSourceRange();
9632 }
9633 }
9634
John McCall1f425642010-11-11 03:21:53 +00009635 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009636 }
John McCall1f425642010-11-11 03:21:53 +00009637
John McCall1f425642010-11-11 03:21:53 +00009638 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00009639
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009640 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00009641 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009642 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9643 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00009644
John McCall1f425642010-11-11 03:21:53 +00009645 if (OriginalWidth <= FieldWidth)
9646 return false;
9647
Eli Friedmanc267a322012-01-26 23:11:39 +00009648 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00009649 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00009650 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00009651
Eli Friedmanc267a322012-01-26 23:11:39 +00009652 // Check whether the stored value is equal to the original value.
9653 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00009654 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00009655 return false;
9656
Eli Friedmanc267a322012-01-26 23:11:39 +00009657 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00009658 // therefore don't strictly fit into a signed bitfield of width 1.
9659 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00009660 return false;
9661
John McCall1f425642010-11-11 03:21:53 +00009662 std::string PrettyValue = Value.toString(10);
9663 std::string PrettyTrunc = TruncatedValue.toString(10);
9664
9665 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9666 << PrettyValue << PrettyTrunc << OriginalInit->getType()
9667 << Init->getSourceRange();
9668
9669 return true;
9670}
9671
John McCalld2a53122010-11-09 23:24:47 +00009672/// Analyze the given simple or compound assignment for warning-worthy
9673/// operations.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009674static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00009675 // Just recurse on the LHS.
9676 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9677
9678 // We want to recurse on the RHS as normal unless we're assigning to
9679 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00009680 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009681 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00009682 E->getOperatorLoc())) {
9683 // Recurse, ignoring any implicit conversions on the RHS.
9684 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9685 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00009686 }
9687 }
9688
9689 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9690}
9691
John McCall263a48b2010-01-04 23:31:57 +00009692/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009693static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9694 SourceLocation CContext, unsigned diag,
9695 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009696 if (pruneControlFlow) {
9697 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9698 S.PDiag(diag)
9699 << SourceType << T << E->getSourceRange()
9700 << SourceRange(CContext));
9701 return;
9702 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00009703 S.Diag(E->getExprLoc(), diag)
9704 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9705}
9706
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009707/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009708static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9709 SourceLocation CContext,
9710 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009711 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009712}
9713
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +00009714/// Analyze the given compound assignment for the possible losing of
9715/// floating-point precision.
9716static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
9717 assert(isa<CompoundAssignOperator>(E) &&
9718 "Must be compound assignment operation");
9719 // Recurse on the LHS and RHS in here
9720 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9721 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9722
9723 // Now check the outermost expression
9724 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
9725 const auto *RBT = cast<CompoundAssignOperator>(E)
9726 ->getComputationResultType()
9727 ->getAs<BuiltinType>();
9728
9729 // If both source and target are floating points.
9730 if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint())
9731 // Builtin FP kinds are ordered by increasing FP rank.
9732 if (ResultBT->getKind() < RBT->getKind())
9733 // We don't want to warn for system macro.
9734 if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
9735 // warn about dropping FP rank.
9736 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(),
9737 E->getOperatorLoc(),
9738 diag::warn_impcast_float_result_precision);
9739}
Richard Trieube234c32016-04-21 21:04:55 +00009740
9741/// Diagnose an implicit cast from a floating point value to an integer value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009742static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9743 SourceLocation CContext) {
Richard Trieube234c32016-04-21 21:04:55 +00009744 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00009745 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00009746
9747 Expr *InnerE = E->IgnoreParenImpCasts();
9748 // We also want to warn on, e.g., "int i = -1.234"
9749 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9750 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9751 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9752
9753 const bool IsLiteral =
9754 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9755
9756 llvm::APFloat Value(0.0);
9757 bool IsConstant =
9758 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9759 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00009760 return DiagnoseImpCast(S, E, T, CContext,
9761 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00009762 }
9763
Chandler Carruth016ef402011-04-10 08:36:24 +00009764 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00009765
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00009766 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9767 T->hasUnsignedIntegerRepresentation());
Erich Keanea4c48c62018-05-08 21:26:21 +00009768 llvm::APFloat::opStatus Result = Value.convertToInteger(
9769 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
9770
9771 if (Result == llvm::APFloat::opOK && isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00009772 if (IsLiteral) return;
9773 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9774 PruneWarnings);
9775 }
9776
Erich Keanea4c48c62018-05-08 21:26:21 +00009777 // Conversion of a floating-point value to a non-bool integer where the
9778 // integral part cannot be represented by the integer type is undefined.
9779 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
9780 return DiagnoseImpCast(
9781 S, E, T, CContext,
9782 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
Richard Trieua2b8fe62018-05-14 23:21:48 +00009783 : diag::warn_impcast_float_to_integer_out_of_range,
9784 PruneWarnings);
Erich Keanea4c48c62018-05-08 21:26:21 +00009785
Richard Trieube234c32016-04-21 21:04:55 +00009786 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00009787 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00009788 // Warn on floating point literal to integer.
9789 DiagID = diag::warn_impcast_literal_float_to_integer;
9790 } else if (IntegerValue == 0) {
9791 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
9792 return DiagnoseImpCast(S, E, T, CContext,
9793 diag::warn_impcast_float_integer, PruneWarnings);
9794 }
9795 // Warn on non-zero to zero conversion.
9796 DiagID = diag::warn_impcast_float_to_integer_zero;
9797 } else {
9798 if (IntegerValue.isUnsigned()) {
9799 if (!IntegerValue.isMaxValue()) {
9800 return DiagnoseImpCast(S, E, T, CContext,
9801 diag::warn_impcast_float_integer, PruneWarnings);
9802 }
9803 } else { // IntegerValue.isSigned()
9804 if (!IntegerValue.isMaxSignedValue() &&
9805 !IntegerValue.isMinSignedValue()) {
9806 return DiagnoseImpCast(S, E, T, CContext,
9807 diag::warn_impcast_float_integer, PruneWarnings);
9808 }
9809 }
9810 // Warn on evaluatable floating point expression to integer conversion.
9811 DiagID = diag::warn_impcast_float_to_integer;
9812 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009813
Eli Friedman07185912013-08-29 23:44:43 +00009814 // FIXME: Force the precision of the source value down so we don't print
9815 // digits which are usually useless (we don't really care here if we
9816 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9817 // would automatically print the shortest representation, but it's a bit
9818 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009819 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009820 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9821 precision = (precision * 59 + 195) / 196;
9822 Value.toString(PrettySourceValue, precision);
9823
David Blaikie9b88cc02012-05-15 17:18:27 +00009824 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009825 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009826 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009827 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009828 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009829
Richard Trieube234c32016-04-21 21:04:55 +00009830 if (PruneWarnings) {
9831 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9832 S.PDiag(DiagID)
9833 << E->getType() << T.getUnqualifiedType()
9834 << PrettySourceValue << PrettyTargetValue
9835 << E->getSourceRange() << SourceRange(CContext));
9836 } else {
9837 S.Diag(E->getExprLoc(), DiagID)
9838 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9839 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9840 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009841}
9842
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009843static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9844 IntRange Range) {
John McCall18a2c2c2010-11-09 22:22:12 +00009845 if (!Range.Width) return "0";
9846
9847 llvm::APSInt ValueInRange = Value;
9848 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009849 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009850 return ValueInRange.toString(10);
9851}
9852
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009853static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009854 if (!isa<ImplicitCastExpr>(Ex))
9855 return false;
9856
9857 Expr *InnerE = Ex->IgnoreParenImpCasts();
9858 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9859 const Type *Source =
9860 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9861 if (Target->isDependentType())
9862 return false;
9863
9864 const BuiltinType *FloatCandidateBT =
9865 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9866 const Type *BoolCandidateType = ToBool ? Target : Source;
9867
9868 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9869 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9870}
9871
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009872static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9873 SourceLocation CC) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009874 unsigned NumArgs = TheCall->getNumArgs();
9875 for (unsigned i = 0; i < NumArgs; ++i) {
9876 Expr *CurrA = TheCall->getArg(i);
9877 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9878 continue;
9879
9880 bool IsSwapped = ((i > 0) &&
9881 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9882 IsSwapped |= ((i < (NumArgs - 1)) &&
9883 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9884 if (IsSwapped) {
9885 // Warn on this floating-point to bool conversion.
9886 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9887 CurrA->getType(), CC,
9888 diag::warn_impcast_floating_point_to_bool);
9889 }
9890 }
9891}
9892
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009893static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
9894 SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009895 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9896 E->getExprLoc()))
9897 return;
9898
Richard Trieu09d6b802016-01-08 23:35:06 +00009899 // Don't warn on functions which have return type nullptr_t.
9900 if (isa<CallExpr>(E))
9901 return;
9902
Richard Trieu5b993502014-10-15 03:42:06 +00009903 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9904 const Expr::NullPointerConstantKind NullKind =
9905 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9906 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9907 return;
9908
9909 // Return if target type is a safe conversion.
9910 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9911 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9912 return;
9913
9914 SourceLocation Loc = E->getSourceRange().getBegin();
9915
Richard Trieu0a5e1662016-02-13 00:58:53 +00009916 // Venture through the macro stacks to get to the source of macro arguments.
9917 // The new location is a better location than the complete location that was
9918 // passed in.
George Karpenkov441e8fd2018-02-09 23:30:07 +00009919 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
9920 CC = S.SourceMgr.getTopMacroCallerLoc(CC);
Richard Trieu0a5e1662016-02-13 00:58:53 +00009921
Richard Trieu5b993502014-10-15 03:42:06 +00009922 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009923 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9924 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9925 Loc, S.SourceMgr, S.getLangOpts());
9926 if (MacroName == "NULL")
Richard Smithb5f81712018-04-30 05:25:48 +00009927 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
Richard Trieu5b993502014-10-15 03:42:06 +00009928 }
9929
9930 // Only warn if the null and context location are in the same macro expansion.
9931 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9932 return;
9933
9934 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009935 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
Richard Trieu5b993502014-10-15 03:42:06 +00009936 << FixItHint::CreateReplacement(Loc,
9937 S.getFixItZeroLiteralForType(T, Loc));
9938}
9939
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009940static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9941 ObjCArrayLiteral *ArrayLiteral);
9942
9943static void
9944checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9945 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00009946
9947/// Check a single element within a collection literal against the
9948/// target element type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009949static void checkObjCCollectionLiteralElement(Sema &S,
9950 QualType TargetElementType,
9951 Expr *Element,
9952 unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009953 // Skip a bitcast to 'id' or qualified 'id'.
9954 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9955 if (ICE->getCastKind() == CK_BitCast &&
9956 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9957 Element = ICE->getSubExpr();
9958 }
9959
9960 QualType ElementType = Element->getType();
9961 ExprResult ElementResult(Element);
9962 if (ElementType->getAs<ObjCObjectPointerType>() &&
9963 S.CheckSingleAssignmentConstraints(TargetElementType,
9964 ElementResult,
9965 false, false)
9966 != Sema::Compatible) {
9967 S.Diag(Element->getLocStart(),
9968 diag::warn_objc_collection_literal_element)
9969 << ElementType << ElementKind << TargetElementType
9970 << Element->getSourceRange();
9971 }
9972
9973 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9974 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9975 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9976 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9977}
9978
9979/// Check an Objective-C array literal being converted to the given
9980/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009981static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9982 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009983 if (!S.NSArrayDecl)
9984 return;
9985
9986 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9987 if (!TargetObjCPtr)
9988 return;
9989
9990 if (TargetObjCPtr->isUnspecialized() ||
9991 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9992 != S.NSArrayDecl->getCanonicalDecl())
9993 return;
9994
9995 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9996 if (TypeArgs.size() != 1)
9997 return;
9998
9999 QualType TargetElementType = TypeArgs[0];
10000 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
10001 checkObjCCollectionLiteralElement(S, TargetElementType,
10002 ArrayLiteral->getElement(I),
10003 0);
10004 }
10005}
10006
10007/// Check an Objective-C dictionary literal being converted to the given
10008/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010009static void
10010checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10011 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010012 if (!S.NSDictionaryDecl)
10013 return;
10014
10015 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10016 if (!TargetObjCPtr)
10017 return;
10018
10019 if (TargetObjCPtr->isUnspecialized() ||
10020 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10021 != S.NSDictionaryDecl->getCanonicalDecl())
10022 return;
10023
10024 auto TypeArgs = TargetObjCPtr->getTypeArgs();
10025 if (TypeArgs.size() != 2)
10026 return;
10027
10028 QualType TargetKeyType = TypeArgs[0];
10029 QualType TargetObjectType = TypeArgs[1];
10030 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
10031 auto Element = DictionaryLiteral->getKeyValueElement(I);
10032 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
10033 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
10034 }
10035}
10036
Richard Trieufc404c72016-02-05 23:02:38 +000010037// Helper function to filter out cases for constant width constant conversion.
10038// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010039static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
10040 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +000010041 // If initializing from a constant, and the constant starts with '0',
10042 // then it is a binary, octal, or hexadecimal. Allow these constants
10043 // to fill all the bits, even if there is a sign change.
10044 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
10045 const char FirstLiteralCharacter =
10046 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
10047 if (FirstLiteralCharacter == '0')
10048 return false;
10049 }
10050
10051 // If the CC location points to a '{', and the type is char, then assume
10052 // assume it is an array initialization.
10053 if (CC.isValid() && T->isCharType()) {
10054 const char FirstContextCharacter =
10055 S.getSourceManager().getCharacterData(CC)[0];
10056 if (FirstContextCharacter == '{')
10057 return false;
10058 }
10059
10060 return true;
10061}
10062
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010063static void
10064CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
10065 bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010066 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +000010067
John McCallcc7e5bf2010-05-06 08:58:33 +000010068 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
10069 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
10070 if (Source == Target) return;
10071 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +000010072
Chandler Carruthc22845a2011-07-26 05:40:03 +000010073 // If the conversion context location is invalid don't complain. We also
10074 // don't want to emit a warning if the issue occurs from the expansion of
10075 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
10076 // delay this check as long as possible. Once we detect we are in that
10077 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010078 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +000010079 return;
10080
Richard Trieu021baa32011-09-23 20:10:00 +000010081 // Diagnose implicit casts to bool.
10082 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
10083 if (isa<StringLiteral>(E))
10084 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +000010085 // and expressions, for instance, assert(0 && "error here"), are
10086 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +000010087 return DiagnoseImpCast(S, E, T, CC,
10088 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +000010089 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
10090 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
10091 // This covers the literal expressions that evaluate to Objective-C
10092 // objects.
10093 return DiagnoseImpCast(S, E, T, CC,
10094 diag::warn_impcast_objective_c_literal_to_bool);
10095 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010096 if (Source->isPointerType() || Source->canDecayToPointerType()) {
10097 // Warn on pointer to bool conversion that is always true.
10098 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
10099 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +000010100 }
Richard Trieu021baa32011-09-23 20:10:00 +000010101 }
John McCall263a48b2010-01-04 23:31:57 +000010102
Douglas Gregor5054cb02015-07-07 03:58:22 +000010103 // Check implicit casts from Objective-C collection literals to specialized
10104 // collection types, e.g., NSArray<NSString *> *.
10105 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
10106 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
10107 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
10108 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
10109
John McCall263a48b2010-01-04 23:31:57 +000010110 // Strip vector types.
10111 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010112 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010113 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010114 return;
John McCallacf0ee52010-10-08 02:01:28 +000010115 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010116 }
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010117
Chris Lattneree7286f2011-06-14 04:51:15 +000010118 // If the vector cast is cast between two vectors of the same size, it is
10119 // a bitcast, not a conversion.
10120 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
10121 return;
John McCall263a48b2010-01-04 23:31:57 +000010122
10123 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
10124 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
10125 }
Stephen Canon3ba640d2014-04-03 10:33:25 +000010126 if (auto VecTy = dyn_cast<VectorType>(Target))
10127 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +000010128
10129 // Strip complex types.
10130 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010131 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +000010132 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010133 return;
10134
Tim Northover02416372017-08-08 23:18:05 +000010135 return DiagnoseImpCast(S, E, T, CC,
10136 S.getLangOpts().CPlusPlus
10137 ? diag::err_impcast_complex_scalar
10138 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010139 }
John McCall263a48b2010-01-04 23:31:57 +000010140
10141 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
10142 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
10143 }
10144
10145 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
10146 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
10147
10148 // If the source is floating point...
10149 if (SourceBT && SourceBT->isFloatingPoint()) {
10150 // ...and the target is floating point...
10151 if (TargetBT && TargetBT->isFloatingPoint()) {
10152 // ...then warn if we're dropping FP rank.
10153
10154 // Builtin FP kinds are ordered by increasing FP rank.
10155 if (SourceBT->getKind() > TargetBT->getKind()) {
10156 // Don't warn about float constants that are precisely
10157 // representable in the target type.
10158 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +000010159 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +000010160 // Value might be a float, a float vector, or a float complex.
10161 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +000010162 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
10163 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +000010164 return;
10165 }
10166
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010167 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010168 return;
10169
John McCallacf0ee52010-10-08 02:01:28 +000010170 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +000010171 }
10172 // ... or possibly if we're increasing rank, too
10173 else if (TargetBT->getKind() > SourceBT->getKind()) {
10174 if (S.SourceMgr.isInSystemMacro(CC))
10175 return;
10176
10177 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +000010178 }
10179 return;
10180 }
10181
Richard Trieube234c32016-04-21 21:04:55 +000010182 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +000010183 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010184 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010185 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +000010186
Richard Trieube234c32016-04-21 21:04:55 +000010187 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +000010188 }
John McCall263a48b2010-01-04 23:31:57 +000010189
Richard Smith54894fd2015-12-30 01:06:52 +000010190 // Detect the case where a call result is converted from floating-point to
10191 // to bool, and the final argument to the call is converted from bool, to
10192 // discover this typo:
10193 //
10194 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
10195 //
10196 // FIXME: This is an incredibly special case; is there some more general
10197 // way to detect this class of misplaced-parentheses bug?
10198 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010199 // Check last argument of function call to see if it is an
10200 // implicit cast from a type matching the type the result
10201 // is being cast to.
10202 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +000010203 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010204 Expr *LastA = CEx->getArg(NumArgs - 1);
10205 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +000010206 if (isa<ImplicitCastExpr>(LastA) &&
10207 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010208 // Warn on this floating-point to bool conversion
10209 DiagnoseImpCast(S, E, T, CC,
10210 diag::warn_impcast_floating_point_to_bool);
10211 }
10212 }
10213 }
John McCall263a48b2010-01-04 23:31:57 +000010214 return;
10215 }
10216
Richard Trieu5b993502014-10-15 03:42:06 +000010217 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +000010218
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010219 S.DiscardMisalignedMemberAddress(Target, E);
10220
David Blaikie9366d2b2012-06-19 21:19:06 +000010221 if (!Source->isIntegerType() || !Target->isIntegerType())
10222 return;
10223
David Blaikie7555b6a2012-05-15 16:56:36 +000010224 // TODO: remove this early return once the false positives for constant->bool
10225 // in templates, macros, etc, are reduced or removed.
10226 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
10227 return;
10228
John McCallcc7e5bf2010-05-06 08:58:33 +000010229 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +000010230 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +000010231
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010232 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +000010233 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010234 // TODO: this should happen for bitfield stores, too.
10235 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +000010236 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010237 if (S.SourceMgr.isInSystemMacro(CC))
10238 return;
10239
John McCall18a2c2c2010-11-09 22:22:12 +000010240 std::string PrettySourceValue = Value.toString(10);
10241 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010242
Ted Kremenek33ba9952011-10-22 02:37:33 +000010243 S.DiagRuntimeBehavior(E->getExprLoc(), E,
10244 S.PDiag(diag::warn_impcast_integer_precision_constant)
10245 << PrettySourceValue << PrettyTargetValue
10246 << E->getType() << T << E->getSourceRange()
10247 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +000010248 return;
10249 }
10250
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010251 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
10252 if (S.SourceMgr.isInSystemMacro(CC))
10253 return;
10254
David Blaikie9455da02012-04-12 22:40:54 +000010255 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +000010256 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
10257 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +000010258 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +000010259 }
10260
Richard Trieudcb55572016-01-29 23:51:16 +000010261 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
10262 SourceRange.NonNegative && Source->isSignedIntegerType()) {
10263 // Warn when doing a signed to signed conversion, warn if the positive
10264 // source value is exactly the width of the target type, which will
10265 // cause a negative value to be stored.
10266
10267 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +000010268 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
10269 !S.SourceMgr.isInSystemMacro(CC)) {
10270 if (isSameWidthConstantConversion(S, E, T, CC)) {
10271 std::string PrettySourceValue = Value.toString(10);
10272 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +000010273
Richard Trieufc404c72016-02-05 23:02:38 +000010274 S.DiagRuntimeBehavior(
10275 E->getExprLoc(), E,
10276 S.PDiag(diag::warn_impcast_integer_precision_constant)
10277 << PrettySourceValue << PrettyTargetValue << E->getType() << T
10278 << E->getSourceRange() << clang::SourceRange(CC));
10279 return;
Richard Trieudcb55572016-01-29 23:51:16 +000010280 }
10281 }
Richard Trieufc404c72016-02-05 23:02:38 +000010282
Richard Trieudcb55572016-01-29 23:51:16 +000010283 // Fall through for non-constants to give a sign conversion warning.
10284 }
10285
John McCallcc7e5bf2010-05-06 08:58:33 +000010286 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
10287 (!TargetRange.NonNegative && SourceRange.NonNegative &&
10288 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010289 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010290 return;
10291
John McCallcc7e5bf2010-05-06 08:58:33 +000010292 unsigned DiagID = diag::warn_impcast_integer_sign;
10293
10294 // Traditionally, gcc has warned about this under -Wsign-compare.
10295 // We also want to warn about it in -Wconversion.
10296 // So if -Wconversion is off, use a completely identical diagnostic
10297 // in the sign-compare group.
10298 // The conditional-checking code will
10299 if (ICContext) {
10300 DiagID = diag::warn_impcast_integer_sign_conditional;
10301 *ICContext = true;
10302 }
10303
John McCallacf0ee52010-10-08 02:01:28 +000010304 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +000010305 }
10306
Douglas Gregora78f1932011-02-22 02:45:07 +000010307 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +000010308 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
10309 // type, to give us better diagnostics.
10310 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000010311 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +000010312 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10313 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
10314 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
10315 SourceType = S.Context.getTypeDeclType(Enum);
10316 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
10317 }
10318 }
10319
Douglas Gregora78f1932011-02-22 02:45:07 +000010320 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
10321 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +000010322 if (SourceEnum->getDecl()->hasNameForLinkage() &&
10323 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010324 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010325 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010326 return;
10327
Douglas Gregor364f7db2011-03-12 00:14:31 +000010328 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +000010329 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010330 }
John McCall263a48b2010-01-04 23:31:57 +000010331}
10332
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010333static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10334 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010335
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010336static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
10337 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010338 E = E->IgnoreParenImpCasts();
10339
10340 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +000010341 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010342
John McCallacf0ee52010-10-08 02:01:28 +000010343 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010344 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000010345 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +000010346}
10347
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010348static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10349 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +000010350 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +000010351
10352 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +000010353 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
10354 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000010355
10356 // If -Wconversion would have warned about either of the candidates
10357 // for a signedness conversion to the context type...
10358 if (!Suspicious) return;
10359
10360 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010361 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +000010362 return;
10363
John McCallcc7e5bf2010-05-06 08:58:33 +000010364 // ...then check whether it would have warned about either of the
10365 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +000010366 if (E->getType() == T) return;
10367
10368 Suspicious = false;
10369 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
10370 E->getType(), CC, &Suspicious);
10371 if (!Suspicious)
10372 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +000010373 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000010374}
10375
Richard Trieu65724892014-11-15 06:37:39 +000010376/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10377/// Input argument E is a logical expression.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010378static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +000010379 if (S.getLangOpts().Bool)
10380 return;
10381 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
10382}
10383
John McCallcc7e5bf2010-05-06 08:58:33 +000010384/// AnalyzeImplicitConversions - Find and report any interesting
10385/// implicit conversions in the given expression. There are a couple
10386/// of competing diagnostics here, -Wconversion and -Wsign-compare.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010387static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
10388 SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +000010389 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +000010390 Expr *E = OrigE->IgnoreParenImpCasts();
10391
Douglas Gregor6e8da6a2011-10-10 17:38:18 +000010392 if (E->isTypeDependent() || E->isValueDependent())
10393 return;
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010394
John McCallcc7e5bf2010-05-06 08:58:33 +000010395 // For conditional operators, we analyze the arguments as if they
10396 // were being fed directly into the output.
10397 if (isa<ConditionalOperator>(E)) {
10398 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +000010399 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010400 return;
10401 }
10402
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010403 // Check implicit argument conversions for function calls.
10404 if (CallExpr *Call = dyn_cast<CallExpr>(E))
10405 CheckImplicitArgumentConversions(S, Call, CC);
10406
John McCallcc7e5bf2010-05-06 08:58:33 +000010407 // Go ahead and check any implicit conversions we might have skipped.
10408 // The non-canonical typecheck is just an optimization;
10409 // CheckImplicitConversion will filter out dead implicit conversions.
10410 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000010411 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010412
10413 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +000010414
10415 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
10416 // The bound subexpressions in a PseudoObjectExpr are not reachable
10417 // as transitive children.
10418 // FIXME: Use a more uniform representation for this.
10419 for (auto *SE : POE->semantics())
10420 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
10421 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +000010422 }
Richard Smithd7bed4d2015-11-22 02:57:17 +000010423
John McCallcc7e5bf2010-05-06 08:58:33 +000010424 // Skip past explicit casts.
10425 if (isa<ExplicitCastExpr>(E)) {
10426 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +000010427 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010428 }
10429
John McCalld2a53122010-11-09 23:24:47 +000010430 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10431 // Do a somewhat different check with comparison operators.
10432 if (BO->isComparisonOp())
10433 return AnalyzeComparison(S, BO);
10434
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010435 // And with simple assignments.
10436 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +000010437 return AnalyzeAssignment(S, BO);
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010438 // And with compound assignments.
10439 if (BO->isAssignmentOp())
10440 return AnalyzeCompoundAssignment(S, BO);
John McCalld2a53122010-11-09 23:24:47 +000010441 }
John McCallcc7e5bf2010-05-06 08:58:33 +000010442
10443 // These break the otherwise-useful invariant below. Fortunately,
10444 // we don't really need to recurse into them, because any internal
10445 // expressions should have been analyzed already when they were
10446 // built into statements.
10447 if (isa<StmtExpr>(E)) return;
10448
10449 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +000010450 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +000010451
10452 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +000010453 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +000010454 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +000010455 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +000010456 for (Stmt *SubStmt : E->children()) {
10457 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +000010458 if (!ChildExpr)
10459 continue;
10460
Richard Trieu955231d2014-01-25 01:10:35 +000010461 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +000010462 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +000010463 // Ignore checking string literals that are in logical and operators.
10464 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +000010465 continue;
10466 AnalyzeImplicitConversions(S, ChildExpr, CC);
10467 }
Richard Trieu791b86e2014-11-19 06:08:18 +000010468
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010469 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +000010470 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
10471 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000010472 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +000010473
10474 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
10475 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000010476 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010477 }
Richard Trieu791b86e2014-11-19 06:08:18 +000010478
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010479 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
10480 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +000010481 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010482}
10483
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000010484/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000010485static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
10486 // Taking into account implicit conversions,
10487 // allow any integer.
10488 if (!E->getType()->isIntegerType()) {
10489 S.Diag(E->getLocStart(),
10490 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
10491 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010492 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000010493 // Potentially emit standard warnings for implicit conversions if enabled
10494 // using -Wconversion.
10495 CheckImplicitConversion(S, E, IntT, E->getLocStart());
10496 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010497}
10498
Richard Trieuc1888e02014-06-28 23:25:37 +000010499// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
10500// Returns true when emitting a warning about taking the address of a reference.
10501static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +000010502 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +000010503 E = E->IgnoreParenImpCasts();
10504
10505 const FunctionDecl *FD = nullptr;
10506
10507 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10508 if (!DRE->getDecl()->getType()->isReferenceType())
10509 return false;
10510 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10511 if (!M->getMemberDecl()->getType()->isReferenceType())
10512 return false;
10513 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +000010514 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +000010515 return false;
10516 FD = Call->getDirectCallee();
10517 } else {
10518 return false;
10519 }
10520
10521 SemaRef.Diag(E->getExprLoc(), PD);
10522
10523 // If possible, point to location of function.
10524 if (FD) {
10525 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
10526 }
10527
10528 return true;
10529}
10530
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010531// Returns true if the SourceLocation is expanded from any macro body.
10532// Returns false if the SourceLocation is invalid, is from not in a macro
10533// expansion, or is from expanded from a top-level macro argument.
10534static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
10535 if (Loc.isInvalid())
10536 return false;
10537
10538 while (Loc.isMacroID()) {
10539 if (SM.isMacroBodyExpansion(Loc))
10540 return true;
10541 Loc = SM.getImmediateMacroCallerLoc(Loc);
10542 }
10543
10544 return false;
10545}
10546
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010547/// Diagnose pointers that are always non-null.
Richard Trieu3bb8b562014-02-26 02:36:06 +000010548/// \param E the expression containing the pointer
10549/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
10550/// compared to a null pointer
10551/// \param IsEqual True when the comparison is equal to a null pointer
10552/// \param Range Extra SourceRange to highlight in the diagnostic
10553void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
10554 Expr::NullPointerConstantKind NullKind,
10555 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +000010556 if (!E)
10557 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010558
10559 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010560 if (E->getExprLoc().isMacroID()) {
10561 const SourceManager &SM = getSourceManager();
10562 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10563 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +000010564 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010565 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010566 E = E->IgnoreImpCasts();
10567
10568 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10569
Richard Trieuf7432752014-06-06 21:39:26 +000010570 if (isa<CXXThisExpr>(E)) {
10571 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10572 : diag::warn_this_bool_conversion;
10573 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10574 return;
10575 }
10576
Richard Trieu3bb8b562014-02-26 02:36:06 +000010577 bool IsAddressOf = false;
10578
10579 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10580 if (UO->getOpcode() != UO_AddrOf)
10581 return;
10582 IsAddressOf = true;
10583 E = UO->getSubExpr();
10584 }
10585
Richard Trieuc1888e02014-06-28 23:25:37 +000010586 if (IsAddressOf) {
10587 unsigned DiagID = IsCompare
10588 ? diag::warn_address_of_reference_null_compare
10589 : diag::warn_address_of_reference_bool_conversion;
10590 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10591 << IsEqual;
10592 if (CheckForReference(*this, E, PD)) {
10593 return;
10594 }
10595 }
10596
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010597 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10598 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +000010599 std::string Str;
10600 llvm::raw_string_ostream S(Str);
10601 E->printPretty(S, nullptr, getPrintingPolicy());
10602 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10603 : diag::warn_cast_nonnull_to_bool;
10604 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10605 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010606 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +000010607 };
10608
10609 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10610 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10611 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010612 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10613 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010614 return;
10615 }
10616 }
10617 }
10618
Richard Trieu3bb8b562014-02-26 02:36:06 +000010619 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +000010620 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010621 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10622 D = R->getDecl();
10623 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10624 D = M->getMemberDecl();
10625 }
10626
10627 // Weak Decls can be null.
10628 if (!D || D->isWeak())
10629 return;
George Burgess IV850269a2015-12-08 22:02:00 +000010630
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010631 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +000010632 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10633 if (getCurFunction() &&
10634 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010635 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10636 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010637 return;
10638 }
10639
10640 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +000010641 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +000010642 assert(ParamIter != FD->param_end());
10643 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10644
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010645 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10646 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010647 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000010648 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010649 }
George Burgess IV850269a2015-12-08 22:02:00 +000010650
Joel E. Denny81508102018-03-13 14:51:22 +000010651 for (const ParamIdx &ArgNo : NonNull->args()) {
10652 if (ArgNo.getASTIndex() == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010653 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010654 return;
10655 }
George Burgess IV850269a2015-12-08 22:02:00 +000010656 }
10657 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010658 }
10659 }
George Burgess IV850269a2015-12-08 22:02:00 +000010660 }
10661
Richard Trieu3bb8b562014-02-26 02:36:06 +000010662 QualType T = D->getType();
10663 const bool IsArray = T->isArrayType();
10664 const bool IsFunction = T->isFunctionType();
10665
Richard Trieuc1888e02014-06-28 23:25:37 +000010666 // Address of function is used to silence the function warning.
10667 if (IsAddressOf && IsFunction) {
10668 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010669 }
10670
10671 // Found nothing.
10672 if (!IsAddressOf && !IsFunction && !IsArray)
10673 return;
10674
10675 // Pretty print the expression for the diagnostic.
10676 std::string Str;
10677 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000010678 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000010679
10680 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10681 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000010682 enum {
10683 AddressOf,
10684 FunctionPointer,
10685 ArrayPointer
10686 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010687 if (IsAddressOf)
10688 DiagType = AddressOf;
10689 else if (IsFunction)
10690 DiagType = FunctionPointer;
10691 else if (IsArray)
10692 DiagType = ArrayPointer;
10693 else
10694 llvm_unreachable("Could not determine diagnostic.");
10695 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10696 << Range << IsEqual;
10697
10698 if (!IsFunction)
10699 return;
10700
10701 // Suggest '&' to silence the function warning.
10702 Diag(E->getExprLoc(), diag::note_function_warning_silence)
10703 << FixItHint::CreateInsertion(E->getLocStart(), "&");
10704
10705 // Check to see if '()' fixit should be emitted.
10706 QualType ReturnType;
10707 UnresolvedSet<4> NonTemplateOverloads;
10708 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10709 if (ReturnType.isNull())
10710 return;
10711
10712 if (IsCompare) {
10713 // There are two cases here. If there is null constant, the only suggest
10714 // for a pointer return type. If the null is 0, then suggest if the return
10715 // type is a pointer or an integer type.
10716 if (!ReturnType->isPointerType()) {
10717 if (NullKind == Expr::NPCK_ZeroExpression ||
10718 NullKind == Expr::NPCK_ZeroLiteral) {
10719 if (!ReturnType->isIntegerType())
10720 return;
10721 } else {
10722 return;
10723 }
10724 }
10725 } else { // !IsCompare
10726 // For function to bool, only suggest if the function pointer has bool
10727 // return type.
10728 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10729 return;
10730 }
10731 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +000010732 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000010733}
10734
John McCallcc7e5bf2010-05-06 08:58:33 +000010735/// Diagnoses "dangerous" implicit conversions within the given
10736/// expression (which is a full expression). Implements -Wconversion
10737/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000010738///
10739/// \param CC the "context" location of the implicit conversion, i.e.
10740/// the most location of the syntactic entity requiring the implicit
10741/// conversion
10742void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010743 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000010744 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000010745 return;
10746
10747 // Don't diagnose for value- or type-dependent expressions.
10748 if (E->isTypeDependent() || E->isValueDependent())
10749 return;
10750
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010751 // Check for array bounds violations in cases where the check isn't triggered
10752 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10753 // ArraySubscriptExpr is on the RHS of a variable initialization.
10754 CheckArrayAccess(E);
10755
John McCallacf0ee52010-10-08 02:01:28 +000010756 // This is not the right CC for (e.g.) a variable initialization.
10757 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010758}
10759
Richard Trieu65724892014-11-15 06:37:39 +000010760/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10761/// Input argument E is a logical expression.
10762void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10763 ::CheckBoolLikeConversion(*this, E, CC);
10764}
10765
Richard Smith9f7df0c2017-06-26 23:19:32 +000010766/// Diagnose when expression is an integer constant expression and its evaluation
10767/// results in integer overflow
10768void Sema::CheckForIntOverflow (Expr *E) {
10769 // Use a work list to deal with nested struct initializers.
10770 SmallVector<Expr *, 2> Exprs(1, E);
10771
10772 do {
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010773 Expr *OriginalE = Exprs.pop_back_val();
10774 Expr *E = OriginalE->IgnoreParenCasts();
Richard Smith9f7df0c2017-06-26 23:19:32 +000010775
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010776 if (isa<BinaryOperator>(E)) {
10777 E->EvaluateForOverflow(Context);
Richard Smith9f7df0c2017-06-26 23:19:32 +000010778 continue;
10779 }
10780
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010781 if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
Richard Smith9f7df0c2017-06-26 23:19:32 +000010782 Exprs.append(InitList->inits().begin(), InitList->inits().end());
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010783 else if (isa<ObjCBoxedExpr>(OriginalE))
10784 E->EvaluateForOverflow(Context);
10785 else if (auto Call = dyn_cast<CallExpr>(E))
10786 Exprs.append(Call->arg_begin(), Call->arg_end());
10787 else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
10788 Exprs.append(Message->arg_begin(), Message->arg_end());
Richard Smith9f7df0c2017-06-26 23:19:32 +000010789 } while (!Exprs.empty());
10790}
10791
Richard Smithc406cb72013-01-17 01:17:56 +000010792namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010793
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010794/// Visitor for expressions which looks for unsequenced operations on the
Richard Smithc406cb72013-01-17 01:17:56 +000010795/// same object.
10796class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010797 using Base = EvaluatedExprVisitor<SequenceChecker>;
Richard Smithe3dbfe02013-06-30 10:40:20 +000010798
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010799 /// A tree of sequenced regions within an expression. Two regions are
Richard Smithc406cb72013-01-17 01:17:56 +000010800 /// unsequenced if one is an ancestor or a descendent of the other. When we
10801 /// finish processing an expression with sequencing, such as a comma
10802 /// expression, we fold its tree nodes into its parent, since they are
10803 /// unsequenced with respect to nodes we will visit later.
10804 class SequenceTree {
10805 struct Value {
10806 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10807 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000010808 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000010809 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010810 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000010811
10812 public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010813 /// A region within an expression which may be sequenced with respect
Richard Smithc406cb72013-01-17 01:17:56 +000010814 /// to some other region.
10815 class Seq {
Richard Smithc406cb72013-01-17 01:17:56 +000010816 friend class SequenceTree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010817
10818 unsigned Index = 0;
10819
10820 explicit Seq(unsigned N) : Index(N) {}
10821
Richard Smithc406cb72013-01-17 01:17:56 +000010822 public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010823 Seq() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010824 };
10825
10826 SequenceTree() { Values.push_back(Value(0)); }
10827 Seq root() const { return Seq(0); }
10828
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010829 /// Create a new sequence of operations, which is an unsequenced
Richard Smithc406cb72013-01-17 01:17:56 +000010830 /// subset of \p Parent. This sequence of operations is sequenced with
10831 /// respect to other children of \p Parent.
10832 Seq allocate(Seq Parent) {
10833 Values.push_back(Value(Parent.Index));
10834 return Seq(Values.size() - 1);
10835 }
10836
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010837 /// Merge a sequence of operations into its parent.
Richard Smithc406cb72013-01-17 01:17:56 +000010838 void merge(Seq S) {
10839 Values[S.Index].Merged = true;
10840 }
10841
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010842 /// Determine whether two operations are unsequenced. This operation
Richard Smithc406cb72013-01-17 01:17:56 +000010843 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10844 /// should have been merged into its parent as appropriate.
10845 bool isUnsequenced(Seq Cur, Seq Old) {
10846 unsigned C = representative(Cur.Index);
10847 unsigned Target = representative(Old.Index);
10848 while (C >= Target) {
10849 if (C == Target)
10850 return true;
10851 C = Values[C].Parent;
10852 }
10853 return false;
10854 }
10855
10856 private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010857 /// Pick a representative for a sequence.
Richard Smithc406cb72013-01-17 01:17:56 +000010858 unsigned representative(unsigned K) {
10859 if (Values[K].Merged)
10860 // Perform path compression as we go.
10861 return Values[K].Parent = representative(Values[K].Parent);
10862 return K;
10863 }
10864 };
10865
10866 /// An object for which we can track unsequenced uses.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010867 using Object = NamedDecl *;
Richard Smithc406cb72013-01-17 01:17:56 +000010868
10869 /// Different flavors of object usage which we track. We only track the
10870 /// least-sequenced usage of each kind.
10871 enum UsageKind {
10872 /// A read of an object. Multiple unsequenced reads are OK.
10873 UK_Use,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010874
Richard Smithc406cb72013-01-17 01:17:56 +000010875 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010876 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010877 UK_ModAsValue,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010878
Richard Smithc406cb72013-01-17 01:17:56 +000010879 /// A modification of an object which is not sequenced before the value
10880 /// computation of the expression, such as n++.
10881 UK_ModAsSideEffect,
10882
10883 UK_Count = UK_ModAsSideEffect + 1
10884 };
10885
10886 struct Usage {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010887 Expr *Use = nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010888 SequenceTree::Seq Seq;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010889
10890 Usage() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010891 };
10892
10893 struct UsageInfo {
Richard Smithc406cb72013-01-17 01:17:56 +000010894 Usage Uses[UK_Count];
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010895
Richard Smithc406cb72013-01-17 01:17:56 +000010896 /// Have we issued a diagnostic for this variable already?
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010897 bool Diagnosed = false;
10898
10899 UsageInfo() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010900 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010901 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
Richard Smithc406cb72013-01-17 01:17:56 +000010902
10903 Sema &SemaRef;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010904
Richard Smithc406cb72013-01-17 01:17:56 +000010905 /// Sequenced regions within the expression.
10906 SequenceTree Tree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010907
Richard Smithc406cb72013-01-17 01:17:56 +000010908 /// Declaration modifications and references which we have seen.
10909 UsageInfoMap UsageMap;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010910
Richard Smithc406cb72013-01-17 01:17:56 +000010911 /// The region we are currently within.
10912 SequenceTree::Seq Region;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010913
Richard Smithc406cb72013-01-17 01:17:56 +000010914 /// Filled in with declarations which were modified as a side-effect
10915 /// (that is, post-increment operations).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010916 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
10917
Richard Smithd33f5202013-01-17 23:18:09 +000010918 /// Expressions to check later. We defer checking these to reduce
10919 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010920 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010921
10922 /// RAII object wrapping the visitation of a sequenced subexpression of an
10923 /// expression. At the end of this process, the side-effects of the evaluation
10924 /// become sequenced with respect to the value computation of the result, so
10925 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10926 /// UK_ModAsValue.
10927 struct SequencedSubexpression {
10928 SequencedSubexpression(SequenceChecker &Self)
10929 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10930 Self.ModAsSideEffect = &ModAsSideEffect;
10931 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010932
Richard Smithc406cb72013-01-17 01:17:56 +000010933 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000010934 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10935 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000010936 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000010937 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10938 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000010939 }
10940 Self.ModAsSideEffect = OldModAsSideEffect;
10941 }
10942
10943 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010944 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010945 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000010946 };
10947
Richard Smith40238f02013-06-20 22:21:56 +000010948 /// RAII object wrapping the visitation of a subexpression which we might
10949 /// choose to evaluate as a constant. If any subexpression is evaluated and
10950 /// found to be non-constant, this allows us to suppress the evaluation of
10951 /// the outer expression.
10952 class EvaluationTracker {
10953 public:
10954 EvaluationTracker(SequenceChecker &Self)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010955 : Self(Self), Prev(Self.EvalTracker) {
Richard Smith40238f02013-06-20 22:21:56 +000010956 Self.EvalTracker = this;
10957 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010958
Richard Smith40238f02013-06-20 22:21:56 +000010959 ~EvaluationTracker() {
10960 Self.EvalTracker = Prev;
10961 if (Prev)
10962 Prev->EvalOK &= EvalOK;
10963 }
10964
10965 bool evaluate(const Expr *E, bool &Result) {
10966 if (!EvalOK || E->isValueDependent())
10967 return false;
10968 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10969 return EvalOK;
10970 }
10971
10972 private:
10973 SequenceChecker &Self;
10974 EvaluationTracker *Prev;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010975 bool EvalOK = true;
10976 } *EvalTracker = nullptr;
Richard Smith40238f02013-06-20 22:21:56 +000010977
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010978 /// Find the object which is produced by the specified expression,
Richard Smithc406cb72013-01-17 01:17:56 +000010979 /// if any.
10980 Object getObject(Expr *E, bool Mod) const {
10981 E = E->IgnoreParenCasts();
10982 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10983 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10984 return getObject(UO->getSubExpr(), Mod);
10985 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10986 if (BO->getOpcode() == BO_Comma)
10987 return getObject(BO->getRHS(), Mod);
10988 if (Mod && BO->isAssignmentOp())
10989 return getObject(BO->getLHS(), Mod);
10990 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10991 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10992 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10993 return ME->getMemberDecl();
10994 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10995 // FIXME: If this is a reference, map through to its value.
10996 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000010997 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010998 }
10999
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011000 /// Note that an object was modified or used by an expression.
Richard Smithc406cb72013-01-17 01:17:56 +000011001 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
11002 Usage &U = UI.Uses[UK];
11003 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
11004 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
11005 ModAsSideEffect->push_back(std::make_pair(O, U));
11006 U.Use = Ref;
11007 U.Seq = Region;
11008 }
11009 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011010
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011011 /// Check whether a modification or use conflicts with a prior usage.
Richard Smithc406cb72013-01-17 01:17:56 +000011012 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
11013 bool IsModMod) {
11014 if (UI.Diagnosed)
11015 return;
11016
11017 const Usage &U = UI.Uses[OtherKind];
11018 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
11019 return;
11020
11021 Expr *Mod = U.Use;
11022 Expr *ModOrUse = Ref;
11023 if (OtherKind == UK_Use)
11024 std::swap(Mod, ModOrUse);
11025
11026 SemaRef.Diag(Mod->getExprLoc(),
11027 IsModMod ? diag::warn_unsequenced_mod_mod
11028 : diag::warn_unsequenced_mod_use)
11029 << O << SourceRange(ModOrUse->getExprLoc());
11030 UI.Diagnosed = true;
11031 }
11032
11033 void notePreUse(Object O, Expr *Use) {
11034 UsageInfo &U = UsageMap[O];
11035 // Uses conflict with other modifications.
11036 checkUsage(O, U, Use, UK_ModAsValue, false);
11037 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011038
Richard Smithc406cb72013-01-17 01:17:56 +000011039 void notePostUse(Object O, Expr *Use) {
11040 UsageInfo &U = UsageMap[O];
11041 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
11042 addUsage(U, O, Use, UK_Use);
11043 }
11044
11045 void notePreMod(Object O, Expr *Mod) {
11046 UsageInfo &U = UsageMap[O];
11047 // Modifications conflict with other modifications and with uses.
11048 checkUsage(O, U, Mod, UK_ModAsValue, true);
11049 checkUsage(O, U, Mod, UK_Use, false);
11050 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011051
Richard Smithc406cb72013-01-17 01:17:56 +000011052 void notePostMod(Object O, Expr *Use, UsageKind UK) {
11053 UsageInfo &U = UsageMap[O];
11054 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
11055 addUsage(U, O, Use, UK);
11056 }
11057
11058public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011059 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011060 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
Richard Smithc406cb72013-01-17 01:17:56 +000011061 Visit(E);
11062 }
11063
11064 void VisitStmt(Stmt *S) {
11065 // Skip all statements which aren't expressions for now.
11066 }
11067
11068 void VisitExpr(Expr *E) {
11069 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000011070 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000011071 }
11072
11073 void VisitCastExpr(CastExpr *E) {
11074 Object O = Object();
11075 if (E->getCastKind() == CK_LValueToRValue)
11076 O = getObject(E->getSubExpr(), false);
11077
11078 if (O)
11079 notePreUse(O, E);
11080 VisitExpr(E);
11081 if (O)
11082 notePostUse(O, E);
11083 }
11084
11085 void VisitBinComma(BinaryOperator *BO) {
11086 // C++11 [expr.comma]p1:
11087 // Every value computation and side effect associated with the left
11088 // expression is sequenced before every value computation and side
11089 // effect associated with the right expression.
11090 SequenceTree::Seq LHS = Tree.allocate(Region);
11091 SequenceTree::Seq RHS = Tree.allocate(Region);
11092 SequenceTree::Seq OldRegion = Region;
11093
11094 {
11095 SequencedSubexpression SeqLHS(*this);
11096 Region = LHS;
11097 Visit(BO->getLHS());
11098 }
11099
11100 Region = RHS;
11101 Visit(BO->getRHS());
11102
11103 Region = OldRegion;
11104
11105 // Forget that LHS and RHS are sequenced. They are both unsequenced
11106 // with respect to other stuff.
11107 Tree.merge(LHS);
11108 Tree.merge(RHS);
11109 }
11110
11111 void VisitBinAssign(BinaryOperator *BO) {
11112 // The modification is sequenced after the value computation of the LHS
11113 // and RHS, so check it before inspecting the operands and update the
11114 // map afterwards.
11115 Object O = getObject(BO->getLHS(), true);
11116 if (!O)
11117 return VisitExpr(BO);
11118
11119 notePreMod(O, BO);
11120
11121 // C++11 [expr.ass]p7:
11122 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
11123 // only once.
11124 //
11125 // Therefore, for a compound assignment operator, O is considered used
11126 // everywhere except within the evaluation of E1 itself.
11127 if (isa<CompoundAssignOperator>(BO))
11128 notePreUse(O, BO);
11129
11130 Visit(BO->getLHS());
11131
11132 if (isa<CompoundAssignOperator>(BO))
11133 notePostUse(O, BO);
11134
11135 Visit(BO->getRHS());
11136
Richard Smith83e37bee2013-06-26 23:16:51 +000011137 // C++11 [expr.ass]p1:
11138 // the assignment is sequenced [...] before the value computation of the
11139 // assignment expression.
11140 // C11 6.5.16/3 has no such rule.
11141 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11142 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000011143 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011144
Richard Smithc406cb72013-01-17 01:17:56 +000011145 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
11146 VisitBinAssign(CAO);
11147 }
11148
11149 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11150 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11151 void VisitUnaryPreIncDec(UnaryOperator *UO) {
11152 Object O = getObject(UO->getSubExpr(), true);
11153 if (!O)
11154 return VisitExpr(UO);
11155
11156 notePreMod(O, UO);
11157 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000011158 // C++11 [expr.pre.incr]p1:
11159 // the expression ++x is equivalent to x+=1
11160 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11161 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000011162 }
11163
11164 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11165 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11166 void VisitUnaryPostIncDec(UnaryOperator *UO) {
11167 Object O = getObject(UO->getSubExpr(), true);
11168 if (!O)
11169 return VisitExpr(UO);
11170
11171 notePreMod(O, UO);
11172 Visit(UO->getSubExpr());
11173 notePostMod(O, UO, UK_ModAsSideEffect);
11174 }
11175
11176 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
11177 void VisitBinLOr(BinaryOperator *BO) {
11178 // The side-effects of the LHS of an '&&' are sequenced before the
11179 // value computation of the RHS, and hence before the value computation
11180 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
11181 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000011182 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000011183 {
11184 SequencedSubexpression Sequenced(*this);
11185 Visit(BO->getLHS());
11186 }
11187
11188 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011189 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000011190 if (!Result)
11191 Visit(BO->getRHS());
11192 } else {
11193 // Check for unsequenced operations in the RHS, treating it as an
11194 // entirely separate evaluation.
11195 //
11196 // FIXME: If there are operations in the RHS which are unsequenced
11197 // with respect to operations outside the RHS, and those operations
11198 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000011199 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000011200 }
Richard Smithc406cb72013-01-17 01:17:56 +000011201 }
11202 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000011203 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000011204 {
11205 SequencedSubexpression Sequenced(*this);
11206 Visit(BO->getLHS());
11207 }
11208
11209 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011210 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000011211 if (Result)
11212 Visit(BO->getRHS());
11213 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000011214 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000011215 }
Richard Smithc406cb72013-01-17 01:17:56 +000011216 }
11217
11218 // Only visit the condition, unless we can be sure which subexpression will
11219 // be chosen.
11220 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000011221 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000011222 {
11223 SequencedSubexpression Sequenced(*this);
11224 Visit(CO->getCond());
11225 }
Richard Smithc406cb72013-01-17 01:17:56 +000011226
11227 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011228 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000011229 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000011230 else {
Richard Smithd33f5202013-01-17 23:18:09 +000011231 WorkList.push_back(CO->getTrueExpr());
11232 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000011233 }
Richard Smithc406cb72013-01-17 01:17:56 +000011234 }
11235
Richard Smithe3dbfe02013-06-30 10:40:20 +000011236 void VisitCallExpr(CallExpr *CE) {
11237 // C++11 [intro.execution]p15:
11238 // When calling a function [...], every value computation and side effect
11239 // associated with any argument expression, or with the postfix expression
11240 // designating the called function, is sequenced before execution of every
11241 // expression or statement in the body of the function [and thus before
11242 // the value computation of its result].
11243 SequencedSubexpression Sequenced(*this);
11244 Base::VisitCallExpr(CE);
11245
11246 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
11247 }
11248
Richard Smithc406cb72013-01-17 01:17:56 +000011249 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000011250 // This is a call, so all subexpressions are sequenced before the result.
11251 SequencedSubexpression Sequenced(*this);
11252
Richard Smithc406cb72013-01-17 01:17:56 +000011253 if (!CCE->isListInitialization())
11254 return VisitExpr(CCE);
11255
11256 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011257 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000011258 SequenceTree::Seq Parent = Region;
11259 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
11260 E = CCE->arg_end();
11261 I != E; ++I) {
11262 Region = Tree.allocate(Parent);
11263 Elts.push_back(Region);
11264 Visit(*I);
11265 }
11266
11267 // Forget that the initializers are sequenced.
11268 Region = Parent;
11269 for (unsigned I = 0; I < Elts.size(); ++I)
11270 Tree.merge(Elts[I]);
11271 }
11272
11273 void VisitInitListExpr(InitListExpr *ILE) {
11274 if (!SemaRef.getLangOpts().CPlusPlus11)
11275 return VisitExpr(ILE);
11276
11277 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011278 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000011279 SequenceTree::Seq Parent = Region;
11280 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
11281 Expr *E = ILE->getInit(I);
11282 if (!E) continue;
11283 Region = Tree.allocate(Parent);
11284 Elts.push_back(Region);
11285 Visit(E);
11286 }
11287
11288 // Forget that the initializers are sequenced.
11289 Region = Parent;
11290 for (unsigned I = 0; I < Elts.size(); ++I)
11291 Tree.merge(Elts[I]);
11292 }
11293};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011294
11295} // namespace
Richard Smithc406cb72013-01-17 01:17:56 +000011296
11297void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011298 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000011299 WorkList.push_back(E);
11300 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000011301 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000011302 SequenceChecker(*this, Item, WorkList);
11303 }
Richard Smithc406cb72013-01-17 01:17:56 +000011304}
11305
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011306void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
11307 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000011308 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000011309 if (!E->isInstantiationDependent())
11310 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011311 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000011312 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011313 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000011314}
11315
John McCall1f425642010-11-11 03:21:53 +000011316void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
11317 FieldDecl *BitField,
11318 Expr *Init) {
11319 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
11320}
11321
David Majnemer61a5bbf2015-04-07 22:08:51 +000011322static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
11323 SourceLocation Loc) {
11324 if (!PType->isVariablyModifiedType())
11325 return;
11326 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
11327 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
11328 return;
11329 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000011330 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
11331 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
11332 return;
11333 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000011334 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
11335 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
11336 return;
11337 }
11338
11339 const ArrayType *AT = S.Context.getAsArrayType(PType);
11340 if (!AT)
11341 return;
11342
11343 if (AT->getSizeModifier() != ArrayType::Star) {
11344 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
11345 return;
11346 }
11347
11348 S.Diag(Loc, diag::err_array_star_in_function_definition);
11349}
11350
Mike Stump0c2ec772010-01-21 03:59:47 +000011351/// CheckParmsForFunctionDef - Check that the parameters of the given
11352/// function are appropriate for the definition of a function. This
11353/// takes care of any checks that cannot be performed on the
11354/// declaration itself, e.g., that the types of each of the function
11355/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000011356bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000011357 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011358 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000011359 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011360 // C99 6.7.5.3p4: the parameters in a parameter type list in a
11361 // function declarator that is part of a function definition of
11362 // that function shall not have incomplete type.
11363 //
11364 // This is also C++ [dcl.fct]p6.
11365 if (!Param->isInvalidDecl() &&
11366 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011367 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011368 Param->setInvalidDecl();
11369 HasInvalidParm = true;
11370 }
11371
11372 // C99 6.9.1p5: If the declarator includes a parameter type list, the
11373 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000011374 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000011375 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000011376 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000011377 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000011378 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000011379
11380 // C99 6.7.5.3p12:
11381 // If the function declarator is not part of a definition of that
11382 // function, parameters may have incomplete type and may use the [*]
11383 // notation in their sequences of declarator specifiers to specify
11384 // variable length array types.
11385 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000011386 // FIXME: This diagnostic should point the '[*]' if source-location
11387 // information is added for it.
11388 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000011389
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011390 // If the parameter is a c++ class type and it has to be destructed in the
11391 // callee function, declare the destructor so that it can be called by the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000011392 // callee function. Do not perform any direct access check on the dtor here.
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011393 if (!Param->isInvalidDecl()) {
11394 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
11395 if (!ClassDecl->isInvalidDecl() &&
11396 !ClassDecl->hasIrrelevantDestructor() &&
11397 !ClassDecl->isDependentContext() &&
Akira Hatanaka85282972018-05-15 21:00:30 +000011398 ClassDecl->isParamDestroyedInCallee()) {
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011399 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11400 MarkFunctionReferenced(Param->getLocation(), Destructor);
11401 DiagnoseUseOfDecl(Destructor, Param->getLocation());
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000011402 }
11403 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000011404 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011405
11406 // Parameters with the pass_object_size attribute only need to be marked
11407 // constant at function definitions. Because we lack information about
11408 // whether we're on a declaration or definition when we're instantiating the
11409 // attribute, we need to check for constness here.
11410 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
11411 if (!Param->getType().isConstQualified())
11412 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
11413 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000011414 }
11415
11416 return HasInvalidParm;
11417}
John McCall2b5c1b22010-08-12 21:44:57 +000011418
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000011419/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
11420/// or MemberExpr.
11421static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
11422 ASTContext &Context) {
11423 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
11424 return Context.getDeclAlign(DRE->getDecl());
11425
11426 if (const auto *ME = dyn_cast<MemberExpr>(E))
11427 return Context.getDeclAlign(ME->getMemberDecl());
11428
11429 return TypeAlign;
11430}
11431
John McCall2b5c1b22010-08-12 21:44:57 +000011432/// CheckCastAlign - Implements -Wcast-align, which warns when a
11433/// pointer cast increases the alignment requirements.
11434void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
11435 // This is actually a lot of work to potentially be doing on every
11436 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011437 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000011438 return;
11439
11440 // Ignore dependent types.
11441 if (T->isDependentType() || Op->getType()->isDependentType())
11442 return;
11443
11444 // Require that the destination be a pointer type.
11445 const PointerType *DestPtr = T->getAs<PointerType>();
11446 if (!DestPtr) return;
11447
11448 // If the destination has alignment 1, we're done.
11449 QualType DestPointee = DestPtr->getPointeeType();
11450 if (DestPointee->isIncompleteType()) return;
11451 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
11452 if (DestAlign.isOne()) return;
11453
11454 // Require that the source be a pointer type.
11455 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
11456 if (!SrcPtr) return;
11457 QualType SrcPointee = SrcPtr->getPointeeType();
11458
11459 // Whitelist casts from cv void*. We already implicitly
11460 // whitelisted casts to cv void*, since they have alignment 1.
11461 // Also whitelist casts involving incomplete types, which implicitly
11462 // includes 'void'.
11463 if (SrcPointee->isIncompleteType()) return;
11464
11465 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000011466
11467 if (auto *CE = dyn_cast<CastExpr>(Op)) {
11468 if (CE->getCastKind() == CK_ArrayToPointerDecay)
11469 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
11470 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
11471 if (UO->getOpcode() == UO_AddrOf)
11472 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
11473 }
11474
John McCall2b5c1b22010-08-12 21:44:57 +000011475 if (SrcAlign >= DestAlign) return;
11476
11477 Diag(TRange.getBegin(), diag::warn_cast_align)
11478 << Op->getType() << T
11479 << static_cast<unsigned>(SrcAlign.getQuantity())
11480 << static_cast<unsigned>(DestAlign.getQuantity())
11481 << TRange << Op->getSourceRange();
11482}
11483
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011484/// Check whether this array fits the idiom of a size-one tail padded
Chandler Carruth28389f02011-08-05 09:10:50 +000011485/// array member of a struct.
11486///
11487/// We avoid emitting out-of-bounds access warnings for such arrays as they are
11488/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000011489static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000011490 const NamedDecl *ND) {
11491 if (Size != 1 || !ND) return false;
11492
11493 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
11494 if (!FD) return false;
11495
11496 // Don't consider sizes resulting from macro expansions or template argument
11497 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000011498
11499 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011500 while (TInfo) {
11501 TypeLoc TL = TInfo->getTypeLoc();
11502 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000011503 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
11504 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011505 TInfo = TDL->getTypeSourceInfo();
11506 continue;
11507 }
David Blaikie6adc78e2013-02-18 22:06:02 +000011508 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
11509 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000011510 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
11511 return false;
11512 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011513 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000011514 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011515
11516 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000011517 if (!RD) return false;
11518 if (RD->isUnion()) return false;
11519 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11520 if (!CRD->isStandardLayout()) return false;
11521 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011522
Benjamin Kramer8c543672011-08-06 03:04:42 +000011523 // See if this is the last field decl in the record.
11524 const Decl *D = FD;
11525 while ((D = D->getNextDeclInContext()))
11526 if (isa<FieldDecl>(D))
11527 return false;
11528 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000011529}
11530
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011531void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011532 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000011533 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011534 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011535 if (IndexExpr->isValueDependent())
11536 return;
11537
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011538 const Type *EffectiveType =
11539 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011540 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011541 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011542 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011543 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000011544 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000011545
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011546 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000011547 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000011548 return;
Richard Smith13f67182011-12-16 19:31:14 +000011549 if (IndexNegated)
11550 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000011551
Craig Topperc3ec1492014-05-26 06:22:03 +000011552 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000011553 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011554 ND = DRE->getDecl();
Chandler Carruth28389f02011-08-05 09:10:50 +000011555 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011556 ND = ME->getMemberDecl();
Chandler Carruth126b1552011-08-05 08:07:29 +000011557
Ted Kremeneke4b316c2011-02-23 23:06:04 +000011558 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011559 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000011560 if (!size.isStrictlyPositive())
11561 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011562
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011563 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000011564 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011565 // Make sure we're comparing apples to apples when comparing index to size
11566 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
11567 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000011568 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000011569 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011570 if (ptrarith_typesize != array_typesize) {
11571 // There's a cast to a different size type involved
11572 uint64_t ratio = array_typesize / ptrarith_typesize;
11573 // TODO: Be smarter about handling cases where array_typesize is not a
11574 // multiple of ptrarith_typesize
11575 if (ptrarith_typesize * ratio == array_typesize)
11576 size *= llvm::APInt(size.getBitWidth(), ratio);
11577 }
11578 }
11579
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011580 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011581 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011582 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011583 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011584
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011585 // For array subscripting the index must be less than size, but for pointer
11586 // arithmetic also allow the index (offset) to be equal to size since
11587 // computing the next address after the end of the array is legal and
11588 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011589 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000011590 return;
11591
11592 // Also don't warn for arrays of size 1 which are members of some
11593 // structure. These are often used to approximate flexible arrays in C89
11594 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011595 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000011596 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011597
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011598 // Suppress the warning if the subscript expression (as identified by the
11599 // ']' location) and the index expression are both from macro expansions
11600 // within a system header.
11601 if (ASE) {
11602 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11603 ASE->getRBracketLoc());
11604 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11605 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11606 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000011607 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011608 return;
11609 }
11610 }
11611
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011612 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011613 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011614 DiagID = diag::warn_array_index_exceeds_bounds;
11615
11616 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11617 PDiag(DiagID) << index.toString(10, true)
11618 << size.toString(10, true)
11619 << (unsigned)size.getLimitedValue(~0U)
11620 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011621 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011622 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011623 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011624 DiagID = diag::warn_ptr_arith_precedes_bounds;
11625 if (index.isNegative()) index = -index;
11626 }
11627
11628 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11629 PDiag(DiagID) << index.toString(10, true)
11630 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000011631 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000011632
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011633 if (!ND) {
11634 // Try harder to find a NamedDecl to point at in the note.
11635 while (const ArraySubscriptExpr *ASE =
11636 dyn_cast<ArraySubscriptExpr>(BaseExpr))
11637 BaseExpr = ASE->getBase()->IgnoreParenCasts();
11638 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011639 ND = DRE->getDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011640 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011641 ND = ME->getMemberDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011642 }
11643
Chandler Carruth1af88f12011-02-17 21:10:52 +000011644 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011645 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11646 PDiag(diag::note_array_index_out_of_bounds)
11647 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000011648}
11649
Ted Kremenekdf26df72011-03-01 18:41:00 +000011650void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011651 int AllowOnePastEnd = 0;
11652 while (expr) {
11653 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000011654 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011655 case Stmt::ArraySubscriptExprClass: {
11656 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011657 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011658 AllowOnePastEnd > 0);
Aaron Ballman93c6ba12018-04-24 19:21:04 +000011659 expr = ASE->getBase();
11660 break;
11661 }
11662 case Stmt::MemberExprClass: {
11663 expr = cast<MemberExpr>(expr)->getBase();
11664 break;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011665 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011666 case Stmt::OMPArraySectionExprClass: {
11667 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11668 if (ASE->getLowerBound())
11669 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11670 /*ASE=*/nullptr, AllowOnePastEnd > 0);
11671 return;
11672 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011673 case Stmt::UnaryOperatorClass: {
11674 // Only unwrap the * and & unary operators
11675 const UnaryOperator *UO = cast<UnaryOperator>(expr);
11676 expr = UO->getSubExpr();
11677 switch (UO->getOpcode()) {
11678 case UO_AddrOf:
11679 AllowOnePastEnd++;
11680 break;
11681 case UO_Deref:
11682 AllowOnePastEnd--;
11683 break;
11684 default:
11685 return;
11686 }
11687 break;
11688 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011689 case Stmt::ConditionalOperatorClass: {
11690 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11691 if (const Expr *lhs = cond->getLHS())
11692 CheckArrayAccess(lhs);
11693 if (const Expr *rhs = cond->getRHS())
11694 CheckArrayAccess(rhs);
11695 return;
11696 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000011697 case Stmt::CXXOperatorCallExprClass: {
11698 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11699 for (const auto *Arg : OCE->arguments())
11700 CheckArrayAccess(Arg);
11701 return;
11702 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011703 default:
11704 return;
11705 }
Peter Collingbourne91147592011-04-15 00:35:48 +000011706 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011707}
John McCall31168b02011-06-15 23:02:42 +000011708
11709//===--- CHECK: Objective-C retain cycles ----------------------------------//
11710
11711namespace {
John McCall31168b02011-06-15 23:02:42 +000011712
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011713struct RetainCycleOwner {
11714 VarDecl *Variable = nullptr;
11715 SourceRange Range;
11716 SourceLocation Loc;
11717 bool Indirect = false;
11718
11719 RetainCycleOwner() = default;
11720
11721 void setLocsFrom(Expr *e) {
11722 Loc = e->getExprLoc();
11723 Range = e->getSourceRange();
11724 }
11725};
11726
11727} // namespace
John McCall31168b02011-06-15 23:02:42 +000011728
11729/// Consider whether capturing the given variable can possibly lead to
11730/// a retain cycle.
11731static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000011732 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000011733 // lifetime. In MRR, it's captured strongly if the variable is
11734 // __block and has an appropriate type.
11735 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11736 return false;
11737
11738 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011739 if (ref)
11740 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000011741 return true;
11742}
11743
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011744static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000011745 while (true) {
11746 e = e->IgnoreParens();
11747 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11748 switch (cast->getCastKind()) {
11749 case CK_BitCast:
11750 case CK_LValueBitCast:
11751 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000011752 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000011753 e = cast->getSubExpr();
11754 continue;
11755
John McCall31168b02011-06-15 23:02:42 +000011756 default:
11757 return false;
11758 }
11759 }
11760
11761 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11762 ObjCIvarDecl *ivar = ref->getDecl();
11763 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11764 return false;
11765
11766 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011767 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000011768 return false;
11769
11770 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11771 owner.Indirect = true;
11772 return true;
11773 }
11774
11775 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11776 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11777 if (!var) return false;
11778 return considerVariable(var, ref, owner);
11779 }
11780
John McCall31168b02011-06-15 23:02:42 +000011781 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11782 if (member->isArrow()) return false;
11783
11784 // Don't count this as an indirect ownership.
11785 e = member->getBase();
11786 continue;
11787 }
11788
John McCallfe96e0b2011-11-06 09:01:30 +000011789 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11790 // Only pay attention to pseudo-objects on property references.
11791 ObjCPropertyRefExpr *pre
11792 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11793 ->IgnoreParens());
11794 if (!pre) return false;
11795 if (pre->isImplicitProperty()) return false;
11796 ObjCPropertyDecl *property = pre->getExplicitProperty();
11797 if (!property->isRetaining() &&
11798 !(property->getPropertyIvarDecl() &&
11799 property->getPropertyIvarDecl()->getType()
11800 .getObjCLifetime() == Qualifiers::OCL_Strong))
11801 return false;
11802
11803 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011804 if (pre->isSuperReceiver()) {
11805 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11806 if (!owner.Variable)
11807 return false;
11808 owner.Loc = pre->getLocation();
11809 owner.Range = pre->getSourceRange();
11810 return true;
11811 }
John McCallfe96e0b2011-11-06 09:01:30 +000011812 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11813 ->getSourceExpr());
11814 continue;
11815 }
11816
John McCall31168b02011-06-15 23:02:42 +000011817 // Array ivars?
11818
11819 return false;
11820 }
11821}
11822
11823namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011824
John McCall31168b02011-06-15 23:02:42 +000011825 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011826 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000011827 VarDecl *Variable;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011828 Expr *Capturer = nullptr;
11829 bool VarWillBeReased = false;
11830
11831 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11832 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11833 Context(Context), Variable(variable) {}
John McCall31168b02011-06-15 23:02:42 +000011834
11835 void VisitDeclRefExpr(DeclRefExpr *ref) {
11836 if (ref->getDecl() == Variable && !Capturer)
11837 Capturer = ref;
11838 }
11839
John McCall31168b02011-06-15 23:02:42 +000011840 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11841 if (Capturer) return;
11842 Visit(ref->getBase());
11843 if (Capturer && ref->isFreeIvar())
11844 Capturer = ref;
11845 }
11846
11847 void VisitBlockExpr(BlockExpr *block) {
11848 // Look inside nested blocks
11849 if (block->getBlockDecl()->capturesVariable(Variable))
11850 Visit(block->getBlockDecl()->getBody());
11851 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000011852
11853 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11854 if (Capturer) return;
11855 if (OVE->getSourceExpr())
11856 Visit(OVE->getSourceExpr());
11857 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011858
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011859 void VisitBinaryOperator(BinaryOperator *BinOp) {
11860 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11861 return;
11862 Expr *LHS = BinOp->getLHS();
11863 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11864 if (DRE->getDecl() != Variable)
11865 return;
11866 if (Expr *RHS = BinOp->getRHS()) {
11867 RHS = RHS->IgnoreParenCasts();
11868 llvm::APSInt Value;
11869 VarWillBeReased =
11870 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11871 }
11872 }
11873 }
John McCall31168b02011-06-15 23:02:42 +000011874 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011875
11876} // namespace
John McCall31168b02011-06-15 23:02:42 +000011877
11878/// Check whether the given argument is a block which captures a
11879/// variable.
11880static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11881 assert(owner.Variable && owner.Loc.isValid());
11882
11883 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011884
11885 // Look through [^{...} copy] and Block_copy(^{...}).
11886 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11887 Selector Cmd = ME->getSelector();
11888 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11889 e = ME->getInstanceReceiver();
11890 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011891 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011892 e = e->IgnoreParenCasts();
11893 }
11894 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11895 if (CE->getNumArgs() == 1) {
11896 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011897 if (Fn) {
11898 const IdentifierInfo *FnI = Fn->getIdentifier();
11899 if (FnI && FnI->isStr("_Block_copy")) {
11900 e = CE->getArg(0)->IgnoreParenCasts();
11901 }
11902 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011903 }
11904 }
11905
John McCall31168b02011-06-15 23:02:42 +000011906 BlockExpr *block = dyn_cast<BlockExpr>(e);
11907 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011908 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011909
11910 FindCaptureVisitor visitor(S.Context, owner.Variable);
11911 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011912 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011913}
11914
11915static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11916 RetainCycleOwner &owner) {
11917 assert(capturer);
11918 assert(owner.Variable && owner.Loc.isValid());
11919
11920 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11921 << owner.Variable << capturer->getSourceRange();
11922 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11923 << owner.Indirect << owner.Range;
11924}
11925
11926/// Check for a keyword selector that starts with the word 'add' or
11927/// 'set'.
11928static bool isSetterLikeSelector(Selector sel) {
11929 if (sel.isUnarySelector()) return false;
11930
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011931 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000011932 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011933 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000011934 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011935 else if (str.startswith("add")) {
11936 // Specially whitelist 'addOperationWithBlock:'.
11937 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11938 return false;
11939 str = str.substr(3);
11940 }
John McCall31168b02011-06-15 23:02:42 +000011941 else
11942 return false;
11943
11944 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000011945 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000011946}
11947
Benjamin Kramer3a743452015-03-09 15:03:32 +000011948static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11949 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011950 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11951 Message->getReceiverInterface(),
11952 NSAPI::ClassId_NSMutableArray);
11953 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011954 return None;
11955 }
11956
11957 Selector Sel = Message->getSelector();
11958
11959 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11960 S.NSAPIObj->getNSArrayMethodKind(Sel);
11961 if (!MKOpt) {
11962 return None;
11963 }
11964
11965 NSAPI::NSArrayMethodKind MK = *MKOpt;
11966
11967 switch (MK) {
11968 case NSAPI::NSMutableArr_addObject:
11969 case NSAPI::NSMutableArr_insertObjectAtIndex:
11970 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11971 return 0;
11972 case NSAPI::NSMutableArr_replaceObjectAtIndex:
11973 return 1;
11974
11975 default:
11976 return None;
11977 }
11978
11979 return None;
11980}
11981
11982static
11983Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11984 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011985 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11986 Message->getReceiverInterface(),
11987 NSAPI::ClassId_NSMutableDictionary);
11988 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011989 return None;
11990 }
11991
11992 Selector Sel = Message->getSelector();
11993
11994 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11995 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11996 if (!MKOpt) {
11997 return None;
11998 }
11999
12000 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
12001
12002 switch (MK) {
12003 case NSAPI::NSMutableDict_setObjectForKey:
12004 case NSAPI::NSMutableDict_setValueForKey:
12005 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
12006 return 0;
12007
12008 default:
12009 return None;
12010 }
12011
12012 return None;
12013}
12014
12015static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012016 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
12017 Message->getReceiverInterface(),
12018 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000012019
Alex Denisov5dfac812015-08-06 04:51:14 +000012020 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
12021 Message->getReceiverInterface(),
12022 NSAPI::ClassId_NSMutableOrderedSet);
12023 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012024 return None;
12025 }
12026
12027 Selector Sel = Message->getSelector();
12028
12029 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
12030 if (!MKOpt) {
12031 return None;
12032 }
12033
12034 NSAPI::NSSetMethodKind MK = *MKOpt;
12035
12036 switch (MK) {
12037 case NSAPI::NSMutableSet_addObject:
12038 case NSAPI::NSOrderedSet_setObjectAtIndex:
12039 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
12040 case NSAPI::NSOrderedSet_insertObjectAtIndex:
12041 return 0;
12042 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
12043 return 1;
12044 }
12045
12046 return None;
12047}
12048
12049void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
12050 if (!Message->isInstanceMessage()) {
12051 return;
12052 }
12053
12054 Optional<int> ArgOpt;
12055
12056 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
12057 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
12058 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
12059 return;
12060 }
12061
12062 int ArgIndex = *ArgOpt;
12063
Alex Denisove1d882c2015-03-04 17:55:52 +000012064 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
12065 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
12066 Arg = OE->getSourceExpr()->IgnoreImpCasts();
12067 }
12068
Alex Denisov5dfac812015-08-06 04:51:14 +000012069 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012070 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012071 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012072 Diag(Message->getSourceRange().getBegin(),
12073 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012074 << ArgRE->getDecl() << StringRef("'super'");
Alex Denisove1d882c2015-03-04 17:55:52 +000012075 }
12076 }
Alex Denisov5dfac812015-08-06 04:51:14 +000012077 } else {
12078 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
12079
12080 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
12081 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
12082 }
12083
12084 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
12085 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
12086 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
12087 ValueDecl *Decl = ReceiverRE->getDecl();
12088 Diag(Message->getSourceRange().getBegin(),
12089 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012090 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012091 if (!ArgRE->isObjCSelfExpr()) {
12092 Diag(Decl->getLocation(),
12093 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000012094 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012095 }
12096 }
12097 }
12098 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
12099 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
12100 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
12101 ObjCIvarDecl *Decl = IvarRE->getDecl();
12102 Diag(Message->getSourceRange().getBegin(),
12103 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012104 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012105 Diag(Decl->getLocation(),
12106 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000012107 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012108 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012109 }
12110 }
12111 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012112}
12113
John McCall31168b02011-06-15 23:02:42 +000012114/// Check a message send to see if it's likely to cause a retain cycle.
12115void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
12116 // Only check instance methods whose selector looks like a setter.
12117 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
12118 return;
12119
12120 // Try to find a variable that the receiver is strongly owned by.
12121 RetainCycleOwner owner;
12122 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012123 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000012124 return;
12125 } else {
12126 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
12127 owner.Variable = getCurMethodDecl()->getSelfDecl();
12128 owner.Loc = msg->getSuperLoc();
12129 owner.Range = msg->getSuperLoc();
12130 }
12131
12132 // Check whether the receiver is captured by any of the arguments.
Alex Lorenz42a97a92017-11-17 20:44:25 +000012133 const ObjCMethodDecl *MD = msg->getMethodDecl();
12134 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
12135 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
12136 // noescape blocks should not be retained by the method.
12137 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
12138 continue;
John McCall31168b02011-06-15 23:02:42 +000012139 return diagnoseRetainCycle(*this, capturer, owner);
Alex Lorenz42a97a92017-11-17 20:44:25 +000012140 }
12141 }
John McCall31168b02011-06-15 23:02:42 +000012142}
12143
12144/// Check a property assign to see if it's likely to cause a retain cycle.
12145void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
12146 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012147 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000012148 return;
12149
12150 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
12151 diagnoseRetainCycle(*this, capturer, owner);
12152}
12153
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012154void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
12155 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000012156 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012157 return;
12158
12159 // Because we don't have an expression for the variable, we have to set the
12160 // location explicitly here.
12161 Owner.Loc = Var->getLocation();
12162 Owner.Range = Var->getSourceRange();
12163
12164 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
12165 diagnoseRetainCycle(*this, Capturer, Owner);
12166}
12167
Ted Kremenek9304da92012-12-21 08:04:28 +000012168static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
12169 Expr *RHS, bool isProperty) {
12170 // Check if RHS is an Objective-C object literal, which also can get
12171 // immediately zapped in a weak reference. Note that we explicitly
12172 // allow ObjCStringLiterals, since those are designed to never really die.
12173 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012174
Ted Kremenek64873352012-12-21 22:46:35 +000012175 // This enum needs to match with the 'select' in
12176 // warn_objc_arc_literal_assign (off-by-1).
12177 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
12178 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
12179 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012180
12181 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000012182 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000012183 << (isProperty ? 0 : 1)
12184 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012185
12186 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000012187}
12188
Ted Kremenekc1f014a2012-12-21 19:45:30 +000012189static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
12190 Qualifiers::ObjCLifetime LT,
12191 Expr *RHS, bool isProperty) {
12192 // Strip off any implicit cast added to get to the one ARC-specific.
12193 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
12194 if (cast->getCastKind() == CK_ARCConsumeObject) {
12195 S.Diag(Loc, diag::warn_arc_retained_assign)
12196 << (LT == Qualifiers::OCL_ExplicitNone)
12197 << (isProperty ? 0 : 1)
12198 << RHS->getSourceRange();
12199 return true;
12200 }
12201 RHS = cast->getSubExpr();
12202 }
12203
12204 if (LT == Qualifiers::OCL_Weak &&
12205 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
12206 return true;
12207
12208 return false;
12209}
12210
Ted Kremenekb36234d2012-12-21 08:04:20 +000012211bool Sema::checkUnsafeAssigns(SourceLocation Loc,
12212 QualType LHS, Expr *RHS) {
12213 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
12214
12215 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
12216 return false;
12217
12218 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
12219 return true;
12220
12221 return false;
12222}
12223
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012224void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
12225 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012226 QualType LHSType;
12227 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000012228 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012229 ObjCPropertyRefExpr *PRE
12230 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
12231 if (PRE && !PRE->isImplicitProperty()) {
12232 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12233 if (PD)
12234 LHSType = PD->getType();
12235 }
12236
12237 if (LHSType.isNull())
12238 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000012239
12240 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
12241
12242 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012243 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000012244 getCurFunction()->markSafeWeakUse(LHS);
12245 }
12246
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012247 if (checkUnsafeAssigns(Loc, LHSType, RHS))
12248 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000012249
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012250 // FIXME. Check for other life times.
12251 if (LT != Qualifiers::OCL_None)
12252 return;
12253
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012254 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012255 if (PRE->isImplicitProperty())
12256 return;
12257 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12258 if (!PD)
12259 return;
12260
Bill Wendling44426052012-12-20 19:22:21 +000012261 unsigned Attributes = PD->getPropertyAttributes();
12262 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012263 // when 'assign' attribute was not explicitly specified
12264 // by user, ignore it and rely on property type itself
12265 // for lifetime info.
12266 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
12267 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
12268 LHSType->isObjCRetainableType())
12269 return;
12270
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012271 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000012272 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012273 Diag(Loc, diag::warn_arc_retained_property_assign)
12274 << RHS->getSourceRange();
12275 return;
12276 }
12277 RHS = cast->getSubExpr();
12278 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012279 }
Bill Wendling44426052012-12-20 19:22:21 +000012280 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000012281 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
12282 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000012283 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012284 }
12285}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012286
12287//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
12288
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012289static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
12290 SourceLocation StmtLoc,
12291 const NullStmt *Body) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012292 // Do not warn if the body is a macro that expands to nothing, e.g:
12293 //
12294 // #define CALL(x)
12295 // if (condition)
12296 // CALL(0);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012297 if (Body->hasLeadingEmptyMacro())
12298 return false;
12299
12300 // Get line numbers of statement and body.
12301 bool StmtLineInvalid;
Hans Wennborg95419752017-11-20 17:38:16 +000012302 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012303 &StmtLineInvalid);
12304 if (StmtLineInvalid)
12305 return false;
12306
12307 bool BodyLineInvalid;
12308 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
12309 &BodyLineInvalid);
12310 if (BodyLineInvalid)
12311 return false;
12312
12313 // Warn if null statement and body are on the same line.
12314 if (StmtLine != BodyLine)
12315 return false;
12316
12317 return true;
12318}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012319
12320void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
12321 const Stmt *Body,
12322 unsigned DiagID) {
12323 // Since this is a syntactic check, don't emit diagnostic for template
12324 // instantiations, this just adds noise.
12325 if (CurrentInstantiationScope)
12326 return;
12327
12328 // The body should be a null statement.
12329 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12330 if (!NBody)
12331 return;
12332
12333 // Do the usual checks.
12334 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12335 return;
12336
12337 Diag(NBody->getSemiLoc(), DiagID);
12338 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12339}
12340
12341void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
12342 const Stmt *PossibleBody) {
12343 assert(!CurrentInstantiationScope); // Ensured by caller
12344
12345 SourceLocation StmtLoc;
12346 const Stmt *Body;
12347 unsigned DiagID;
12348 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
12349 StmtLoc = FS->getRParenLoc();
12350 Body = FS->getBody();
12351 DiagID = diag::warn_empty_for_body;
12352 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
12353 StmtLoc = WS->getCond()->getSourceRange().getEnd();
12354 Body = WS->getBody();
12355 DiagID = diag::warn_empty_while_body;
12356 } else
12357 return; // Neither `for' nor `while'.
12358
12359 // The body should be a null statement.
12360 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12361 if (!NBody)
12362 return;
12363
12364 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012365 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012366 return;
12367
12368 // Do the usual checks.
12369 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12370 return;
12371
12372 // `for(...);' and `while(...);' are popular idioms, so in order to keep
12373 // noise level low, emit diagnostics only if for/while is followed by a
12374 // CompoundStmt, e.g.:
12375 // for (int i = 0; i < n; i++);
12376 // {
12377 // a(i);
12378 // }
12379 // or if for/while is followed by a statement with more indentation
12380 // than for/while itself:
12381 // for (int i = 0; i < n; i++);
12382 // a(i);
12383 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
12384 if (!ProbableTypo) {
12385 bool BodyColInvalid;
12386 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
12387 PossibleBody->getLocStart(),
12388 &BodyColInvalid);
12389 if (BodyColInvalid)
12390 return;
12391
12392 bool StmtColInvalid;
12393 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
12394 S->getLocStart(),
12395 &StmtColInvalid);
12396 if (StmtColInvalid)
12397 return;
12398
12399 if (BodyCol > StmtCol)
12400 ProbableTypo = true;
12401 }
12402
12403 if (ProbableTypo) {
12404 Diag(NBody->getSemiLoc(), DiagID);
12405 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12406 }
12407}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012408
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012409//===--- CHECK: Warn on self move with std::move. -------------------------===//
12410
12411/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
12412void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
12413 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012414 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
12415 return;
12416
Richard Smith51ec0cf2017-02-21 01:17:38 +000012417 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012418 return;
12419
12420 // Strip parens and casts away.
12421 LHSExpr = LHSExpr->IgnoreParenImpCasts();
12422 RHSExpr = RHSExpr->IgnoreParenImpCasts();
12423
12424 // Check for a call expression
12425 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
12426 if (!CE || CE->getNumArgs() != 1)
12427 return;
12428
12429 // Check for a call to std::move
Nico Weberb688d132017-09-28 16:16:39 +000012430 if (!CE->isCallToStdMove())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012431 return;
12432
12433 // Get argument from std::move
12434 RHSExpr = CE->getArg(0);
12435
12436 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12437 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12438
12439 // Two DeclRefExpr's, check that the decls are the same.
12440 if (LHSDeclRef && RHSDeclRef) {
12441 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12442 return;
12443 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12444 RHSDeclRef->getDecl()->getCanonicalDecl())
12445 return;
12446
12447 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12448 << LHSExpr->getSourceRange()
12449 << RHSExpr->getSourceRange();
12450 return;
12451 }
12452
12453 // Member variables require a different approach to check for self moves.
12454 // MemberExpr's are the same if every nested MemberExpr refers to the same
12455 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
12456 // the base Expr's are CXXThisExpr's.
12457 const Expr *LHSBase = LHSExpr;
12458 const Expr *RHSBase = RHSExpr;
12459 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
12460 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
12461 if (!LHSME || !RHSME)
12462 return;
12463
12464 while (LHSME && RHSME) {
12465 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
12466 RHSME->getMemberDecl()->getCanonicalDecl())
12467 return;
12468
12469 LHSBase = LHSME->getBase();
12470 RHSBase = RHSME->getBase();
12471 LHSME = dyn_cast<MemberExpr>(LHSBase);
12472 RHSME = dyn_cast<MemberExpr>(RHSBase);
12473 }
12474
12475 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
12476 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
12477 if (LHSDeclRef && RHSDeclRef) {
12478 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12479 return;
12480 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12481 RHSDeclRef->getDecl()->getCanonicalDecl())
12482 return;
12483
12484 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12485 << LHSExpr->getSourceRange()
12486 << RHSExpr->getSourceRange();
12487 return;
12488 }
12489
12490 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
12491 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12492 << LHSExpr->getSourceRange()
12493 << RHSExpr->getSourceRange();
12494}
12495
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012496//===--- Layout compatibility ----------------------------------------------//
12497
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012498static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012499
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012500/// Check if two enumeration types are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012501static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012502 // C++11 [dcl.enum] p8:
12503 // Two enumeration types are layout-compatible if they have the same
12504 // underlying type.
12505 return ED1->isComplete() && ED2->isComplete() &&
12506 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
12507}
12508
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012509/// Check if two fields are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012510static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
12511 FieldDecl *Field2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012512 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
12513 return false;
12514
12515 if (Field1->isBitField() != Field2->isBitField())
12516 return false;
12517
12518 if (Field1->isBitField()) {
12519 // Make sure that the bit-fields are the same length.
12520 unsigned Bits1 = Field1->getBitWidthValue(C);
12521 unsigned Bits2 = Field2->getBitWidthValue(C);
12522
12523 if (Bits1 != Bits2)
12524 return false;
12525 }
12526
12527 return true;
12528}
12529
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012530/// Check if two standard-layout structs are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012531/// (C++11 [class.mem] p17)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012532static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
12533 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012534 // If both records are C++ classes, check that base classes match.
12535 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
12536 // If one of records is a CXXRecordDecl we are in C++ mode,
12537 // thus the other one is a CXXRecordDecl, too.
12538 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
12539 // Check number of base classes.
12540 if (D1CXX->getNumBases() != D2CXX->getNumBases())
12541 return false;
12542
12543 // Check the base classes.
12544 for (CXXRecordDecl::base_class_const_iterator
12545 Base1 = D1CXX->bases_begin(),
12546 BaseEnd1 = D1CXX->bases_end(),
12547 Base2 = D2CXX->bases_begin();
12548 Base1 != BaseEnd1;
12549 ++Base1, ++Base2) {
12550 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
12551 return false;
12552 }
12553 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
12554 // If only RD2 is a C++ class, it should have zero base classes.
12555 if (D2CXX->getNumBases() > 0)
12556 return false;
12557 }
12558
12559 // Check the fields.
12560 RecordDecl::field_iterator Field2 = RD2->field_begin(),
12561 Field2End = RD2->field_end(),
12562 Field1 = RD1->field_begin(),
12563 Field1End = RD1->field_end();
12564 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
12565 if (!isLayoutCompatible(C, *Field1, *Field2))
12566 return false;
12567 }
12568 if (Field1 != Field1End || Field2 != Field2End)
12569 return false;
12570
12571 return true;
12572}
12573
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012574/// Check if two standard-layout unions are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012575/// (C++11 [class.mem] p18)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012576static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
12577 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012578 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012579 for (auto *Field2 : RD2->fields())
12580 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012581
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012582 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012583 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12584 I = UnmatchedFields.begin(),
12585 E = UnmatchedFields.end();
12586
12587 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012588 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012589 bool Result = UnmatchedFields.erase(*I);
12590 (void) Result;
12591 assert(Result);
12592 break;
12593 }
12594 }
12595 if (I == E)
12596 return false;
12597 }
12598
12599 return UnmatchedFields.empty();
12600}
12601
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012602static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12603 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012604 if (RD1->isUnion() != RD2->isUnion())
12605 return false;
12606
12607 if (RD1->isUnion())
12608 return isLayoutCompatibleUnion(C, RD1, RD2);
12609 else
12610 return isLayoutCompatibleStruct(C, RD1, RD2);
12611}
12612
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012613/// Check if two types are layout-compatible in C++11 sense.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012614static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012615 if (T1.isNull() || T2.isNull())
12616 return false;
12617
12618 // C++11 [basic.types] p11:
12619 // If two types T1 and T2 are the same type, then T1 and T2 are
12620 // layout-compatible types.
12621 if (C.hasSameType(T1, T2))
12622 return true;
12623
12624 T1 = T1.getCanonicalType().getUnqualifiedType();
12625 T2 = T2.getCanonicalType().getUnqualifiedType();
12626
12627 const Type::TypeClass TC1 = T1->getTypeClass();
12628 const Type::TypeClass TC2 = T2->getTypeClass();
12629
12630 if (TC1 != TC2)
12631 return false;
12632
12633 if (TC1 == Type::Enum) {
12634 return isLayoutCompatible(C,
12635 cast<EnumType>(T1)->getDecl(),
12636 cast<EnumType>(T2)->getDecl());
12637 } else if (TC1 == Type::Record) {
12638 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12639 return false;
12640
12641 return isLayoutCompatible(C,
12642 cast<RecordType>(T1)->getDecl(),
12643 cast<RecordType>(T2)->getDecl());
12644 }
12645
12646 return false;
12647}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012648
12649//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12650
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012651/// Given a type tag expression find the type tag itself.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012652///
12653/// \param TypeExpr Type tag expression, as it appears in user's code.
12654///
12655/// \param VD Declaration of an identifier that appears in a type tag.
12656///
12657/// \param MagicValue Type tag magic value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012658static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12659 const ValueDecl **VD, uint64_t *MagicValue) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012660 while(true) {
12661 if (!TypeExpr)
12662 return false;
12663
12664 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12665
12666 switch (TypeExpr->getStmtClass()) {
12667 case Stmt::UnaryOperatorClass: {
12668 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12669 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12670 TypeExpr = UO->getSubExpr();
12671 continue;
12672 }
12673 return false;
12674 }
12675
12676 case Stmt::DeclRefExprClass: {
12677 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12678 *VD = DRE->getDecl();
12679 return true;
12680 }
12681
12682 case Stmt::IntegerLiteralClass: {
12683 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12684 llvm::APInt MagicValueAPInt = IL->getValue();
12685 if (MagicValueAPInt.getActiveBits() <= 64) {
12686 *MagicValue = MagicValueAPInt.getZExtValue();
12687 return true;
12688 } else
12689 return false;
12690 }
12691
12692 case Stmt::BinaryConditionalOperatorClass:
12693 case Stmt::ConditionalOperatorClass: {
12694 const AbstractConditionalOperator *ACO =
12695 cast<AbstractConditionalOperator>(TypeExpr);
12696 bool Result;
12697 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12698 if (Result)
12699 TypeExpr = ACO->getTrueExpr();
12700 else
12701 TypeExpr = ACO->getFalseExpr();
12702 continue;
12703 }
12704 return false;
12705 }
12706
12707 case Stmt::BinaryOperatorClass: {
12708 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12709 if (BO->getOpcode() == BO_Comma) {
12710 TypeExpr = BO->getRHS();
12711 continue;
12712 }
12713 return false;
12714 }
12715
12716 default:
12717 return false;
12718 }
12719 }
12720}
12721
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012722/// Retrieve the C type corresponding to type tag TypeExpr.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012723///
12724/// \param TypeExpr Expression that specifies a type tag.
12725///
12726/// \param MagicValues Registered magic values.
12727///
12728/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12729/// kind.
12730///
12731/// \param TypeInfo Information about the corresponding C type.
12732///
12733/// \returns true if the corresponding C type was found.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012734static bool GetMatchingCType(
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012735 const IdentifierInfo *ArgumentKind,
12736 const Expr *TypeExpr, const ASTContext &Ctx,
12737 const llvm::DenseMap<Sema::TypeTagMagicValue,
12738 Sema::TypeTagData> *MagicValues,
12739 bool &FoundWrongKind,
12740 Sema::TypeTagData &TypeInfo) {
12741 FoundWrongKind = false;
12742
12743 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000012744 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012745
12746 uint64_t MagicValue;
12747
12748 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12749 return false;
12750
12751 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000012752 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012753 if (I->getArgumentKind() != ArgumentKind) {
12754 FoundWrongKind = true;
12755 return false;
12756 }
12757 TypeInfo.Type = I->getMatchingCType();
12758 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12759 TypeInfo.MustBeNull = I->getMustBeNull();
12760 return true;
12761 }
12762 return false;
12763 }
12764
12765 if (!MagicValues)
12766 return false;
12767
12768 llvm::DenseMap<Sema::TypeTagMagicValue,
12769 Sema::TypeTagData>::const_iterator I =
12770 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12771 if (I == MagicValues->end())
12772 return false;
12773
12774 TypeInfo = I->second;
12775 return true;
12776}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012777
12778void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12779 uint64_t MagicValue, QualType Type,
12780 bool LayoutCompatible,
12781 bool MustBeNull) {
12782 if (!TypeTagForDatatypeMagicValues)
12783 TypeTagForDatatypeMagicValues.reset(
12784 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12785
12786 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12787 (*TypeTagForDatatypeMagicValues)[Magic] =
12788 TypeTagData(Type, LayoutCompatible, MustBeNull);
12789}
12790
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012791static bool IsSameCharType(QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012792 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12793 if (!BT1)
12794 return false;
12795
12796 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12797 if (!BT2)
12798 return false;
12799
12800 BuiltinType::Kind T1Kind = BT1->getKind();
12801 BuiltinType::Kind T2Kind = BT2->getKind();
12802
12803 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
12804 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
12805 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12806 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12807}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012808
12809void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012810 const ArrayRef<const Expr *> ExprArgs,
12811 SourceLocation CallSiteLoc) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012812 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12813 bool IsPointerAttr = Attr->getIsPointer();
12814
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012815 // Retrieve the argument representing the 'type_tag'.
Joel E. Denny81508102018-03-13 14:51:22 +000012816 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
12817 if (TypeTagIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012818 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012819 << 0 << Attr->getTypeTagIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012820 return;
12821 }
Joel E. Denny81508102018-03-13 14:51:22 +000012822 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012823 bool FoundWrongKind;
12824 TypeTagData TypeInfo;
12825 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12826 TypeTagForDatatypeMagicValues.get(),
12827 FoundWrongKind, TypeInfo)) {
12828 if (FoundWrongKind)
12829 Diag(TypeTagExpr->getExprLoc(),
12830 diag::warn_type_tag_for_datatype_wrong_kind)
12831 << TypeTagExpr->getSourceRange();
12832 return;
12833 }
12834
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012835 // Retrieve the argument representing the 'arg_idx'.
Joel E. Denny81508102018-03-13 14:51:22 +000012836 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
12837 if (ArgumentIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012838 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012839 << 1 << Attr->getArgumentIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012840 return;
12841 }
Joel E. Denny81508102018-03-13 14:51:22 +000012842 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012843 if (IsPointerAttr) {
12844 // Skip implicit cast of pointer to `void *' (as a function argument).
12845 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000012846 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000012847 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012848 ArgumentExpr = ICE->getSubExpr();
12849 }
12850 QualType ArgumentType = ArgumentExpr->getType();
12851
12852 // Passing a `void*' pointer shouldn't trigger a warning.
12853 if (IsPointerAttr && ArgumentType->isVoidPointerType())
12854 return;
12855
12856 if (TypeInfo.MustBeNull) {
12857 // Type tag with matching void type requires a null pointer.
12858 if (!ArgumentExpr->isNullPointerConstant(Context,
12859 Expr::NPC_ValueDependentIsNotNull)) {
12860 Diag(ArgumentExpr->getExprLoc(),
12861 diag::warn_type_safety_null_pointer_required)
12862 << ArgumentKind->getName()
12863 << ArgumentExpr->getSourceRange()
12864 << TypeTagExpr->getSourceRange();
12865 }
12866 return;
12867 }
12868
12869 QualType RequiredType = TypeInfo.Type;
12870 if (IsPointerAttr)
12871 RequiredType = Context.getPointerType(RequiredType);
12872
12873 bool mismatch = false;
12874 if (!TypeInfo.LayoutCompatible) {
12875 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12876
12877 // C++11 [basic.fundamental] p1:
12878 // Plain char, signed char, and unsigned char are three distinct types.
12879 //
12880 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12881 // char' depending on the current char signedness mode.
12882 if (mismatch)
12883 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12884 RequiredType->getPointeeType())) ||
12885 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12886 mismatch = false;
12887 } else
12888 if (IsPointerAttr)
12889 mismatch = !isLayoutCompatible(Context,
12890 ArgumentType->getPointeeType(),
12891 RequiredType->getPointeeType());
12892 else
12893 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12894
12895 if (mismatch)
12896 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012897 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012898 << TypeInfo.LayoutCompatible << RequiredType
12899 << ArgumentExpr->getSourceRange()
12900 << TypeTagExpr->getSourceRange();
12901}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012902
12903void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12904 CharUnits Alignment) {
12905 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12906}
12907
12908void Sema::DiagnoseMisalignedMembers() {
12909 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000012910 const NamedDecl *ND = m.RD;
12911 if (ND->getName().empty()) {
12912 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12913 ND = TD;
12914 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012915 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000012916 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012917 }
12918 MisalignedMembers.clear();
12919}
12920
12921void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012922 E = E->IgnoreParens();
12923 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012924 return;
12925 if (isa<UnaryOperator>(E) &&
12926 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12927 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12928 if (isa<MemberExpr>(Op)) {
12929 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12930 MisalignedMember(Op));
12931 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012932 (T->isIntegerType() ||
Roger Ferrer Ibanezd80d6c52017-12-07 09:23:50 +000012933 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
12934 Context.getTypeAlignInChars(
12935 T->getPointeeType()) <= MA->Alignment))))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012936 MisalignedMembers.erase(MA);
12937 }
12938 }
12939}
12940
12941void Sema::RefersToMemberWithReducedAlignment(
12942 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000012943 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12944 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012945 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012946 if (!ME)
12947 return;
12948
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000012949 // No need to check expressions with an __unaligned-qualified type.
12950 if (E->getType().getQualifiers().hasUnaligned())
12951 return;
12952
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012953 // For a chain of MemberExpr like "a.b.c.d" this list
12954 // will keep FieldDecl's like [d, c, b].
12955 SmallVector<FieldDecl *, 4> ReverseMemberChain;
12956 const MemberExpr *TopME = nullptr;
12957 bool AnyIsPacked = false;
12958 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012959 QualType BaseType = ME->getBase()->getType();
12960 if (ME->isArrow())
12961 BaseType = BaseType->getPointeeType();
12962 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000012963 if (RD->isInvalidDecl())
12964 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012965
12966 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012967 auto *FD = dyn_cast<FieldDecl>(MD);
12968 // We do not care about non-data members.
12969 if (!FD || FD->isInvalidDecl())
12970 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012971
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012972 AnyIsPacked =
12973 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12974 ReverseMemberChain.push_back(FD);
12975
12976 TopME = ME;
12977 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12978 } while (ME);
12979 assert(TopME && "We did not compute a topmost MemberExpr!");
12980
12981 // Not the scope of this diagnostic.
12982 if (!AnyIsPacked)
12983 return;
12984
12985 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12986 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12987 // TODO: The innermost base of the member expression may be too complicated.
12988 // For now, just disregard these cases. This is left for future
12989 // improvement.
12990 if (!DRE && !isa<CXXThisExpr>(TopBase))
12991 return;
12992
12993 // Alignment expected by the whole expression.
12994 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12995
12996 // No need to do anything else with this case.
12997 if (ExpectedAlignment.isOne())
12998 return;
12999
13000 // Synthesize offset of the whole access.
13001 CharUnits Offset;
13002 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
13003 I++) {
13004 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
13005 }
13006
13007 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
13008 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
13009 ReverseMemberChain.back()->getParent()->getTypeForDecl());
13010
13011 // The base expression of the innermost MemberExpr may give
13012 // stronger guarantees than the class containing the member.
13013 if (DRE && !TopME->isArrow()) {
13014 const ValueDecl *VD = DRE->getDecl();
13015 if (!VD->getType()->isReferenceType())
13016 CompleteObjectAlignment =
13017 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
13018 }
13019
13020 // Check if the synthesized offset fulfills the alignment.
13021 if (Offset % ExpectedAlignment != 0 ||
13022 // It may fulfill the offset it but the effective alignment may still be
13023 // lower than the expected expression alignment.
13024 CompleteObjectAlignment < ExpectedAlignment) {
13025 // If this happens, we want to determine a sensible culprit of this.
13026 // Intuitively, watching the chain of member expressions from right to
13027 // left, we start with the required alignment (as required by the field
13028 // type) but some packed attribute in that chain has reduced the alignment.
13029 // It may happen that another packed structure increases it again. But if
13030 // we are here such increase has not been enough. So pointing the first
13031 // FieldDecl that either is packed or else its RecordDecl is,
13032 // seems reasonable.
13033 FieldDecl *FD = nullptr;
13034 CharUnits Alignment;
13035 for (FieldDecl *FDI : ReverseMemberChain) {
13036 if (FDI->hasAttr<PackedAttr>() ||
13037 FDI->getParent()->hasAttr<PackedAttr>()) {
13038 FD = FDI;
13039 Alignment = std::min(
13040 Context.getTypeAlignInChars(FD->getType()),
13041 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
13042 break;
13043 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013044 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013045 assert(FD && "We did not find a packed FieldDecl!");
13046 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013047 }
13048}
13049
13050void Sema::CheckAddressOfPackedMember(Expr *rhs) {
13051 using namespace std::placeholders;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013052
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013053 RefersToMemberWithReducedAlignment(
13054 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
13055 _2, _3, _4));
13056}